readme.md000064400000031423150250170430006323 0ustar00Nette Schema ************ [![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema) [![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions) [![Coverage Status](https://coveralls.io/repos/github/nette/schema/badge.svg?branch=master)](https://coveralls.io/github/nette/schema?branch=master) [![Latest Stable Version](https://poser.pugx.org/nette/schema/v/stable)](https://github.com/nette/schema/releases) [![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/schema/blob/master/license.md) Introduction ============ A practical library for validation and normalization of data structures against a given schema with a smart & easy-to-understand API. Documentation can be found on the [website](https://doc.nette.org/schema). Installation: ```shell composer require nette/schema ``` It requires PHP version 7.1 and supports PHP up to 8.2. [Support Me](https://github.com/sponsors/dg) -------------------------------------------- Do you like Nette Schema? Are you looking forward to the new features? [![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) Thank you! Basic Usage ----------- 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. The task is handled by the [Nette\Schema\Processor](https://api.nette.org/3.0/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/3.0/Nette/Schema/ValidationException.html) exception on error. ```php $processor = new Nette\Schema\Processor; try { $normalized = $processor->process($schema, $data); } catch (Nette\Schema\ValidationException $e) { echo 'Data is invalid: ' . $e->getMessage(); } ``` Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/3.1/Nette/Schema/Message.html) objects. Defining Schema --------------- And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/3.0/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. ```php use Nette\Schema\Expect; $schema = Expect::structure([ 'processRefund' => Expect::bool(), 'refundAmount' => Expect::int(), ]); ``` We believe that the schema definition looks clear, even if you see it for the very first time. Lets send the following data for validation: ```php $data = [ 'processRefund' => true, 'refundAmount' => 17, ]; $normalized = $processor->process($schema, $data); // OK, it passes ``` 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')`. All elements of the structure are optional and have a default value `null`. Example: ```php $data = [ 'refundAmount' => 17, ]; $normalized = $processor->process($schema, $data); // OK, it passes // $normalized = {'processRefund' => null, 'refundAmount' => 17} ``` 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()`. 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)`. 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: ```php $schema = Expect::structure([ 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), 'refundAmount' => Expect::int(), ]); $normalized = $processor->process($schema, $data); is_bool($normalized->processRefund); // true ``` 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. Data Types: type() ------------------ All standard PHP data types can be listed in the schema: ```php Expect::string($default = null) Expect::int($default = null) Expect::float($default = null) Expect::bool($default = null) Expect::null() Expect::array($default = []) ``` 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')`. You can also use union notation: ```php Expect::type('bool|string|array') ``` 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). Array of Values: arrayOf() listOf() ----------------------------------- 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: ```php $schema = Expect::arrayOf('string'); $processor->process($schema, ['hello', 'world']); // OK $processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK $processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string ``` The list is an indexed array: ```php $schema = Expect::listOf('string'); $processor->process($schema, ['a', 'b']); // OK $processor->process($schema, ['a', 123]); // ERROR: 123 is not a string $processor->process($schema, ['key' => 'a']); // ERROR: is not a list $processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: is not a list ``` The parameter can also be a schema, so we can write: ```php Expect::arrayOf(Expect::bool()) ``` The default value is an empty array. If you specify default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`. Enumeration: anyOf() -------------------- `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`: ```php $schema = Expect::listOf( Expect::anyOf('a', true, null) ); $processor->process($schema, ['a', true, null, 'a']); // OK $processor->process($schema, ['a', false]); // ERROR: false does not belong there ``` The enumeration elements can also be schemas: ```php $schema = Expect::listOf( Expect::anyOf(Expect::string(), true, null) ); $processor->process($schema, ['foo', true, null, 'bar']); // OK $processor->process($schema, [123]); // ERROR ``` The default value is `null`. Structures ---------- Structures are objects with defined keys. Each of these key => value pairs is referred to as a "property": Structures accept arrays and objects and return objects `stdClass` (unless you change it with `castTo('array')`, etc.). By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`: ```php $schema = Expect::structure([ 'required' => Expect::string()->required(), 'optional' => Expect::string(), // the default value is null ]); $processor->process($schema, ['optional' => '']); // ERROR: item 'required' is missing $processor->process($schema, ['required' => 'foo']); // OK, returns {'required' => 'foo', 'optional' => null} ``` 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()`: ```php $schema = Expect::structure([ 'optional' => Expect::string(), 'nullable' => Expect::string()->nullable(), ]); $processor->process($schema, ['optional' => null]); // ERROR: 'optional' expects to be string, null given. $processor->process($schema, ['nullable' => null]); // OK, returns {'optional' => null, 'nullable' => null} ``` By default, there can be no extra items in the input data: ```php $schema = Expect::structure([ 'key' => Expect::string(), ]); $processor->process($schema, ['additional' => 1]); // ERROR: Unexpected item 'additional' ``` Which we can change with `otherItems()`. As a parameter, we will specify the schema for each extra element: ```php $schema = Expect::structure([ 'key' => Expect::string(), ])->otherItems(Expect::int()); $processor->process($schema, ['additional' => 1]); // OK $processor->process($schema, ['additional' => true]); // ERROR ``` Deprecations ------------ You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()` (since v1.1): ```php $schema = Expect::structure([ 'old' => Expect::int()->deprecated('The item %path% is deprecated'), ]); $processor->process($schema, ['old' => 1]); // OK $processor->getWarnings(); // ["The item 'old' is deprecated"] ``` Ranges: min() max() ------------------- Use `min()` and `max()` to limit the number of elements for arrays: ```php // array, at least 10 items, maximum 20 items Expect::array()->min(10)->max(20); ``` For strings, limit their length: ```php // string, at least 10 characters long, maximum 20 characters Expect::string()->min(10)->max(20); ``` For numbers, limit their value: ```php // integer, between 10 and 20 inclusive Expect::int()->min(10)->max(20); ``` Of course, it is possible to mention only `min()`, or only `max()`: ```php // string, maximum 20 characters Expect::string()->max(20); ``` Regular Expressions: pattern() ------------------------------ 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 `$`): ```php // just 9 digits Expect::string()->pattern('\d{9}'); ``` Custom Assertions: assert() --------------------------- You can add any other restrictions using `assert(callable $fn)`. ```php $countIsEven = function ($v) { return count($v) % 2 === 0; }; $schema = Expect::arrayOf('string') ->assert($countIsEven); // the count must be even $processor->process($schema, ['a', 'b']); // OK $processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even ``` Or ```php Expect::string()->assert('is_file'); // the file must exist ``` You can add your own description for each assertions. It will be part of the error message. ```php $schema = Expect::arrayOf('string') ->assert($countIsEven, 'Even items in array'); $processor->process($schema, ['a', 'b', 'c']); // Failed assertion "Even items in array" for item with value array. ``` The method can be called repeatedly to add more assertions. Mapping to Objects: from() -------------------------- You can generate structure schema from the class. Example: ```php class Config { /** @var string */ public $name; /** @var string|null */ public $password; /** @var bool */ public $admin = false; } $schema = Expect::from(new Config); $data = [ 'name' => 'jeff', ]; $normalized = $processor->process($schema, $data); // $normalized instanceof Config // $normalized = {'name' => 'jeff', 'password' => null, 'admin' => false} ``` If you are using PHP 7.4 or higher, you can use native types: ```php class Config { public string $name; public ?string $password; public bool $admin = false; } $schema = Expect::from(new Config); ``` Anonymous classes are also supported: ```php $schema = Expect::from(new class { public string $name; public ?string $password; public bool $admin = false; }); ``` 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: ```php $schema = Expect::from(new Config, [ 'name' => Expect::string()->pattern('\w:.*'), ]); ``` Casting: castTo() ----------------- Successfully validated data can be cast: ```php Expect::scalar()->castTo('string'); ``` In addition to native PHP types, you can also cast to classes: ```php Expect::scalar()->castTo('AddressEntity'); ``` Normalization: before() ----------------------- 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`: ```php $explode = function ($v) { return explode(' ', $v); }; $schema = Expect::arrayOf('string') ->before($explode); $normalized = $processor->process($schema, 'a b c'); // OK, returns ['a', 'b', 'c'] ``` composer.json000064400000001515150250170430007265 0ustar00{ "name": "nette/schema", "description": "📐 Nette Schema: validating data structures against a given Schema.", "keywords": ["nette", "config"], "homepage": "https://nette.org", "license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"], "authors": [ { "name": "David Grudl", "homepage": "https://davidgrudl.com" }, { "name": "Nette Community", "homepage": "https://nette.org/contributors" } ], "require": { "php": ">=7.1 <8.3", "nette/utils": "^2.5.7 || ^3.1.5 || ^4.0" }, "require-dev": { "nette/tester": "^2.3 || ^2.4", "tracy/tracy": "^2.7", "phpstan/phpstan-nette": "^1.0" }, "autoload": { "classmap": ["src/"] }, "minimum-stability": "dev", "scripts": { "phpstan": "phpstan analyse", "tester": "tester tests -s" }, "extra": { "branch-alias": { "dev-master": "1.2-dev" } } } src/Schema/Schema.php000064400000001062150250170430010440 0ustar00isKey; return $this->errors[] = new Message($message, $code, $this->path, $variables); } public function addWarning(string $message, string $code, array $variables = []): Message { return $this->warnings[] = new Message($message, $code, $this->path, $variables); } } src/Schema/Message.php000064400000003573150250170430010635 0ustar00message = $message; $this->code = $code; $this->path = $path; $this->variables = $variables; } public function toString(): string { $vars = $this->variables; $vars['label'] = empty($vars['isKey']) ? 'item' : 'key of item'; $vars['path'] = $this->path ? "'" . implode("\u{a0}›\u{a0}", $this->path) . "'" : null; $vars['value'] = Helpers::formatValue($vars['value'] ?? null); return preg_replace_callback('~( ?)%(\w+)%~', function ($m) use ($vars) { [, $space, $key] = $m; return $vars[$key] === null ? '' : $space . $vars[$key]; }, $this->message); } } src/Schema/Helpers.php000064400000004757150250170430010660 0ustar00 $val) { if ($key === $index) { $base[] = $val; $index++; } else { $base[$key] = static::merge($val, $base[$key] ?? null); } } return $base; } elseif ($value === null && is_array($base)) { return $base; } else { return $value; } } public static function getPropertyType(\ReflectionProperty $prop): ?string { if (!class_exists(Nette\Utils\Type::class)) { throw new Nette\NotSupportedException('Expect::from() requires nette/utils 3.x'); } elseif ($type = Nette\Utils\Type::fromReflection($prop)) { return (string) $type; } elseif ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var'))) { $class = Reflection::getPropertyDeclaringClass($prop); return preg_replace_callback('#[\w\\\\]+#', function ($m) use ($class) { return Reflection::expandClassName($m[0], $class); }, $type); } return null; } /** * Returns an annotation value. * @param \ReflectionProperty $ref */ public static function parseAnnotation(\Reflector $ref, string $name): ?string { if (!Reflection::areCommentsAvailable()) { throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.'); } $re = '#[\s*]@' . preg_quote($name, '#') . '(?=\s|$)(?:[ \t]+([^@\s]\S*))?#'; if ($ref->getDocComment() && preg_match($re, trim($ref->getDocComment(), '/*'), $m)) { return $m[1] ?? ''; } return null; } /** * @param mixed $value */ public static function formatValue($value): string { if (is_object($value)) { return 'object ' . get_class($value); } elseif (is_string($value)) { return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'"; } elseif (is_scalar($value)) { return var_export($value, true); } else { return strtolower(gettype($value)); } } } src/Schema/ValidationException.php000064400000001521150250170430013211 0ustar00toString()); $this->messages = $messages; } /** * @return string[] */ public function getMessages(): array { $res = []; foreach ($this->messages as $message) { $res[] = $message->toString(); } return $res; } /** * @return Message[] */ public function getMessageObjects(): array { return $this->messages; } } src/Schema/Expect.php000064400000004723150250170430010477 0ustar00default($args[0]); } return $type; } public static function type(string $type): Type { return new Type($type); } /** * @param mixed|Schema ...$set */ public static function anyOf(...$set): AnyOf { return new AnyOf(...$set); } /** * @param Schema[] $items */ public static function structure(array $items): Structure { return new Structure($items); } /** * @param object $object */ public static function from($object, array $items = []): Structure { $ro = new \ReflectionObject($object); foreach ($ro->getProperties() as $prop) { $type = Helpers::getPropertyType($prop) ?? 'mixed'; $item = &$items[$prop->getName()]; if (!$item) { $item = new Type($type); if (PHP_VERSION_ID >= 70400 && !$prop->isInitialized($object)) { $item->required(); } else { $def = $prop->getValue($object); if (is_object($def)) { $item = static::from($def); } elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) { $item->required(); } else { $item->default($def); } } } } return (new Structure($items))->castTo($ro->getName()); } /** * @param string|Schema $valueType * @param string|Schema|null $keyType */ public static function arrayOf($valueType, $keyType = null): Type { return (new Type('array'))->items($valueType, $keyType); } /** * @param string|Schema $type */ public static function listOf($type): Type { return (new Type('list'))->items($type); } } src/Schema/Processor.php000064400000003674150250170430011232 0ustar00skipDefaults = $value; } /** * Normalizes and validates data. Result is a clean completed data. * @return mixed * @throws ValidationException */ public function process(Schema $schema, $data) { $this->createContext(); $data = $schema->normalize($data, $this->context); $this->throwsErrors(); $data = $schema->complete($data, $this->context); $this->throwsErrors(); return $data; } /** * Normalizes and validates and merges multiple data. Result is a clean completed data. * @return mixed * @throws ValidationException */ public function processMultiple(Schema $schema, array $dataset) { $this->createContext(); $flatten = null; $first = true; foreach ($dataset as $data) { $data = $schema->normalize($data, $this->context); $this->throwsErrors(); $flatten = $first ? $data : $schema->merge($data, $flatten); $first = false; } $data = $schema->complete($flatten, $this->context); $this->throwsErrors(); return $data; } /** * @return string[] */ public function getWarnings(): array { $res = []; foreach ($this->context->warnings as $message) { $res[] = $message->toString(); } return $res; } private function throwsErrors(): void { if ($this->context->errors) { throw new ValidationException(null, $this->context->errors); } } private function createContext() { $this->context = new Context; $this->context->skipDefaults = $this->skipDefaults; $this->onNewContext($this->context); } } src/Schema/Elements/Structure.php000064400000010516150250170430013020 0ustar00items = $items; $this->castTo = 'object'; $this->required = true; } public function default($value): self { throw new Nette\InvalidStateException('Structure cannot have default value.'); } public function min(?int $min): self { $this->range[0] = $min; return $this; } public function max(?int $max): self { $this->range[1] = $max; return $this; } /** * @param string|Schema $type */ public function otherItems($type = 'mixed'): self { $this->otherItems = $type instanceof Schema ? $type : new Type($type); return $this; } public function skipDefaults(bool $state = true): self { $this->skipDefaults = $state; return $this; } /********************* processing ****************d*g**/ public function normalize($value, Context $context) { if ($prevent = (is_array($value) && isset($value[Helpers::PREVENT_MERGING]))) { unset($value[Helpers::PREVENT_MERGING]); } $value = $this->doNormalize($value, $context); if (is_object($value)) { $value = (array) $value; } if (is_array($value)) { foreach ($value as $key => $val) { $itemSchema = $this->items[$key] ?? $this->otherItems; if ($itemSchema) { $context->path[] = $key; $value[$key] = $itemSchema->normalize($val, $context); array_pop($context->path); } } if ($prevent) { $value[Helpers::PREVENT_MERGING] = true; } } return $value; } public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PREVENT_MERGING])) { unset($value[Helpers::PREVENT_MERGING]); $base = null; } if (is_array($value) && is_array($base)) { $index = 0; foreach ($value as $key => $val) { if ($key === $index) { $base[] = $val; $index++; } elseif (array_key_exists($key, $base)) { $itemSchema = $this->items[$key] ?? $this->otherItems; $base[$key] = $itemSchema ? $itemSchema->merge($val, $base[$key]) : Helpers::merge($val, $base[$key]); } else { $base[$key] = $val; } } return $base; } return Helpers::merge($value, $base); } public function complete($value, Context $context) { if ($value === null) { $value = []; // is unable to distinguish null from array in NEON } $this->doDeprecation($context); if (!$this->doValidate($value, 'array', $context) || !$this->doValidateRange($value, $this->range, $context) ) { return; } $errCount = count($context->errors); $items = $this->items; if ($extraKeys = array_keys(array_diff_key($value, $items))) { if ($this->otherItems) { $items += array_fill_keys($extraKeys, $this->otherItems); } else { $keys = array_map('strval', array_keys($items)); foreach ($extraKeys as $key) { $hint = Nette\Utils\ObjectHelpers::getSuggestion($keys, (string) $key); $context->addError( 'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'), Nette\Schema\Message::UNEXPECTED_ITEM, ['hint' => $hint] )->path[] = $key; } } } foreach ($items as $itemKey => $itemVal) { $context->path[] = $itemKey; if (array_key_exists($itemKey, $value)) { $value[$itemKey] = $itemVal->complete($value[$itemKey], $context); } else { $default = $itemVal->completeDefault($context); // checks required item if (!$context->skipDefaults && !$this->skipDefaults) { $value[$itemKey] = $default; } } array_pop($context->path); } if (count($context->errors) > $errCount) { return; } return $this->doFinalize($value, $context); } public function completeDefault(Context $context) { return $this->required ? $this->complete([], $context) : null; } } src/Schema/Elements/Type.php000064400000011610150250170430011735 0ustar00 [], 'array' => []]; $this->type = $type; $this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null; } public function nullable(): self { $this->type = 'null|' . $this->type; return $this; } public function mergeDefaults(bool $state = true): self { $this->merge = $state; return $this; } public function dynamic(): self { $this->type = DynamicParameter::class . '|' . $this->type; return $this; } public function min(?float $min): self { $this->range[0] = $min; return $this; } public function max(?float $max): self { $this->range[1] = $max; return $this; } /** * @param string|Schema $valueType * @param string|Schema|null $keyType * @internal use arrayOf() or listOf() */ public function items($valueType = 'mixed', $keyType = null): self { $this->itemsValue = $valueType instanceof Schema ? $valueType : new self($valueType); $this->itemsKey = $keyType instanceof Schema || $keyType === null ? $keyType : new self($keyType); return $this; } public function pattern(?string $pattern): self { $this->pattern = $pattern; return $this; } /********************* processing ****************d*g**/ public function normalize($value, Context $context) { if ($prevent = (is_array($value) && isset($value[Helpers::PREVENT_MERGING]))) { unset($value[Helpers::PREVENT_MERGING]); } $value = $this->doNormalize($value, $context); if (is_array($value) && $this->itemsValue) { $res = []; foreach ($value as $key => $val) { $context->path[] = $key; $context->isKey = true; $key = $this->itemsKey ? $this->itemsKey->normalize($key, $context) : $key; $context->isKey = false; $res[$key] = $this->itemsValue->normalize($val, $context); array_pop($context->path); } $value = $res; } if ($prevent && is_array($value)) { $value[Helpers::PREVENT_MERGING] = true; } return $value; } public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PREVENT_MERGING])) { unset($value[Helpers::PREVENT_MERGING]); return $value; } if (is_array($value) && is_array($base) && $this->itemsValue) { $index = 0; foreach ($value as $key => $val) { if ($key === $index) { $base[] = $val; $index++; } else { $base[$key] = array_key_exists($key, $base) ? $this->itemsValue->merge($val, $base[$key]) : $val; } } return $base; } return Helpers::merge($value, $base); } public function complete($value, Context $context) { $merge = $this->merge; if (is_array($value) && isset($value[Helpers::PREVENT_MERGING])) { unset($value[Helpers::PREVENT_MERGING]); $merge = false; } if ($value === null && is_array($this->default)) { $value = []; // is unable to distinguish null from array in NEON } $this->doDeprecation($context); if (!$this->doValidate($value, $this->type, $context) || !$this->doValidateRange($value, $this->range, $context, $this->type) ) { return; } if ($value !== null && $this->pattern !== null && !preg_match("\x01^(?:$this->pattern)$\x01Du", $value)) { $context->addError( "The %label% %path% expects to match pattern '%pattern%', %value% given.", Nette\Schema\Message::PATTERN_MISMATCH, ['value' => $value, 'pattern' => $this->pattern] ); return; } if ($value instanceof DynamicParameter) { $expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range)); $context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected)]; } if ($this->itemsValue) { $errCount = count($context->errors); $res = []; foreach ($value as $key => $val) { $context->path[] = $key; $context->isKey = true; $key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key; $context->isKey = false; $res[$key] = $this->itemsValue->complete($val, $context); array_pop($context->path); } if (count($context->errors) > $errCount) { return null; } $value = $res; } if ($merge) { $value = Helpers::merge($value, $this->default); } return $this->doFinalize($value, $context); } } src/Schema/Elements/AnyOf.php000064400000005421150250170430012033 0ustar00set = $set; } public function firstIsDefault(): self { $this->default = $this->set[0]; return $this; } public function nullable(): self { $this->set[] = null; return $this; } public function dynamic(): self { $this->set[] = new Type(Nette\Schema\DynamicParameter::class); return $this; } /********************* processing ****************d*g**/ public function normalize($value, Context $context) { return $this->doNormalize($value, $context); } public function merge($value, $base) { if (is_array($value) && isset($value[Helpers::PREVENT_MERGING])) { unset($value[Helpers::PREVENT_MERGING]); return $value; } return Helpers::merge($value, $base); } public function complete($value, Context $context) { $expecteds = $innerErrors = []; foreach ($this->set as $item) { if ($item instanceof Schema) { $dolly = new Context; $dolly->path = $context->path; $res = $item->complete($item->normalize($value, $dolly), $dolly); if (!$dolly->errors) { $context->warnings = array_merge($context->warnings, $dolly->warnings); return $this->doFinalize($res, $context); } foreach ($dolly->errors as $error) { if ($error->path !== $context->path || empty($error->variables['expected'])) { $innerErrors[] = $error; } else { $expecteds[] = $error->variables['expected']; } } } else { if ($item === $value) { return $this->doFinalize($value, $context); } $expecteds[] = Nette\Schema\Helpers::formatValue($item); } } if ($innerErrors) { $context->errors = array_merge($context->errors, $innerErrors); } else { $context->addError( 'The %label% %path% expects to be %expected%, %value% given.', Nette\Schema\Message::TYPE_MISMATCH, [ 'value' => $value, 'expected' => implode('|', array_unique($expecteds)), ] ); } } public function completeDefault(Context $context) { if ($this->required) { $context->addError( 'The mandatory item %path% is missing.', Nette\Schema\Message::MISSING_ITEM ); return null; } if ($this->default instanceof Schema) { return $this->default->completeDefault($context); } return $this->default; } } src/Schema/Elements/Base.php000064400000010246150250170430011672 0ustar00default = $value; return $this; } public function required(bool $state = true): self { $this->required = $state; return $this; } public function before(callable $handler): self { $this->before = $handler; return $this; } public function castTo(string $type): self { $this->castTo = $type; return $this; } public function assert(callable $handler, ?string $description = null): self { $this->asserts[] = [$handler, $description]; return $this; } /** Marks as deprecated */ public function deprecated(string $message = 'The item %path% is deprecated.'): self { $this->deprecated = $message; return $this; } public function completeDefault(Context $context) { if ($this->required) { $context->addError( 'The mandatory item %path% is missing.', Nette\Schema\Message::MISSING_ITEM ); return null; } return $this->default; } public function doNormalize($value, Context $context) { if ($this->before) { $value = ($this->before)($value); } return $value; } private function doDeprecation(Context $context): void { if ($this->deprecated !== null) { $context->addWarning( $this->deprecated, Nette\Schema\Message::DEPRECATED ); } } private function doValidate($value, string $expected, Context $context): bool { if (!Nette\Utils\Validators::is($value, $expected)) { $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); $context->addError( 'The %label% %path% expects to be %expected%, %value% given.', Nette\Schema\Message::TYPE_MISMATCH, ['value' => $value, 'expected' => $expected] ); return false; } return true; } private function doValidateRange($value, array $range, Context $context, string $types = ''): bool { if (is_array($value) || is_string($value)) { [$length, $label] = is_array($value) ? [count($value), 'items'] : (in_array('unicode', explode('|', $types), true) ? [Nette\Utils\Strings::length($value), 'characters'] : [strlen($value), 'bytes']); if (!self::isInRange($length, $range)) { $context->addError( "The length of %label% %path% expects to be in range %expected%, %length% $label given.", Nette\Schema\Message::LENGTH_OUT_OF_RANGE, ['value' => $value, 'length' => $length, 'expected' => implode('..', $range)] ); return false; } } elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) { $context->addError( 'The %label% %path% expects to be in range %expected%, %value% given.', Nette\Schema\Message::VALUE_OUT_OF_RANGE, ['value' => $value, 'expected' => implode('..', $range)] ); return false; } return true; } private function isInRange($value, array $range): bool { return ($range[0] === null || $value >= $range[0]) && ($range[1] === null || $value <= $range[1]); } private function doFinalize($value, Context $context) { if ($this->castTo) { if (Nette\Utils\Reflection::isBuiltinType($this->castTo)) { settype($value, $this->castTo); } else { $object = new $this->castTo; foreach ($value as $k => $v) { $object->$k = $v; } $value = $object; } } foreach ($this->asserts as $i => [$handler, $description]) { if (!$handler($value)) { $expected = $description ?: (is_string($handler) ? "$handler()" : "#$i"); $context->addError( 'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.', Nette\Schema\Message::FAILED_ASSERTION, ['value' => $value, 'assertion' => $expected] ); return; } } return $value; } } license.md000064400000005244150250170430006512 0ustar00Licenses ======== Good news! You may use Nette Framework under the terms of either the New BSD License or the GNU General Public License (GPL) version 2 or 3. The BSD License is recommended for most projects. It is easy to understand and it places almost no restrictions on what you can do with the framework. If the GPL fits better to your project, you can use the framework under this license. You don't have to notify anyone which license you are using. You can freely use Nette Framework in commercial projects as long as the copyright header remains intact. Please be advised that the name "Nette Framework" is a protected trademark and its usage has some limitations. So please do not use word "Nette" in the name of your project or top-level domain, and choose a name that stands on its own merits. If your stuff is good, it will not take long to establish a reputation for yourselves. New BSD License --------------- Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of "Nette Framework" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. GNU General Public License -------------------------- GPL licenses are very very long, so instead of including them here we offer you URLs with full text: - [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) - [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) contributing.md000064400000002504150250170430007573 0ustar00How to contribute & use the issue tracker ========================================= Nette welcomes your contributions. There are several ways to help out: * Create an issue on GitHub, if you have found a bug * Write test cases for open bug issues * Write fixes for open bug/feature issues, preferably with test cases included * Contribute to the [documentation](https://nette.org/en/writing) Issues ------ Please **do not use the issue tracker to ask questions**. We will be happy to help you on [Nette forum](https://forum.nette.org) or chat with us on [Gitter](https://gitter.im/nette/nette). A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. **Feature requests** are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Contributing ------------ If you'd like to contribute, please take a moment to read [the contributing guide](https://nette.org/en/contributing). The best way to propose a feature is to discuss your ideas on [Nette forum](https://forum.nette.org) before implementing them. Please do not fix whitespace, format code, or make a purely cosmetic patch. Thanks! :heart: