├── src └── Schema │ ├── DynamicParameter.php │ ├── MergeMode.php │ ├── Schema.php │ ├── ValidationException.php │ ├── Context.php │ ├── Processor.php │ ├── Message.php │ ├── Elements │ ├── AnyOf.php │ ├── Base.php │ ├── Structure.php │ └── Type.php │ ├── Expect.php │ └── Helpers.php ├── composer.json ├── license.md └── readme.md /src/Schema/DynamicParameter.php: -------------------------------------------------------------------------------- 1 | toString()); 30 | $this->messages = $messages; 31 | } 32 | 33 | 34 | /** 35 | * @return string[] 36 | */ 37 | public function getMessages(): array 38 | { 39 | $res = []; 40 | foreach ($this->messages as $message) { 41 | $res[] = $message->toString(); 42 | } 43 | 44 | return $res; 45 | } 46 | 47 | 48 | /** 49 | * @return Message[] 50 | */ 51 | public function getMessageObjects(): array 52 | { 53 | return $this->messages; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Schema/Context.php: -------------------------------------------------------------------------------- 1 | isKey; 37 | return $this->errors[] = new Message($message, $code, $this->path, $variables); 38 | } 39 | 40 | 41 | public function addWarning(string $message, string $code, array $variables = []): Message 42 | { 43 | return $this->warnings[] = new Message($message, $code, $this->path, $variables); 44 | } 45 | 46 | 47 | /** @return \Closure(): bool */ 48 | public function createChecker(): \Closure 49 | { 50 | $count = count($this->errors); 51 | return fn(): bool => $count === count($this->errors); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Schema/Processor.php: -------------------------------------------------------------------------------- 1 | skipDefaults = $value; 28 | } 29 | 30 | 31 | /** 32 | * Normalizes and validates data. Result is a clean completed data. 33 | * @throws ValidationException 34 | */ 35 | public function process(Schema $schema, mixed $data): mixed 36 | { 37 | $this->createContext(); 38 | $data = $schema->normalize($data, $this->context); 39 | $this->throwsErrors(); 40 | $data = $schema->complete($data, $this->context); 41 | $this->throwsErrors(); 42 | return $data; 43 | } 44 | 45 | 46 | /** 47 | * Normalizes and validates and merges multiple data. Result is a clean completed data. 48 | * @throws ValidationException 49 | */ 50 | public function processMultiple(Schema $schema, array $dataset): mixed 51 | { 52 | $this->createContext(); 53 | $flatten = null; 54 | $first = true; 55 | foreach ($dataset as $data) { 56 | $data = $schema->normalize($data, $this->context); 57 | $this->throwsErrors(); 58 | $flatten = $first ? $data : $schema->merge($data, $flatten); 59 | $first = false; 60 | } 61 | 62 | $data = $schema->complete($flatten, $this->context); 63 | $this->throwsErrors(); 64 | return $data; 65 | } 66 | 67 | 68 | /** 69 | * @return string[] 70 | */ 71 | public function getWarnings(): array 72 | { 73 | $res = []; 74 | foreach ($this->context->warnings as $message) { 75 | $res[] = $message->toString(); 76 | } 77 | 78 | return $res; 79 | } 80 | 81 | 82 | private function throwsErrors(): void 83 | { 84 | if ($this->context->errors) { 85 | throw new ValidationException(null, $this->context->errors); 86 | } 87 | } 88 | 89 | 90 | private function createContext(): void 91 | { 92 | $this->context = new Context; 93 | $this->context->skipDefaults = $this->skipDefaults; 94 | Nette\Utils\Arrays::invoke($this->onNewContext, $this->context); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | Licenses 2 | ======== 3 | 4 | Good news! You may use Nette Framework under the terms of either 5 | the New BSD License or the GNU General Public License (GPL) version 2 or 3. 6 | 7 | The BSD License is recommended for most projects. It is easy to understand and it 8 | places almost no restrictions on what you can do with the framework. If the GPL 9 | fits better to your project, you can use the framework under this license. 10 | 11 | You don't have to notify anyone which license you are using. You can freely 12 | use Nette Framework in commercial projects as long as the copyright header 13 | remains intact. 14 | 15 | Please be advised that the name "Nette Framework" is a protected trademark and its 16 | usage has some limitations. So please do not use word "Nette" in the name of your 17 | project or top-level domain, and choose a name that stands on its own merits. 18 | If your stuff is good, it will not take long to establish a reputation for yourselves. 19 | 20 | 21 | New BSD License 22 | --------------- 23 | 24 | Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) 25 | All rights reserved. 26 | 27 | Redistribution and use in source and binary forms, with or without modification, 28 | are permitted provided that the following conditions are met: 29 | 30 | * Redistributions of source code must retain the above copyright notice, 31 | this list of conditions and the following disclaimer. 32 | 33 | * Redistributions in binary form must reproduce the above copyright notice, 34 | this list of conditions and the following disclaimer in the documentation 35 | and/or other materials provided with the distribution. 36 | 37 | * Neither the name of "Nette Framework" nor the names of its contributors 38 | may be used to endorse or promote products derived from this software 39 | without specific prior written permission. 40 | 41 | This software is provided by the copyright holders and contributors "as is" and 42 | any express or implied warranties, including, but not limited to, the implied 43 | warranties of merchantability and fitness for a particular purpose are 44 | disclaimed. In no event shall the copyright owner or contributors be liable for 45 | any direct, indirect, incidental, special, exemplary, or consequential damages 46 | (including, but not limited to, procurement of substitute goods or services; 47 | loss of use, data, or profits; or business interruption) however caused and on 48 | any theory of liability, whether in contract, strict liability, or tort 49 | (including negligence or otherwise) arising in any way out of the use of this 50 | software, even if advised of the possibility of such damage. 51 | 52 | 53 | GNU General Public License 54 | -------------------------- 55 | 56 | GPL licenses are very very long, so instead of including them here we offer 57 | you URLs with full text: 58 | 59 | - [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) 60 | - [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) 61 | -------------------------------------------------------------------------------- /src/Schema/Message.php: -------------------------------------------------------------------------------- 1 | message = $message; 79 | $this->code = $code; 80 | $this->path = $path; 81 | $this->variables = $variables; 82 | } 83 | 84 | 85 | public function toString(): string 86 | { 87 | $vars = $this->variables; 88 | $vars['label'] = empty($vars['isKey']) ? 'item' : 'key of item'; 89 | $vars['path'] = $this->path 90 | ? "'" . implode("\u{a0}›\u{a0}", $this->path) . "'" 91 | : null; 92 | $vars['value'] = Helpers::formatValue($vars['value'] ?? null); 93 | 94 | return preg_replace_callback('~( ?)%(\w+)%~', function ($m) use ($vars) { 95 | [, $space, $key] = $m; 96 | return $vars[$key] === null ? '' : $space . $vars[$key]; 97 | }, $this->message) ?? throw new Nette\InvalidStateException(preg_last_error_msg()); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/Schema/Elements/AnyOf.php: -------------------------------------------------------------------------------- 1 | set = $set; 33 | } 34 | 35 | 36 | public function firstIsDefault(): self 37 | { 38 | $this->default = $this->set[0]; 39 | return $this; 40 | } 41 | 42 | 43 | public function nullable(): self 44 | { 45 | $this->set[] = null; 46 | return $this; 47 | } 48 | 49 | 50 | public function dynamic(): self 51 | { 52 | $this->set[] = new Type(Nette\Schema\DynamicParameter::class); 53 | return $this; 54 | } 55 | 56 | 57 | /********************* processing ****************d*g**/ 58 | 59 | 60 | public function normalize(mixed $value, Context $context): mixed 61 | { 62 | return $this->doNormalize($value, $context); 63 | } 64 | 65 | 66 | public function merge(mixed $value, mixed $base): mixed 67 | { 68 | return Helpers::merge($value, $base); 69 | } 70 | 71 | 72 | public function complete(mixed $value, Context $context): mixed 73 | { 74 | $isOk = $context->createChecker(); 75 | $value = $this->findAlternative($value, $context); 76 | $isOk() && $value = $this->doTransform($value, $context); 77 | return $isOk() ? $value : null; 78 | } 79 | 80 | 81 | private function findAlternative(mixed $value, Context $context): mixed 82 | { 83 | $expecteds = $innerErrors = []; 84 | foreach ($this->set as $item) { 85 | if ($item instanceof Schema) { 86 | $dolly = new Context; 87 | $dolly->path = $context->path; 88 | $res = $item->complete($item->normalize($value, $dolly), $dolly); 89 | if (!$dolly->errors) { 90 | $context->warnings = array_merge($context->warnings, $dolly->warnings); 91 | return $res; 92 | } 93 | 94 | foreach ($dolly->errors as $error) { 95 | if ($error->path !== $context->path || empty($error->variables['expected'])) { 96 | $innerErrors[] = $error; 97 | } else { 98 | $expecteds[] = $error->variables['expected']; 99 | } 100 | } 101 | } else { 102 | if ($item === $value) { 103 | return $value; 104 | } 105 | 106 | $expecteds[] = Nette\Schema\Helpers::formatValue($item); 107 | } 108 | } 109 | 110 | if ($innerErrors) { 111 | $context->errors = array_merge($context->errors, $innerErrors); 112 | } else { 113 | $context->addError( 114 | 'The %label% %path% expects to be %expected%, %value% given.', 115 | Nette\Schema\Message::TypeMismatch, 116 | [ 117 | 'value' => $value, 118 | 'expected' => implode('|', array_unique($expecteds)), 119 | ], 120 | ); 121 | } 122 | 123 | return null; 124 | } 125 | 126 | 127 | public function completeDefault(Context $context): mixed 128 | { 129 | if ($this->required) { 130 | $context->addError( 131 | 'The mandatory item %path% is missing.', 132 | Nette\Schema\Message::MissingItem, 133 | ); 134 | return null; 135 | } 136 | 137 | if ($this->default instanceof Schema) { 138 | return $this->default->completeDefault($context); 139 | } 140 | 141 | return $this->default; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/Schema/Expect.php: -------------------------------------------------------------------------------- 1 | default($args[0]); 40 | } 41 | 42 | return $type; 43 | } 44 | 45 | 46 | public static function type(string $type): Type 47 | { 48 | return new Type($type); 49 | } 50 | 51 | 52 | public static function anyOf(mixed ...$set): AnyOf 53 | { 54 | return new AnyOf(...$set); 55 | } 56 | 57 | 58 | /** 59 | * @param Schema[] $shape 60 | */ 61 | public static function structure(array $shape): Structure 62 | { 63 | return new Structure($shape); 64 | } 65 | 66 | 67 | public static function from(object|string $object, array $items = []): Structure 68 | { 69 | $ro = new \ReflectionClass($object); 70 | $props = $ro->hasMethod('__construct') 71 | ? $ro->getMethod('__construct')->getParameters() 72 | : $ro->getProperties(); 73 | 74 | foreach ($props as $prop) { 75 | \assert($prop instanceof \ReflectionProperty || $prop instanceof \ReflectionParameter); 76 | if ($item = &$items[$prop->getName()]) { 77 | continue; 78 | } 79 | 80 | $item = new Type($propType = (string) (Nette\Utils\Type::fromReflection($prop) ?? 'mixed')); 81 | if (class_exists($propType)) { 82 | $item = static::from($propType); 83 | } 84 | 85 | $hasDefault = match (true) { 86 | $prop instanceof \ReflectionParameter => $prop->isOptional(), 87 | is_object($object) => $prop->isInitialized($object), 88 | default => $prop->hasDefaultValue(), 89 | }; 90 | if ($hasDefault) { 91 | $default = match (true) { 92 | $prop instanceof \ReflectionParameter => $prop->getDefaultValue(), 93 | is_object($object) => $prop->getValue($object), 94 | default => $prop->getDefaultValue(), 95 | }; 96 | if (is_object($default)) { 97 | $item = static::from($default); 98 | } else { 99 | $item->default($default); 100 | } 101 | } else { 102 | $item->required(); 103 | } 104 | } 105 | 106 | return (new Structure($items))->castTo($ro->getName()); 107 | } 108 | 109 | 110 | /** 111 | * @param mixed[] $shape 112 | */ 113 | public static function array(?array $shape = []): Structure|Type 114 | { 115 | return Nette\Utils\Arrays::first($shape ?? []) instanceof Schema 116 | ? (new Structure($shape))->castTo('array') 117 | : (new Type('array'))->default($shape); 118 | } 119 | 120 | 121 | public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): Type 122 | { 123 | return (new Type('array'))->items($valueType, $keyType); 124 | } 125 | 126 | 127 | public static function listOf(string|Schema $type): Type 128 | { 129 | return (new Type('list'))->items($type); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/Schema/Elements/Base.php: -------------------------------------------------------------------------------- 1 | default = $value; 37 | return $this; 38 | } 39 | 40 | 41 | public function required(bool $state = true): self 42 | { 43 | $this->required = $state; 44 | return $this; 45 | } 46 | 47 | 48 | public function before(callable $handler): self 49 | { 50 | $this->before = $handler; 51 | return $this; 52 | } 53 | 54 | 55 | public function castTo(string $type): self 56 | { 57 | return $this->transform(Helpers::getCastStrategy($type)); 58 | } 59 | 60 | 61 | public function transform(callable $handler): self 62 | { 63 | $this->transforms[] = $handler; 64 | return $this; 65 | } 66 | 67 | 68 | public function assert(callable $handler, ?string $description = null): self 69 | { 70 | $expected = $description ?: (is_string($handler) ? "$handler()" : '#' . count($this->transforms)); 71 | return $this->transform(function ($value, Context $context) use ($handler, $description, $expected) { 72 | if ($handler($value)) { 73 | return $value; 74 | } 75 | $context->addError( 76 | 'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.', 77 | Nette\Schema\Message::FailedAssertion, 78 | ['value' => $value, 'assertion' => $expected], 79 | ); 80 | }); 81 | } 82 | 83 | 84 | /** Marks as deprecated */ 85 | public function deprecated(string $message = 'The item %path% is deprecated.'): self 86 | { 87 | $this->deprecated = $message; 88 | return $this; 89 | } 90 | 91 | 92 | public function completeDefault(Context $context): mixed 93 | { 94 | if ($this->required) { 95 | $context->addError( 96 | 'The mandatory item %path% is missing.', 97 | Nette\Schema\Message::MissingItem, 98 | ); 99 | return null; 100 | } 101 | 102 | return $this->default; 103 | } 104 | 105 | 106 | public function doNormalize(mixed $value, Context $context): mixed 107 | { 108 | if ($this->before) { 109 | $value = ($this->before)($value); 110 | } 111 | 112 | return $value; 113 | } 114 | 115 | 116 | private function doDeprecation(Context $context): void 117 | { 118 | if ($this->deprecated !== null) { 119 | $context->addWarning( 120 | $this->deprecated, 121 | Nette\Schema\Message::Deprecated, 122 | ); 123 | } 124 | } 125 | 126 | 127 | private function doTransform(mixed $value, Context $context): mixed 128 | { 129 | $isOk = $context->createChecker(); 130 | foreach ($this->transforms as $handler) { 131 | $value = $handler($value, $context); 132 | if (!$isOk()) { 133 | return null; 134 | } 135 | } 136 | return $value; 137 | } 138 | 139 | 140 | #[\Deprecated('use Nette\Schema\Validators::validateType()')] 141 | private function doValidate(mixed $value, string $expected, Context $context): bool 142 | { 143 | $isOk = $context->createChecker(); 144 | Helpers::validateType($value, $expected, $context); 145 | return $isOk(); 146 | } 147 | 148 | 149 | #[\Deprecated('use Nette\Schema\Validators::validateRange()')] 150 | private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool 151 | { 152 | $isOk = $context->createChecker(); 153 | Helpers::validateRange($value, $range, $context, $types); 154 | return $isOk(); 155 | } 156 | 157 | 158 | #[\Deprecated('use doTransform()')] 159 | private function doFinalize(mixed $value, Context $context): mixed 160 | { 161 | return $this->doTransform($value, $context); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/Schema/Helpers.php: -------------------------------------------------------------------------------- 1 | $val) { 39 | if ($key === $index) { 40 | $base[] = $val; 41 | $index++; 42 | } else { 43 | $base[$key] = static::merge($val, $base[$key] ?? null); 44 | } 45 | } 46 | 47 | return $base; 48 | 49 | } elseif ($value === null && is_array($base)) { 50 | return $base; 51 | 52 | } else { 53 | return $value; 54 | } 55 | } 56 | 57 | 58 | public static function formatValue(mixed $value): string 59 | { 60 | if ($value instanceof DynamicParameter) { 61 | return 'dynamic'; 62 | } elseif (is_object($value)) { 63 | return 'object ' . $value::class; 64 | } elseif (is_string($value)) { 65 | return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'"; 66 | } elseif (is_scalar($value)) { 67 | return var_export($value, return: true); 68 | } else { 69 | return get_debug_type($value); 70 | } 71 | } 72 | 73 | 74 | public static function validateType(mixed $value, string $expected, Context $context): void 75 | { 76 | if (!Nette\Utils\Validators::is($value, $expected)) { 77 | $expected = str_replace(DynamicParameter::class . '|', '', $expected); 78 | $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); 79 | $context->addError( 80 | 'The %label% %path% expects to be %expected%, %value% given.', 81 | Message::TypeMismatch, 82 | ['value' => $value, 'expected' => $expected], 83 | ); 84 | } 85 | } 86 | 87 | 88 | public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void 89 | { 90 | if (is_array($value) || is_string($value)) { 91 | [$length, $label] = is_array($value) 92 | ? [count($value), 'items'] 93 | : (in_array('unicode', explode('|', $types), true) 94 | ? [Nette\Utils\Strings::length($value), 'characters'] 95 | : [strlen($value), 'bytes']); 96 | 97 | if (!self::isInRange($length, $range)) { 98 | $context->addError( 99 | "The length of %label% %path% expects to be in range %expected%, %length% $label given.", 100 | Message::LengthOutOfRange, 101 | ['value' => $value, 'length' => $length, 'expected' => implode('..', $range)], 102 | ); 103 | } 104 | } elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) { 105 | $context->addError( 106 | 'The %label% %path% expects to be in range %expected%, %value% given.', 107 | Message::ValueOutOfRange, 108 | ['value' => $value, 'expected' => implode('..', $range)], 109 | ); 110 | } 111 | } 112 | 113 | 114 | public static function isInRange(mixed $value, array $range): bool 115 | { 116 | return ($range[0] === null || $value >= $range[0]) 117 | && ($range[1] === null || $value <= $range[1]); 118 | } 119 | 120 | 121 | public static function validatePattern(string $value, string $pattern, Context $context): void 122 | { 123 | if (!preg_match("\x01^(?:$pattern)$\x01Du", $value)) { 124 | $context->addError( 125 | "The %label% %path% expects to match pattern '%pattern%', %value% given.", 126 | Message::PatternMismatch, 127 | ['value' => $value, 'pattern' => $pattern], 128 | ); 129 | } 130 | } 131 | 132 | 133 | public static function getCastStrategy(string $type): \Closure 134 | { 135 | if (Nette\Utils\Validators::isBuiltinType($type)) { 136 | return static function ($value) use ($type) { 137 | settype($value, $type); 138 | return $value; 139 | }; 140 | } elseif (method_exists($type, '__construct')) { 141 | return static fn($value) => is_array($value) || $value instanceof \stdClass 142 | ? new $type(...(array) $value) 143 | : new $type($value); 144 | } else { 145 | return static fn($value) => Nette\Utils\Arrays::toObject((array) $value, new $type); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/Schema/Elements/Structure.php: -------------------------------------------------------------------------------- 1 | items = $shape; 41 | $this->castTo('object'); 42 | $this->required = true; 43 | } 44 | 45 | 46 | public function default(mixed $value): self 47 | { 48 | throw new Nette\InvalidStateException('Structure cannot have default value.'); 49 | } 50 | 51 | 52 | public function min(?int $min): self 53 | { 54 | $this->range[0] = $min; 55 | return $this; 56 | } 57 | 58 | 59 | public function max(?int $max): self 60 | { 61 | $this->range[1] = $max; 62 | return $this; 63 | } 64 | 65 | 66 | public function otherItems(string|Schema $type = 'mixed'): self 67 | { 68 | $this->otherItems = $type instanceof Schema ? $type : new Type($type); 69 | return $this; 70 | } 71 | 72 | 73 | public function skipDefaults(bool $state = true): self 74 | { 75 | $this->skipDefaults = $state; 76 | return $this; 77 | } 78 | 79 | 80 | public function extend(array|self $shape): self 81 | { 82 | $shape = $shape instanceof self ? $shape->items : $shape; 83 | return new self(array_merge($this->items, $shape)); 84 | } 85 | 86 | 87 | public function getShape(): array 88 | { 89 | return $this->items; 90 | } 91 | 92 | 93 | /********************* processing ****************d*g**/ 94 | 95 | 96 | public function normalize(mixed $value, Context $context): mixed 97 | { 98 | $value = $this->doNormalize($value, $context); 99 | if (is_object($value)) { 100 | $value = (array) $value; 101 | } 102 | 103 | if (is_array($value)) { 104 | foreach ($value as $key => $val) { 105 | $itemSchema = $this->items[$key] ?? $this->otherItems; 106 | if ($itemSchema) { 107 | $context->path[] = $key; 108 | $value[$key] = $itemSchema->normalize($val, $context); 109 | array_pop($context->path); 110 | } 111 | } 112 | } 113 | 114 | return $value; 115 | } 116 | 117 | 118 | public function merge(mixed $value, mixed $base): mixed 119 | { 120 | if (is_array($value) && isset($value[Helpers::PreventMerging])) { 121 | unset($value[Helpers::PreventMerging]); 122 | $base = null; 123 | } 124 | 125 | if (is_array($value) && is_array($base)) { 126 | $index = $this->otherItems === null ? null : 0; 127 | foreach ($value as $key => $val) { 128 | if ($key === $index) { 129 | $base[] = $val; 130 | $index++; 131 | } else { 132 | $base[$key] = array_key_exists($key, $base) && ($itemSchema = $this->items[$key] ?? $this->otherItems) 133 | ? $itemSchema->merge($val, $base[$key]) 134 | : $val; 135 | } 136 | } 137 | 138 | return $base; 139 | } 140 | 141 | return $value ?? $base; 142 | } 143 | 144 | 145 | public function complete(mixed $value, Context $context): mixed 146 | { 147 | if ($value === null) { 148 | $value = []; // is unable to distinguish null from array in NEON 149 | } 150 | 151 | $this->doDeprecation($context); 152 | 153 | $isOk = $context->createChecker(); 154 | Helpers::validateType($value, 'array', $context); 155 | $isOk() && Helpers::validateRange($value, $this->range, $context); 156 | $isOk() && $this->validateItems($value, $context); 157 | $isOk() && $value = $this->doTransform($value, $context); 158 | return $isOk() ? $value : null; 159 | } 160 | 161 | 162 | private function validateItems(array &$value, Context $context): void 163 | { 164 | $items = $this->items; 165 | if ($extraKeys = array_keys(array_diff_key($value, $items))) { 166 | if ($this->otherItems) { 167 | $items += array_fill_keys($extraKeys, $this->otherItems); 168 | } else { 169 | $keys = array_map('strval', array_keys($items)); 170 | foreach ($extraKeys as $key) { 171 | $hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key); 172 | $context->addError( 173 | 'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'), 174 | Nette\Schema\Message::UnexpectedItem, 175 | ['hint' => $hint], 176 | )->path[] = $key; 177 | } 178 | } 179 | } 180 | 181 | foreach ($items as $itemKey => $itemVal) { 182 | $context->path[] = $itemKey; 183 | if (array_key_exists($itemKey, $value)) { 184 | $value[$itemKey] = $itemVal->complete($value[$itemKey], $context); 185 | } else { 186 | $default = $itemVal->completeDefault($context); // checks required item 187 | if (!$context->skipDefaults && !$this->skipDefaults) { 188 | $value[$itemKey] = $default; 189 | } 190 | } 191 | 192 | array_pop($context->path); 193 | } 194 | } 195 | 196 | 197 | public function completeDefault(Context $context): mixed 198 | { 199 | return $this->required 200 | ? $this->complete([], $context) 201 | : null; 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/Schema/Elements/Type.php: -------------------------------------------------------------------------------- 1 | [], 'array' => []]; 38 | $this->type = $type; 39 | $this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null; 40 | } 41 | 42 | 43 | public function nullable(): self 44 | { 45 | $this->type = 'null|' . $this->type; 46 | return $this; 47 | } 48 | 49 | 50 | #[\Deprecated('mergeDefaults is disabled by default')] 51 | public function mergeDefaults(bool $state = true): self 52 | { 53 | if ($state === true) { 54 | trigger_error(__METHOD__ . '() is deprecated and will be removed in the next major version.', E_USER_DEPRECATED); 55 | } 56 | $this->merge = $state; 57 | return $this; 58 | } 59 | 60 | 61 | public function mergeMode(MergeMode $mode): self 62 | { 63 | $this->mergeMode = $mode; 64 | return $this; 65 | } 66 | 67 | 68 | public function dynamic(): self 69 | { 70 | $this->type = DynamicParameter::class . '|' . $this->type; 71 | return $this; 72 | } 73 | 74 | 75 | public function min(?float $min): self 76 | { 77 | $this->range[0] = $min; 78 | return $this; 79 | } 80 | 81 | 82 | public function max(?float $max): self 83 | { 84 | $this->range[1] = $max; 85 | return $this; 86 | } 87 | 88 | 89 | /** 90 | * @internal use arrayOf() or listOf() 91 | */ 92 | public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): self 93 | { 94 | $this->itemsValue = $valueType instanceof Schema 95 | ? $valueType 96 | : new self($valueType); 97 | $this->itemsKey = $keyType instanceof Schema || $keyType === null 98 | ? $keyType 99 | : new self($keyType); 100 | return $this; 101 | } 102 | 103 | 104 | public function pattern(?string $pattern): self 105 | { 106 | $this->pattern = $pattern; 107 | return $this; 108 | } 109 | 110 | 111 | /********************* processing ****************d*g**/ 112 | 113 | 114 | public function normalize(mixed $value, Context $context): mixed 115 | { 116 | $value = $this->doNormalize($value, $context); 117 | if (is_array($value) && $this->itemsValue) { 118 | $res = []; 119 | foreach ($value as $key => $val) { 120 | $context->path[] = $key; 121 | $context->isKey = true; 122 | $key = $this->itemsKey 123 | ? $this->itemsKey->normalize($key, $context) 124 | : $key; 125 | $context->isKey = false; 126 | $res[$key] = $this->itemsValue->normalize($val, $context); 127 | array_pop($context->path); 128 | } 129 | 130 | $value = $res; 131 | } 132 | 133 | return $value; 134 | } 135 | 136 | 137 | public function merge(mixed $value, mixed $base): mixed 138 | { 139 | if ($this->mergeMode === MergeMode::Replace) { 140 | return $value; 141 | } 142 | 143 | if (is_array($value) && is_array($base)) { 144 | $index = $this->mergeMode === MergeMode::OverwriteKeys ? null : 0; 145 | foreach ($value as $key => $val) { 146 | if ($key === $index) { 147 | $base[] = $val; 148 | $index++; 149 | } else { 150 | $base[$key] = array_key_exists($key, $base) && $this->itemsValue 151 | ? $this->itemsValue->merge($val, $base[$key]) 152 | : $val; 153 | } 154 | } 155 | 156 | return $base; 157 | } 158 | 159 | return $value === null && is_array($base) ? $base : $value; 160 | } 161 | 162 | 163 | public function complete(mixed $value, Context $context): mixed 164 | { 165 | if ($value === null && is_array($this->default)) { 166 | $value = []; // is unable to distinguish null from array in NEON 167 | } 168 | 169 | $this->doDeprecation($context); 170 | 171 | $isOk = $context->createChecker(); 172 | Helpers::validateType($value, $this->type, $context); 173 | $isOk() && Helpers::validateRange($value, $this->range, $context, $this->type); 174 | $isOk() && $value !== null && $this->pattern !== null && Helpers::validatePattern($value, $this->pattern, $context); 175 | $isOk() && is_array($value) && $this->validateItems($value, $context); 176 | $isOk() && $this->merge && $value = Helpers::merge($value, $this->default); 177 | $isOk() && $value = $this->doTransform($value, $context); 178 | if (!$isOk()) { 179 | return null; 180 | } 181 | 182 | if ($value instanceof DynamicParameter) { 183 | $expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range)); 184 | $context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path]; 185 | } 186 | return $value; 187 | } 188 | 189 | 190 | private function validateItems(array &$value, Context $context): void 191 | { 192 | if (!$this->itemsValue) { 193 | return; 194 | } 195 | 196 | $res = []; 197 | foreach ($value as $key => $val) { 198 | $context->path[] = $key; 199 | $context->isKey = true; 200 | $key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key; 201 | $context->isKey = false; 202 | $res[$key ?? ''] = $this->itemsValue->complete($val, $context); 203 | array_pop($context->path); 204 | } 205 | $value = $res; 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Nette Schema 2 | 3 | [![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema) 4 | [![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions) 5 | [![Coverage Status](https://coveralls.io/repos/github/nette/schema/badge.svg?branch=master)](https://coveralls.io/github/nette/schema?branch=master) 6 | [![Latest Stable Version](https://poser.pugx.org/nette/schema/v/stable)](https://github.com/nette/schema/releases) 7 | [![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/schema/blob/master/license.md) 8 | 9 | 10 | Introduction 11 | ============ 12 | 13 | A practical library for validation and normalization of data structures against a given schema with a smart & easy-to-understand API. 14 | 15 | Documentation can be found on the [website](https://doc.nette.org/schema). 16 | 17 | Installation: 18 | 19 | ```shell 20 | composer require nette/schema 21 | ``` 22 | 23 | It requires PHP version 8.1 and supports PHP up to 8.5. 24 | 25 | 26 | [Support Me](https://github.com/sponsors/dg) 27 | -------------------------------------------- 28 | 29 | Do you like Nette Schema? Are you looking forward to the new features? 30 | 31 | [![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) 32 | 33 | Thank you! 34 | 35 | 36 | Basic Usage 37 | ----------- 38 | 39 | In variable `$schema` we have a validation schema (what exactly this means and how to create it we will say later) and in variable `$data` we have a data structure that we want to validate and normalize. This can be, for example, data sent by the user through an API, configuration file, etc. 40 | 41 | The task is handled by the [Nette\Schema\Processor](https://api.nette.org/schema/master/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception on error. 42 | 43 | ```php 44 | $processor = new Nette\Schema\Processor; 45 | 46 | try { 47 | $normalized = $processor->process($schema, $data); 48 | } catch (Nette\Schema\ValidationException $e) { 49 | echo 'Data is invalid: ' . $e->getMessage(); 50 | } 51 | ``` 52 | 53 | Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects. 54 | 55 | 56 | Defining Schema 57 | --------------- 58 | 59 | And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it, we actually define expectations of what the data should look like. Let's say that the input data must be a structure (e.g. an array) containing elements `processRefund` of type bool and `refundAmount` of type int. 60 | 61 | ```php 62 | use Nette\Schema\Expect; 63 | 64 | $schema = Expect::structure([ 65 | 'processRefund' => Expect::bool(), 66 | 'refundAmount' => Expect::int(), 67 | ]); 68 | ``` 69 | 70 | We believe that the schema definition looks clear, even if you see it for the very first time. 71 | 72 | Lets send the following data for validation: 73 | 74 | ```php 75 | $data = [ 76 | 'processRefund' => true, 77 | 'refundAmount' => 17, 78 | ]; 79 | 80 | $normalized = $processor->process($schema, $data); // OK, it passes 81 | ``` 82 | 83 | The output, i.e. the value `$normalized`, is the object `stdClass`. If we want the output to be an array, we add a cast to schema `Expect::structure([...])->castTo('array')`. 84 | 85 | All elements of the structure are optional and have a default value `null`. Example: 86 | 87 | ```php 88 | $data = [ 89 | 'refundAmount' => 17, 90 | ]; 91 | 92 | $normalized = $processor->process($schema, $data); // OK, it passes 93 | // $normalized = {'processRefund' => null, 'refundAmount' => 17} 94 | ``` 95 | 96 | The fact that the default value is `null` does not mean that it would be accepted in the input data `'processRefund' => null`. No, the input must be boolean, i.e. only `true` or `false`. We would have to explicitly allow `null` via `Expect::bool()->nullable()`. 97 | 98 | An item can be made mandatory using `Expect::bool()->required()`. We change the default value to `false` using `Expect::bool()->default(false)` or shortly using `Expect::bool(false)`. 99 | 100 | And what if we wanted to accept `1` and `0` besides booleans? Then we list the allowed values, which we will also normalize to boolean: 101 | 102 | ```php 103 | $schema = Expect::structure([ 104 | 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), 105 | 'refundAmount' => Expect::int(), 106 | ]); 107 | 108 | $normalized = $processor->process($schema, $data); 109 | is_bool($normalized->processRefund); // true 110 | ``` 111 | 112 | Now you know the basics of how the schema is defined and how the individual elements of the structure behave. We will now show what all the other elements can be used in defining a schema. 113 | 114 | 115 | Data Types: type() 116 | ------------------ 117 | 118 | All standard PHP data types can be listed in the schema: 119 | 120 | ```php 121 | Expect::string($default = null) 122 | Expect::int($default = null) 123 | Expect::float($default = null) 124 | Expect::bool($default = null) 125 | Expect::null() 126 | Expect::array($default = []) 127 | ``` 128 | 129 | And then all types [supported by the Validators](https://doc.nette.org/validators#toc-validation-rules) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`. 130 | 131 | You can also use union notation: 132 | 133 | ```php 134 | Expect::type('bool|string|array') 135 | ``` 136 | 137 | The default value is always `null` except for `array` and `list`, where it is an empty array. (A list is an array indexed in ascending order of numeric keys from zero, that is, a non-associative array). 138 | 139 | 140 | Array of Values: arrayOf() listOf() 141 | ----------------------------------- 142 | 143 | The array is too general structure, it is more useful to specify exactly what elements it can contain. For example, an array whose elements can only be strings: 144 | 145 | ```php 146 | $schema = Expect::arrayOf('string'); 147 | 148 | $processor->process($schema, ['hello', 'world']); // OK 149 | $processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK 150 | $processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string 151 | ``` 152 | 153 | The second parameter can be used to specify keys (since version 1.2): 154 | 155 | ```php 156 | $schema = Expect::arrayOf('string', 'int'); 157 | 158 | $processor->process($schema, ['hello', 'world']); // OK 159 | $processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not int 160 | ``` 161 | 162 | The list is an indexed array: 163 | 164 | ```php 165 | $schema = Expect::listOf('string'); 166 | 167 | $processor->process($schema, ['a', 'b']); // OK 168 | $processor->process($schema, ['a', 123]); // ERROR: 123 is not a string 169 | $processor->process($schema, ['key' => 'a']); // ERROR: is not a list 170 | $processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: is not a list 171 | ``` 172 | 173 | The parameter can also be a schema, so we can write: 174 | 175 | ```php 176 | Expect::arrayOf(Expect::bool()) 177 | ``` 178 | 179 | The default value is an empty array. If you specify a default value and call `mergeDefaults()`, it will be merged with the passed data. 180 | 181 | 182 | Enumeration: anyOf() 183 | -------------------- 184 | 185 | `anyOf()` is a set of values ​​or schemas that a value can be. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`: 186 | 187 | ```php 188 | $schema = Expect::listOf( 189 | Expect::anyOf('a', true, null), 190 | ); 191 | 192 | $processor->process($schema, ['a', true, null, 'a']); // OK 193 | $processor->process($schema, ['a', false]); // ERROR: false does not belong there 194 | ``` 195 | 196 | The enumeration elements can also be schemas: 197 | 198 | ```php 199 | $schema = Expect::listOf( 200 | Expect::anyOf(Expect::string(), true, null), 201 | ); 202 | 203 | $processor->process($schema, ['foo', true, null, 'bar']); // OK 204 | $processor->process($schema, [123]); // ERROR 205 | ``` 206 | 207 | The `anyOf()` method accepts variants as individual parameters, not as array. To pass it an array of values, use the unpacking operator `anyOf(...$variants)`. 208 | 209 | The default value is `null`. Use the `firstIsDefault()` method to make the first element the default: 210 | 211 | ```php 212 | // default is 'hello' 213 | Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); 214 | ``` 215 | 216 | 217 | Structures 218 | ---------- 219 | 220 | Structures are objects with defined keys. Each of these key => value pairs is referred to as a "property": 221 | 222 | Structures accept arrays and objects and return objects `stdClass` (unless you change it with `castTo('array')`, etc.). 223 | 224 | By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: 225 | 226 | ```php 227 | $schema = Expect::structure([ 228 | 'required' => Expect::string()->required(), 229 | 'optional' => Expect::string(), // the default value is null 230 | ]); 231 | 232 | $processor->process($schema, ['optional' => '']); 233 | // ERROR: option 'required' is missing 234 | 235 | $processor->process($schema, ['required' => 'foo']); 236 | // OK, returns {'required' => 'foo', 'optional' => null} 237 | ``` 238 | 239 | If you do not want to output properties with only a default value, use `skipDefaults()`: 240 | 241 | ```php 242 | $schema = Expect::structure([ 243 | 'required' => Expect::string()->required(), 244 | 'optional' => Expect::string(), 245 | ])->skipDefaults(); 246 | 247 | $processor->process($schema, ['required' => 'foo']); 248 | // OK, returns {'required' => 'foo'} 249 | ``` 250 | 251 | Although `null` is the default value of the `optional` property, it is not allowed in the input data (the value must be a string). Properties accepting `null` are defined using `nullable()`: 252 | 253 | ```php 254 | $schema = Expect::structure([ 255 | 'optional' => Expect::string(), 256 | 'nullable' => Expect::string()->nullable(), 257 | ]); 258 | 259 | $processor->process($schema, ['optional' => null]); 260 | // ERROR: 'optional' expects to be string, null given. 261 | 262 | $processor->process($schema, ['nullable' => null]); 263 | // OK, returns {'optional' => null, 'nullable' => null} 264 | ``` 265 | 266 | By default, there can be no extra items in the input data: 267 | 268 | ```php 269 | $schema = Expect::structure([ 270 | 'key' => Expect::string(), 271 | ]); 272 | 273 | $processor->process($schema, ['additional' => 1]); 274 | // ERROR: Unexpected item 'additional' 275 | ``` 276 | 277 | Which we can change with `otherItems()`. As a parameter, we will specify the schema for each extra element: 278 | 279 | ```php 280 | $schema = Expect::structure([ 281 | 'key' => Expect::string(), 282 | ])->otherItems(Expect::int()); 283 | 284 | $processor->process($schema, ['additional' => 1]); // OK 285 | $processor->process($schema, ['additional' => true]); // ERROR 286 | ``` 287 | 288 | 289 | Deprecations 290 | ------------ 291 | 292 | You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()`: 293 | 294 | ```php 295 | $schema = Expect::structure([ 296 | 'old' => Expect::int()->deprecated('The item %path% is deprecated'), 297 | ]); 298 | 299 | $processor->process($schema, ['old' => 1]); // OK 300 | $processor->getWarnings(); // ["The item 'old' is deprecated"] 301 | ``` 302 | 303 | 304 | Ranges: min() max() 305 | ------------------- 306 | 307 | Use `min()` and `max()` to limit the number of elements for arrays: 308 | 309 | ```php 310 | // array, at least 10 items, maximum 20 items 311 | Expect::array()->min(10)->max(20); 312 | ``` 313 | 314 | For strings, limit their length: 315 | 316 | ```php 317 | // string, at least 10 characters long, maximum 20 characters 318 | Expect::string()->min(10)->max(20); 319 | ``` 320 | 321 | For numbers, limit their value: 322 | 323 | ```php 324 | // integer, between 10 and 20 inclusive 325 | Expect::int()->min(10)->max(20); 326 | ``` 327 | 328 | Of course, it is possible to mention only `min()`, or only `max()`: 329 | 330 | ```php 331 | // string, maximum 20 characters 332 | Expect::string()->max(20); 333 | ``` 334 | 335 | 336 | Regular Expressions: pattern() 337 | ------------------------------ 338 | 339 | Using `pattern()`, you can specify a regular expression which the **whole** input string must match (i.e. as if it were wrapped in characters `^` a `$`): 340 | 341 | ```php 342 | // just 9 digits 343 | Expect::string()->pattern('\d{9}'); 344 | ``` 345 | 346 | 347 | Custom Assertions: assert() 348 | --------------------------- 349 | 350 | You can add any other restrictions using `assert(callable $fn)`. 351 | 352 | ```php 353 | $countIsEven = fn($v) => count($v) % 2 === 0; 354 | 355 | $schema = Expect::arrayOf('string') 356 | ->assert($countIsEven); // the count must be even 357 | 358 | $processor->process($schema, ['a', 'b']); // OK 359 | $processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even 360 | ``` 361 | 362 | Or 363 | 364 | ```php 365 | Expect::string()->assert('is_file'); // the file must exist 366 | ``` 367 | 368 | You can add your own description for each assertion. It will be part of the error message. 369 | 370 | ```php 371 | $schema = Expect::arrayOf('string') 372 | ->assert($countIsEven, 'Even items in array'); 373 | 374 | $processor->process($schema, ['a', 'b', 'c']); 375 | // Failed assertion "Even items in array" for item with value array. 376 | ``` 377 | 378 | The method can be called repeatedly to add multiple constraints. It can be intermixed with calls to `transform()` and `castTo()`. 379 | 380 | 381 | Transformation: transform() 382 | --------------------------- 383 | 384 | Successfully validated data can be modified using a custom function: 385 | 386 | ```php 387 | // conversion to uppercase: 388 | Expect::string()->transform(fn(string $s) => strtoupper($s)); 389 | ``` 390 | 391 | The method can be called repeatedly to add multiple transformations. It can be intermixed with calls to `assert()` and `castTo()`. The operations will be executed in the order in which they are declared: 392 | 393 | ```php 394 | Expect::type('string|int') 395 | ->castTo('string') 396 | ->assert('ctype_lower', 'All characters must be lowercased') 397 | ->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase 398 | ``` 399 | 400 | The `transform()` method can both transform and validate the value simultaneously. This is often simpler and less redundant than chaining `transform()` and `assert()`. For this purpose, the function receives a [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object with an `addError()` method, which can be used to add information about validation issues: 401 | 402 | ```php 403 | Expect::string() 404 | ->transform(function (string $s, Nette\Schema\Context $context) { 405 | if (!ctype_lower($s)) { 406 | $context->addError('All characters must be lowercased', 'my.case.error'); 407 | return null; 408 | } 409 | 410 | return strtoupper($s); 411 | }); 412 | ``` 413 | 414 | 415 | Casting: castTo() 416 | ----------------- 417 | 418 | Successfully validated data can be cast: 419 | 420 | ```php 421 | Expect::scalar()->castTo('string'); 422 | ``` 423 | 424 | In addition to native PHP types, you can also cast to classes. It distinguishes whether it is a simple class without a constructor or a class with a constructor. If the class has no constructor, an instance of it is created and all elements of the structure are written to its properties: 425 | 426 | ```php 427 | class Info 428 | { 429 | public bool $processRefund; 430 | public int $refundAmount; 431 | } 432 | 433 | Expect::structure([ 434 | 'processRefund' => Expect::bool(), 435 | 'refundAmount' => Expect::int(), 436 | ])->castTo(Info::class); 437 | 438 | // creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount 439 | ``` 440 | 441 | If the class has a constructor, the elements of the structure are passed as named parameters to the constructor: 442 | 443 | ```php 444 | class Info 445 | { 446 | public function __construct( 447 | public bool $processRefund, 448 | public int $refundAmount, 449 | ) { 450 | } 451 | } 452 | 453 | // creates $obj = new Info(processRefund: ..., refundAmount: ...) 454 | ``` 455 | 456 | Casting combined with a scalar parameter creates an object and passes the value as the sole parameter to the constructor: 457 | 458 | ```php 459 | Expect::string()->castTo(DateTime::class); 460 | // creates new DateTime(...) 461 | ``` 462 | 463 | 464 | Normalization: before() 465 | ----------------------- 466 | 467 | Prior to the validation itself, the data can be normalized using the method `before()`. As an example, let's have an element that must be an array of strings (eg `['a', 'b', 'c']`), but receives input in the form of a string `a b c`: 468 | 469 | ```php 470 | $explode = fn($v) => explode(' ', $v); 471 | 472 | $schema = Expect::arrayOf('string') 473 | ->before($explode); 474 | 475 | $normalized = $processor->process($schema, 'a b c'); 476 | // OK, returns ['a', 'b', 'c'] 477 | ``` 478 | 479 | 480 | Mapping to Objects: from() 481 | -------------------------- 482 | 483 | You can generate structure schema from the class. Example: 484 | 485 | ```php 486 | class Config 487 | { 488 | public string $name; 489 | public ?string $password; 490 | public bool $admin = false; 491 | } 492 | 493 | $schema = Expect::from(new Config); 494 | 495 | $data = [ 496 | 'name' => 'jeff', 497 | ]; 498 | 499 | $normalized = $processor->process($schema, $data); 500 | // $normalized instanceof Config 501 | // $normalized = {'name' => 'jeff', 'password' => null, 'admin' => false} 502 | ``` 503 | 504 | Anonymous classes are also supported: 505 | 506 | ```php 507 | $schema = Expect::from(new class { 508 | public string $name; 509 | public ?string $password; 510 | public bool $admin = false; 511 | }); 512 | ``` 513 | 514 | Because the information obtained from the class definition may not be sufficient, you can add a custom schema for the elements with the second parameter: 515 | 516 | ```php 517 | $schema = Expect::from(new Config, [ 518 | 'name' => Expect::string()->pattern('\w:.*'), 519 | ]); 520 | ``` 521 | --------------------------------------------------------------------------------