1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus MCP SDK package.
7: *
8: * (c) 2025 John Paul E. Balandan, CPA <paulbalandan@gmail.com>
9: *
10: * For the full copyright and license information, please view
11: * the LICENSE file that was distributed with this source code.
12: */
13:
14: namespace Nexus\Mcp\Schema\Elicitation\Builder;
15:
16: use Nexus\Mcp\Schema\Elicitation\StringSchema;
17:
18: /**
19: * Fluent builder for {@see StringSchema}.
20: *
21: * @extends PrimitiveSchemaDefinitionBuilder<string, array{
22: * type: 'string',
23: * description?: non-empty-string,
24: * title?: non-empty-string,
25: * minLength?: int<0, max>,
26: * maxLength?: int<0, max>,
27: * format?: 'date'|'date-time'|'email'|'uri',
28: * default?: string,
29: * }>
30: */
31: final class StringSchemaBuilder extends PrimitiveSchemaDefinitionBuilder
32: {
33: /**
34: * @var null|int<0, max>
35: */
36: private ?int $minLength = null;
37:
38: /**
39: * @var null|int<0, max>
40: */
41: private ?int $maxLength = null;
42:
43: /**
44: * @var null|'date'|'date-time'|'email'|'uri'
45: */
46: private ?string $format = null;
47:
48: public function minLength(int $minLength): self
49: {
50: if ($minLength < 0) {
51: throw new \InvalidArgumentException('The minimum length must be a non-negative integer.');
52: }
53:
54: $this->minLength = $minLength;
55:
56: return $this;
57: }
58:
59: public function maxLength(int $maxLength): self
60: {
61: if ($maxLength < 0) {
62: throw new \InvalidArgumentException('The maximum length must be a non-negative integer.');
63: }
64:
65: $this->maxLength = $maxLength;
66:
67: return $this;
68: }
69:
70: public function format(string $format): self
71: {
72: $allowedFormats = ['date', 'date-time', 'email', 'uri'];
73:
74: if (! \in_array($format, $allowedFormats, true)) {
75: throw new \InvalidArgumentException(\sprintf(
76: 'The format must be one of "%s".',
77: implode('", "', $allowedFormats),
78: ));
79: }
80:
81: $this->format = $format;
82:
83: return $this;
84: }
85:
86: #[\Override]
87: public function build(): StringSchema
88: {
89: if (isset($this->minLength, $this->maxLength) && $this->minLength > $this->maxLength) {
90: throw new \LogicException('The minimum length cannot be greater than the maximum length.');
91: }
92:
93: if (isset($this->default, $this->minLength) && \strlen($this->default) < $this->minLength) {
94: throw new \LogicException('The default value length cannot be less than the minimum length.');
95: }
96:
97: if (isset($this->default, $this->maxLength) && \strlen($this->default) > $this->maxLength) {
98: throw new \LogicException('The default value length cannot be greater than the maximum length.');
99: }
100:
101: return new StringSchema(
102: $this->description,
103: $this->title,
104: $this->minLength,
105: $this->maxLength,
106: $this->format,
107: $this->default,
108: );
109: }
110: }
111: