This commit is contained in:
2026-11-27 17:34:16 +08:00
parent 2aa9e5097f
commit e0e860f330
1111 changed files with 153644 additions and 7 deletions
+45
View File
@@ -0,0 +1,45 @@
{
"name": "nette/schema",
"description": "📐 Nette Schema: validates and normalizes data such as configuration or API input against a schema described in a few readable lines of PHP, with precise error messages.",
"keywords": ["nette", "schema", "validation", "data validation", "normalization", "configuration"],
"homepage": "https://doc.nette.org/schema",
"license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
}
],
"require": {
"php": "8.1 - 8.6",
"nette/utils": "^4.0"
},
"require-dev": {
"nette/tester": "^2.6",
"tracy/tracy": "^2.8",
"phpstan/phpstan": "^2.3@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0.7"
},
"autoload": {
"classmap": ["src/"],
"psr-4": {
"Nette\\": "src"
}
},
"minimum-stability": "dev",
"scripts": {
"phpstan": "phpstan analyse",
"tester": "tester tests -s"
},
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}
+60
View File
@@ -0,0 +1,60 @@
Licenses
========
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)
+802
View File
@@ -0,0 +1,802 @@
# Nette Schema
[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema)
[![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 validating and normalizing 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 8.1 and supports PHP up to 8.6.
[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 the variable `$schema`, we have a validation schema (we'll explain what this means and how to create one in a moment), and in the variable `$data`, we have the data structure we want to validate and normalize. This could be, for example, data submitted by a user via an API, a configuration file, etc.
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 a [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception if an error occurs.
```php
$processor = new Nette\Schema\Processor;
try {
$normalized = $processor->process($schema, $data);
} catch (Nette\Schema\ValidationException $e) {
echo 'Data is invalid: ' . $e->getMessage();
}
```
The method `$e->getMessages()` returns an array of all messages as strings, and `$e->getMessageObjects()` returns all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects.
Defining the Schema
-------------------
And now let's create the schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it; we essentially define expectations for what the data should look like. Let's say 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 the schema definition looks understandable, even if you're seeing it for the first time.
Let's send the following data for validation:
```php
$data = [
'processRefund' => true,
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, passes validation
```
The output, i.e., the value `$normalized`, is a `stdClass` object. If we wanted the output to be an array, we would add casting `->castTo('array')` to the schema.
All elements of the structure are optional and have a default value of `null`. Example:
```php
$data = [
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, passes validation
// $normalized = {'processRefund' => null, 'refundAmount' => 17}
```
The fact that the default value is `null` does not mean it would accept `'processRefund' => null` in the input data. No, the input must be a boolean, i.e. `true` or `false` only. We would have to explicitly allow `null` using `Expect::bool()->nullable()`.
An item can be made mandatory using `Expect::bool()->required()`. We can change the default value, for example, to `false` using `Expect::bool()->default(false)` or shorthand `Expect::bool(false)`.
And what if we wanted to accept `1` and `0` in addition to booleans? Then we list the values that we also want to 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 defining a schema and how the structure items behave. We will now show what other elements you can use when defining a schema.
Data Types: type()
------------------
All standard PHP data types can be specified 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 = [])
Expect::list($default = [])
```
And also all types [supported by the Validators class](https://doc.nette.org/validators#toc-expected-types), for example `Expect::type('scalar')` or shorthand `Expect::scalar()`. Also class or interface names, e.g., `Expect::type('AddressEntity')`.
Union syntax can also be used:
```php
Expect::type('bool|string|array')
```
The default value is always `null` with the exception of `array` and `list`, where it is an empty array. (A list is an array indexed by a sequence of numeric keys starting from zero, i.e. a non-associative array).
Array of Values: arrayOf() listOf()
-----------------------------------
An array represents too general a structure; it's more useful to specify precisely which elements it may 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 second parameter can specify keys (since version 1.2):
```php
$schema = Expect::arrayOf('string', 'int');
$processor->process($schema, ['hello', 'world']); // OK
$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not an int
```
A 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: not a list
$processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: also not a list
```
With the `wrap` parameter, a single value is also accepted and wrapped into a one-item list (since version 1.4):
```php
$schema = Expect::listOf('string', wrap: true);
$processor->process($schema, 'hello'); // OK, gives ['hello']
$processor->process($schema, ['a', 'b']); // OK
```
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 a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)` (since version 1.1).
Enumeration: anyOf()
--------------------
`anyOf()` represents a set of values or schemas that a value can take. 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 elements of the enumeration 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 `anyOf()` method accepts variants as separate parameters, not as an array. To pass it an array of values, use the unpack operator `anyOf(...$variants)`.
Variants are tried in the order they are written and the first matching one wins. The single exception is `null`: when it belongs to the accepted values, a `null` input always gives `null`, even though a structure or an array variant would otherwise read it as an empty value of its own.
The default value is `null`. Use the `firstIsDefault()` method to make the first item the default:
```php
// default is 'hello'
Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault();
```
Enums: enum()
-------------
A configuration file can only carry a plain string like `'hearts'`, but in your code you would much rather work with an enum. That is the gap `enum()` closes (since version 1.4): give it an enum with a backing value (`enum Suit: string`) and it accepts either the backing value or the case itself, always handing you back the case:
```php
enum Suit: string
{
case Hearts = 'hearts';
case Spades = 'spades';
}
$schema = Expect::enum(Suit::class);
$processor->process($schema, 'hearts'); // OK, returns Suit::Hearts
$processor->process($schema, Suit::Spades); // OK, returns Suit::Spades
$processor->process($schema, 'clubs'); // ERROR: expects to be Suit
```
Enums backed by integers work exactly the same, and so does everything you know from the other elements, such as `Expect::enum(Suit::class)->required()` or `->default(Suit::Hearts)`.
When [generating a schema from a class](#mapping-to-objects-from), a `public Suit $suit` property gives you this very element, so you do not have to reach for `enum()` there. `Expect::type(Suit::class)` is a different thing: like any class name, it accepts only an instance, i.e. the case itself.
Structures
----------
Structures are objects with defined keys. Each key-value pair is referred to as a "property".
Structures accept arrays and objects and return `stdClass` objects.
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(), // default value is null
]);
$processor->process($schema, ['optional' => '']);
// ERROR: the mandatory item 'required' is missing
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo', 'optional' => null}
```
A structure itself is mandatory. Therefore, if it is nested inside another structure and the input does not contain it, it is created anyway - and it reports an error when it contains a required property. Use `required(false)` to make the entire nested structure optional. If it is missing in the input, `null` appears in the output, but if it is present, its required properties are enforced:
```php
$schema = Expect::structure([
'db' => Expect::structure([
'dsn' => Expect::string()->required(),
])->required(false),
]);
$processor->process($schema, []);
// OK, returns {'db' => null}
$processor->process($schema, ['db' => []]);
// ERROR: 'db › dsn' is missing
```
If you do not want properties with default values in the output, use `skipDefaults()`:
```php
$schema = Expect::structure([
'required' => Expect::string()->required(),
'optional' => Expect::string(),
])->skipDefaults();
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo'}
```
Although `null` is the default value for the `optional` property, it is not allowed in 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}
```
The array of all structure properties is returned by the `getShape()` method.
By default, no additional items can be present in the input data:
```php
$schema = Expect::structure([
'key' => Expect::string(),
]);
$processor->process($schema, ['additional' => 1]);
// ERROR: Unexpected item 'additional'
```
This can be changed using `otherItems()`. As a parameter, pass the schema to validate each extra item:
```php
$schema = Expect::structure([
'key' => Expect::string(),
])->otherItems(Expect::int());
$processor->process($schema, ['additional' => 1]); // OK
$processor->process($schema, ['additional' => true]); // ERROR
```
You can create a new structure by extending another using `extend()`:
```php
$dog = Expect::structure([
'name' => Expect::string(),
'age' => Expect::int(),
]);
$dogWithBreed = $dog->extend([
'breed' => Expect::string(),
]);
```
Array
-----
An array with defined keys (since version 1.3.2). Everything that applies to [structures](#structures) applies to it.
```php
$schema = Expect::array([
'required' => Expect::string()->required(),
'optional' => Expect::string(), // default value is null
]);
```
Tuples: tuple()
---------------
A tuple is a fixed-size array where each position has its own schema (since version 1.4):
```php
$schema = Expect::tuple([
Expect::int(),
Expect::string(),
Expect::bool(),
]);
$processor->process($schema, [1, 'hello', true]); // OK
```
The input must be a list, positions given by keys or in another order are refused. When configurations are layered, a later tuple replaces the earlier one wholesale - mixing positions of two tuples is never what you meant. Positions beyond the shape can be allowed with `otherItems()`, which describes the rest elements, and `extend()` appends further positions.
Unlike a structure, a tuple does not accept `null` as an empty value; call `nullable()` when `null` is a valid value.
Deprecated Properties
---------------------
You can mark a property as deprecated using the `deprecated([string $message])` method. Information about deprecation is returned using `$processor->getWarnings()`:
```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"]
```
Description: description()
--------------------------
Any element can carry a human-readable description (since version 1.4). It has no effect on validation - the schema is often the only place where the meaning of a configuration option is written down at all, and `description()` is where you write it. It also travels into the [JSON Schema export](#exporting-to-json-schema):
```php
$schema = Expect::structure([
'host' => Expect::string('localhost')->description('Database server hostname'),
'port' => Expect::int(3306)->description('Port the server listens on'),
])->description('Database connection');
```
Ranges: min() max()
-------------------
Use `min()` and `max()` to limit the count for arrays:
```php
// array, at least 10 items, maximum 20 items
Expect::array()->min(10)->max(20);
```
For strings, they limit the length:
```php
// string, at least 10 bytes long, maximum 20 bytes
Expect::string()->min(10)->max(20);
```
The length of a string is measured in bytes. To count characters of a UTF-8 string, use `Expect::unicode()`.
For numbers, they limit the value:
```php
// integer, between 10 and 20 inclusive
Expect::int()->min(10)->max(20);
```
Of course, it is possible to specify just `min()` or just `max()`:
```php
// string, maximum 20 bytes
Expect::string()->max(20);
```
Regular Expressions: pattern()
------------------------------
Using `pattern()`, you can specify a regular expression that the **entire** input string must match (i.e. as if it were wrapped in `^` and `$` characters):
```php
// exactly 9 digits
Expect::string()->pattern('\d{9}');
```
A pattern belongs to strings, just like `items()` belongs to arrays. Attach either of them to an element of a different kind and Schema raises a deprecation notice instead of silently ignoring the constraint (since version 1.4).
Custom Assertions: assert()
---------------------------
You can add any other constraints using `assert(callable $fn)`.
```php
$countIsEven = fn($v) => 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 an even count
```
Or
```php
Expect::string()->assert('is_file'); // file must exist
```
You can add a custom description to each assertion. 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 multiple constraints. It can be interleaved with calls to `transform()` and `castTo()`.
Transformation: transform()
---------------------------
Successfully validated data can be modified using a custom function:
```php
// convert to uppercase:
Expect::string()->transform(fn(string $s) => strtoupper($s));
```
The method can be called repeatedly to add multiple transformations. It can be interleaved with calls to `assert()` and `castTo()`. The operations are performed in the order in which they are declared:
```php
Expect::type('string|int')
->castTo('string')
->assert('ctype_lower', 'All characters must be lowercased')
->transform(fn(string $s) => strtoupper($s)); // convert to uppercase
```
The `transform()` method can simultaneously transform and validate the value. This is often simpler and involves less code duplication 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 problems:
```php
Expect::string()
->transform(function (string $s, Nette\Schema\Context $context) {
if (!ctype_lower($s)) {
$context->addError('All characters must be lowercased', 'my.case.error');
return null;
}
return strtoupper($s);
});
```
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. It distinguishes between a simple class without a constructor and a class with a constructor. If the class has no constructor, an instance is created, and all structure elements are written to the properties:
```php
class Info
{
public bool $processRefund;
public int $refundAmount;
}
Expect::structure([
'processRefund' => Expect::bool(),
'refundAmount' => Expect::int(),
])->castTo(Info::class);
// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount
```
If the class has a constructor, the structure elements are passed as named arguments to the constructor:
```php
class Info
{
public function __construct(
public bool $processRefund,
public int $refundAmount,
) {
}
}
// creates $obj = new Info(processRefund: ..., refundAmount: ...)
```
Casting combined with a scalar parameter creates an object and passes the value as the single argument to the constructor:
```php
Expect::string()->castTo(DateTime::class);
// creates new DateTime(...)
```
Normalization: before()
-----------------------
Before the validation itself, the data can be normalized using the `before()` method. As an example, let's take an element that must be an array of strings (e.g., `['a', 'b', 'c']`), but accepts input in the form of string `a b c`:
```php
$explode = fn($v) => explode(' ', $v);
$schema = Expect::arrayOf('string')
->before($explode);
$normalized = $processor->process($schema, 'a b c');
// OK and returns ['a', 'b', 'c']
```
An element has one handler: a second call to `before()` replaces the first one and raises a deprecation notice (since version 1.4), because in version 2.0 the handlers will be chained, each receiving the result of the previous one. Put all the normalization into one handler instead.
Mapping to Objects: from()
--------------------------
You can have the structure schema generated from a class. Example:
```php
class Config
{
public string $name;
public string|null $password = null;
public bool $admin = false;
}
$schema = Expect::from(new Config);
$data = [
'name' => 'Frank',
];
$normalized = $processor->process($schema, $data);
// $normalized instanceof Config
// $normalized = {'name' => 'Frank', 'password' => null, 'admin' => false}
```
Anonymous classes are also supported:
```php
$schema = Expect::from(new class {
public string $name;
public ?string $password = null;
public bool $admin = false;
});
```
Because the information obtained from the class definition may not be sufficient, you can supplement the elements with your own schema using the second parameter:
```php
$schema = Expect::from(new Config, [
'name' => Expect::string()->pattern('\w:.*'),
]);
```
Merging Multiple Configurations
-------------------------------
Applications often assemble their configuration in layers: there are built-in default values, and on top of them the user supplies their own settings, which should override only the items they actually specify. That is exactly what `processMultiple()` does - it takes several datasets, merges them in order so that later ones take precedence, and validates the final result as a whole:
```php
$schema = Expect::structure([
'host' => Expect::string(),
'port' => Expect::int(),
'logging' => Expect::bool(),
]);
$defaults = ['host' => 'localhost', 'port' => 3306, 'logging' => false];
$userConfig = ['port' => 5432, 'logging' => true];
$config = $processor->processMultiple($schema, [$defaults, $userConfig]);
// $config = {'host' => 'localhost', 'port' => 5432, 'logging' => true}
```
The `host` item keeps its default value because the user did not set it, while `port` and `logging` are overwritten by the later dataset. Values stored under string keys are merged this way; the items of a list (`listOf()`, `arrayOf()`) are appended one after another instead of being overwritten.
Arrays and structures can set their strategy with `mergeMode()` (since version 1.4):
```php
use Nette\Schema\MergeMode;
Expect::arrayOf('string')->mergeMode(MergeMode::Replace); // the later array replaces the earlier one
```
`MergeMode::AppendKeys` merges by keys and appends list items, `OverwriteKeys` merges by keys and overwrites list items by position, and `Replace` keeps only the later value. Without `mergeMode()`, an array whose items are not described is merged deeply. For anything else, `mergeWith()` takes your own function combining the later value with the earlier one:
```php
Expect::bool()->mergeWith(fn($value, $base) => $value || $base); // once enabled, stays enabled
```
Exporting to JSON Schema
------------------------
Your schema is already a precise description of what the configuration may contain, and that description is useful outside PHP as well. `JsonSchema::export()` (since version 1.4) turns it into a [JSON Schema](https://json-schema.org) document, the format editors read to offer completion and underline mistakes directly in the JSON or YAML file:
```php
use Nette\Schema\JsonSchema;
$schema = Expect::structure([
'host' => Expect::string('localhost')->description('Database server hostname'),
'port' => Expect::int(3306)->min(1)->max(65535),
'user' => Expect::string()->required(),
]);
echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT);
```
```json
{
"type": "object",
"properties": {
"host": {"type": "string", "description": "Database server hostname"},
"port": {"type": "integer", "minimum": 1, "maximum": 65535},
"user": {"type": "string"}
},
"required": ["user"],
"additionalProperties": false
}
```
The export describes the **shape** of the data: types, ranges, patterns, required items, enum values and the texts you added with `description()`. Default values, `castTo()` and `transform()` are deliberately left out - they describe what happens to the data once it has been validated, and JSON Schema has no way to say that.
For the same reason, a type that exists only in PHP - a class such as `Expect::type(Address::class)`, a callable or a resource - throws `Nette\NotSupportedException` instead of producing a document that would quietly claim something else.
Two differences remain between the export and the validation. JSON Schema counts the length of a string in characters, while `Expect::string()` counts bytes, so use `Expect::unicode()` for text that is not plain ASCII. And a `pattern()` is exported as it is, but a JSON Schema validator reads it as an ECMAScript regular expression, so constructions specific to PCRE may be understood differently there.
Under the Hood: normalize, merge, complete
------------------------------------------
Every schema element - whether built-in or one you write yourself - implements four methods that together define how it handles data. Three of them form the processing pipeline:
1. **normalize()** - prepares the raw input. This is where `before()` hooks run and where, for example, an object is turned into an array. It runs first, separately on each dataset.
2. **merge()** - combines two already normalized datasets, with the later one taking priority. This step is used only by `processMultiple()`; `process()` skips it, because it has just a single dataset.
3. **complete()** - performs the actual validation, fills in default values for missing items, and applies `assert()`, `transform()` and `castTo()`. It runs last, on the merged result.
The fourth method, **completeDefault()**, is called by the parent element for an item entirely missing from the input - it either supplies the default value or reports that a `required()` item is missing.
So `process()` runs *normalize → complete*, while `processMultiple()` runs *normalize (each dataset) → merge → complete*. This order is why `before()` sees the raw input, whereas `transform()` sees the already validated value.
Custom Schema Elements
----------------------
You can get a long way with `assert()`, `transform()` and `before()`, so you rarely need to build anything from scratch. But when you want a reusable, self-contained element with its own validation and merging logic, you can create one by implementing the [Nette\Schema\Schema](https://api.nette.org/schema/master/Nette/Schema/Schema.html) interface. It has exactly the four methods described above:
```php
interface Schema
{
function normalize(mixed $value, Context $context);
function merge(mixed $value, mixed $base);
function complete(mixed $value, Context $context);
function completeDefault(Context $context);
}
```
Errors are not thrown; instead you report them through the [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object using `$context->addError()` and return `null`. The `Processor` gathers all errors and throws them together at the end.
As an example, let's build a reusable element for byte sizes in the friendly notation people use in configuration files - `'512kB'`, `'2 MB'` - which validates them and returns the number of bytes:
```php
use Nette\Schema\Context;
use Nette\Schema\Schema;
class ByteSizeSchema implements Schema
{
private const Units = ['b' => 1, 'kb' => 1024, 'mb' => 1024 ** 2, 'gb' => 1024 ** 3];
public function normalize(mixed $value, Context $context): mixed
{
return is_int($value) ? "$value B" : $value; // unify both notations
}
public function merge(mixed $value, mixed $base): mixed
{
return $value ?? $base; // the later value wins
}
public function complete(mixed $value, Context $context): mixed
{
if (!is_string($value) || !preg_match('~^(\d+)\s*([a-zA-Z]+)$~', $value, $m)) {
$context->addError("The item %path% expects to be a size like '512kB'.", 'size.format');
return null;
}
$unit = self::Units[strtolower($m[2])] ?? null;
if ($unit === null) {
$context->addError("The item %path% uses an unknown unit '$m[2]'.", 'size.unit');
return null;
}
return (int) $m[1] * $unit;
}
public function completeDefault(Context $context): mixed
{
return null; // value used when the item is missing from the input
}
}
```
You can use it anywhere a built-in element is expected - on its own or as part of a larger structure:
```php
$schema = Expect::structure([
'maxUpload' => new ByteSizeSchema,
'diskQuota' => new ByteSizeSchema,
]);
$processor->process($schema, ['maxUpload' => '2 MB', 'diskQuota' => 512]);
// OK, returns {'maxUpload' => 2097152, 'diskQuota' => 512}
$processor->process($schema, ['maxUpload' => '5 TB']);
// ERROR: The item 'maxUpload' uses an unknown unit 'TB'.
```
Because the element implements the whole interface, it also works automatically inside `processMultiple()` - the `Processor` calls its `merge()` method just like for any other element. Only `JsonSchema::export()` cannot know what such an element accepts, so it throws `Nette\NotSupportedException`.
+66
View File
@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use function count;
/**
* Accumulates errors and warnings during schema validation and tracks the current path.
*/
final class Context
{
public bool $skipDefaults = false;
/**
* @internal path at which a null is not coerced to an empty value, because the enclosing anyOf() accepts it
* @var ?list<int|string>
*/
public ?array $keepNullAt = null;
/** @var list<int|string> */
public array $path = [];
public bool $isKey = false;
/** @var list<Message> */
public array $errors = [];
/** @var list<Message> */
public array $warnings = [];
/** @var list<array{DynamicParameter, string, list<int|string>}> */
public array $dynamics = [];
/** @param array<string, mixed> $variables */
public function addError(string $message, string $code, array $variables = []): Message
{
$variables['isKey'] = $this->isKey;
return $this->errors[] = new Message($message, $code, $this->path, $variables);
}
/** @param array<string, mixed> $variables */
public function addWarning(string $message, string $code, array $variables = []): Message
{
$variables['isKey'] = $this->isKey;
return $this->warnings[] = new Message($message, $code, $this->path, $variables);
}
/**
* Returns a closure that returns true as long as no new errors have been added since the call.
* @return \Closure(): bool
*/
public function createChecker(): \Closure
{
$count = count($this->errors);
return fn(): bool => $count === count($this->errors);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
interface DynamicParameter
{
}
+212
View File
@@ -0,0 +1,212 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, Helpers, Kind, Schema};
use function is_array;
/**
* Schema that accepts any of a fixed set of values or sub-schemas (union type / enumeration).
*/
final class AnyOf implements Schema
{
use Base;
/** @var mixed[] */
private array $set;
private bool $dynamic = false;
public function __construct(mixed ...$set)
{
if (!$set) {
throw new Nette\InvalidStateException('The enumeration must not be empty.');
}
$this->set = $set;
}
/**
* Sets the first variant as the default value (instead of null).
*/
public function firstIsDefault(): self
{
$this->default = $this->set[0];
return $this;
}
/**
* Allows null as an accepted value in addition to the defined variants.
*/
public function nullable(): self
{
$this->set[] = null;
return $this;
}
/**
* Allows the value to be a DynamicParameter as an accepted variant.
*/
public function dynamic(): self
{
$this->dynamic = true;
return $this;
}
/********************* inspection ****************d*g**/
/**
* Scalar variants are reported as 'values', schema variants as 'variants'; scalars alone make an Enum,
* anything with a schema variant a Union.
* @return array<string, mixed>
* @internal
*/
public function describe(): array
{
$values = $variants = [];
$nullable = false;
foreach ($this->set as $item) {
if ($item === null) {
$nullable = true;
} elseif (!$item instanceof Schema) {
$values[] = $item;
} else {
$variants[] = $item;
}
}
return [
'kind' => match (true) {
(bool) $variants => Kind::Union,
(bool) $values => Kind::Enum,
default => $nullable ? Kind::Null : Kind::Any,
},
'values' => $values,
'variants' => $variants,
'nullable' => $nullable,
'dynamic' => $this->dynamic,
] + $this->describeBase();
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
return $this->doNormalize($value, $context);
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
return $value;
}
if ($this->mergeWith) {
return ($this->mergeWith)($value, $base);
}
return Helpers::merge($value, $base);
}
public function complete(mixed $value, Context $context): mixed
{
$this->doDeprecation($context);
$isOk = $context->createChecker();
$value = $this->findAlternative($value, $context);
$isOk() && $value = $this->doTransform($value, $context);
return $isOk() ? $value : null;
}
private function findAlternative(mixed $value, Context $context): mixed
{
$keepNullAt = $value === null && in_array(null, $this->set, true)
? $context->path
: $context->keepNullAt;
$expecteds = $innerErrors = [];
foreach ($this->set as $item) {
if ($item instanceof Schema) {
$dolly = new Context;
$dolly->skipDefaults = $context->skipDefaults;
$dolly->isKey = $context->isKey;
$dolly->path = $context->path;
$dolly->keepNullAt = $keepNullAt;
$res = $item->complete($item->normalize($value, $dolly), $dolly);
if (!$dolly->errors) {
$context->warnings = [...$context->warnings, ...$dolly->warnings];
$context->dynamics = [...$context->dynamics, ...$dolly->dynamics];
return $res;
}
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 $value;
}
$expecteds[] = Nette\Schema\Helpers::formatValue($item);
}
}
if ($this->dynamic && $value instanceof Nette\Schema\DynamicParameter) {
return $value;
}
if ($innerErrors) {
$context->errors = [...$context->errors, ...$innerErrors];
} else {
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Nette\Schema\Message::TypeMismatch,
[
'value' => $value,
'expected' => implode('|', array_unique($expecteds)),
],
);
}
return null;
}
public function completeDefault(Context $context): mixed
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
);
return null;
}
if ($this->default instanceof Schema) {
return $this->default->completeDefault($context);
}
return $this->default;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette\Schema\{Context, MergeMode, Schema};
use function is_array;
/**
* An array, a list or an iterable, optionally with a schema for its items and keys.
*/
final class ArrayType extends Type
{
public function __construct(
string $type,
/** a single value is accepted and wrapped into a one-item list */
private readonly bool $wrap = false,
) {
parent::__construct($type);
}
public function doNormalize(mixed $value, Context $context): mixed
{
$value = parent::doNormalize($value, $context);
return $this->wrap && !is_array($value) && $value !== null ? [$value] : $value;
}
/**
* Sets the schema of items and optionally of keys.
*/
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static
{
return parent::items($valueType, $keyType);
}
/**
* Sets how the array is combined when merging multiple configuration layers.
*/
public function mergeMode(MergeMode $mode): static
{
return parent::mergeMode($mode);
}
/** @deprecated an array has no pattern */
public function pattern(?string $pattern): static
{
trigger_error(__METHOD__ . '() is deprecated, an array has no pattern.', E_USER_DEPRECATED);
return parent::pattern($pattern);
}
public function describe(): array
{
return parent::describe() + ['wrap' => $this->wrap];
}
}
+224
View File
@@ -0,0 +1,224 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, Helpers};
use function count, is_string;
/**
* @internal
*/
trait Base
{
private bool $required = false;
private mixed $default = null;
/** @var ?\Closure(mixed): mixed */
private ?\Closure $before = null;
/** @var list<\Closure(mixed, Context): mixed> */
private array $transforms = [];
private ?string $deprecated = null;
private ?string $description = null;
/** @var ?\Closure(mixed, mixed): mixed */
private ?\Closure $mergeWith = null;
public function default(mixed $value): static
{
$this->default = $value;
return $this;
}
public function required(bool $state = true): static
{
$this->required = $state;
return $this;
}
/**
* Sets a pre-normalization callback applied to the raw input value before any validation.
* @param callable(mixed): mixed $handler
*/
public function before(callable $handler): static
{
if ($this->before) {
trigger_error(
'Calling before() repeatedly is deprecated, it replaces the previous handler while in 2.0 the handlers will be chained; merge them into one.',
E_USER_DEPRECATED,
);
}
$this->before = $handler(...);
return $this;
}
/**
* Sets a custom strategy combining two layers. Must be a pure combiner; canonicalize layer shape in before() instead.
* Either side may be null, a layer can legally be null.
* @param callable(mixed, mixed): mixed $fn
*/
public function mergeWith(callable $fn): static
{
$this->mergeWith = $fn(...);
return $this;
}
/**
* Casts the validated value to a built-in type or instantiates the given class; a null stays null for a class or ?type.
*/
public function castTo(string $type): static
{
return $this->transform(Helpers::getCastStrategy($type));
}
/**
* Adds a post-validation transformation callback. The handler may also report errors via Context.
* @param callable(mixed, Context): mixed $handler
*/
public function transform(callable $handler): static
{
$this->transforms[] = $handler(...);
return $this;
}
/**
* Adds a custom validation assertion; optionally describe it for error messages.
* @param callable(mixed): bool $handler
*/
public function assert(callable $handler, ?string $description = null): static
{
$expected = $description ?? (is_string($handler) ? "$handler()" : '#' . count($this->transforms));
return $this->transform(function ($value, Context $context) use ($handler, $description, $expected) {
if ($handler($value)) {
return $value;
}
$context->addError(
'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.',
Nette\Schema\Message::FailedAssertion,
['value' => $value, 'assertion' => $expected],
);
return null;
});
}
/**
* Marks the item as deprecated; emits a warning with the given message when the item is used.
*/
public function deprecated(string $message = 'The item %path% is deprecated.'): static
{
$this->deprecated = $message;
return $this;
}
/**
* Sets a human-readable description of the item; it does not affect validation.
*/
public function description(string $description): static
{
$this->description = $description;
return $this;
}
/**
* The metadata every element reports from describe(); the element adds its own keys.
* @return array{required: bool, description: ?string}
*/
protected function describeBase(): array
{
return ['required' => $this->required, 'description' => $this->description];
}
public function completeDefault(Context $context): mixed
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
);
return null;
}
return $this->default;
}
public function doNormalize(mixed $value, Context $context): mixed
{
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 doTransform(mixed $value, Context $context): mixed
{
$isOk = $context->createChecker();
foreach ($this->transforms as $handler) {
$value = $handler($value, $context);
if (!$isOk()) {
return null;
}
}
return $value;
}
/** @deprecated use Nette\Schema\Helpers::validateType() */
private function doValidate(mixed $value, string $expected, Context $context): bool
{
$isOk = $context->createChecker();
Helpers::validateType($value, $expected, $context);
return $isOk();
}
/**
* @deprecated use Nette\Schema\Helpers::validateRange()
* @param array{int|float|null, int|float|null} $range
*/
private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool
{
$isOk = $context->createChecker();
Helpers::validateRange($value, $range, $context, $types);
return $isOk();
}
/** @deprecated use doTransform() */
private function doFinalize(mixed $value, Context $context): mixed
{
return $this->doTransform($value, $context);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, Kind};
use function is_int, is_string;
/**
* A backed enum: accepts a case or its backing value and yields the case.
*/
final class EnumType extends Type
{
public function __construct(
/** @var class-string<\BackedEnum> */
private string $enum,
) {
if (!is_subclass_of($enum, \BackedEnum::class)) {
throw new Nette\InvalidArgumentException("'$enum' is not a backed enum.");
}
parent::__construct($enum);
}
public function doNormalize(mixed $value, Context $context): mixed
{
$value = parent::doNormalize($value, $context);
try {
return is_int($value) || is_string($value) ? $this->enum::tryFrom($value) ?? $value : $value;
} catch (\TypeError) {
return $value; // a string for an int-backed enum and vice versa
}
}
public function describe(): array
{
return [
'kind' => Kind::Enum,
'values' => array_map(fn(\BackedEnum $case) => $case->value, ($this->enum)::cases()),
] + parent::describe();
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette\Schema\Schema;
/**
* An int or a float.
*/
final class NumberType extends Type
{
/** @deprecated a number has no pattern */
public function pattern(?string $pattern): static
{
trigger_error(__METHOD__ . '() is deprecated, a number has no pattern.', E_USER_DEPRECATED);
return parent::pattern($pattern);
}
/** @deprecated a number has no items */
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static
{
trigger_error(__METHOD__ . '() is deprecated, a number has no items.', E_USER_DEPRECATED);
return parent::items($valueType, $keyType);
}
/** @deprecated a number has no default merging */
public function mergeDefaults(bool $state = true): static
{
trigger_error(__METHOD__ . '() is deprecated, a number has no default merging.', E_USER_DEPRECATED);
return parent::mergeDefaults($state);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette\Schema\Schema;
/**
* A string, plain or in a specified format.
*/
final class StringType extends Type
{
/** @deprecated a string has no items */
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static
{
trigger_error(__METHOD__ . '() is deprecated, a string has no items.', E_USER_DEPRECATED);
return parent::items($valueType, $keyType);
}
/** @deprecated a string has no default merging */
public function mergeDefaults(bool $state = true): static
{
trigger_error(__METHOD__ . '() is deprecated, a string has no default merging.', E_USER_DEPRECATED);
return parent::mergeDefaults($state);
}
}
+274
View File
@@ -0,0 +1,274 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, Helpers, Kind, MergeMode, Schema};
use function array_key_exists, is_array, is_object;
final class Structure implements Schema
{
use Base;
/** @var Schema[] */
private array $items;
/** for array|list */
private ?Schema $otherItems = null;
/** @var array{?int, ?int} */
private array $range = [null, null];
private bool $skipDefaults = false;
private ?MergeMode $mergeMode = null;
/** @param Schema[] $shape */
public function __construct(array $shape)
{
(function (Schema ...$items) {})(...array_values($shape));
$this->items = $shape;
$this->castTo('object');
$this->required = true;
}
/**
* Not supported for structures; always throws.
*/
public function default(mixed $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;
}
/**
* Allows extra keys not defined in the shape, validating their values against the given type.
*/
public function otherItems(string|Schema $type = 'mixed'): self
{
$this->otherItems = $type instanceof Schema ? $type : Nette\Schema\Expect::type($type);
return $this;
}
/**
* When enabled, missing properties are not filled with their default values.
*/
public function skipDefaults(bool $state = true): self
{
$this->skipDefaults = $state;
return $this;
}
/**
* Sets how the structure is combined when merging multiple configuration layers.
*/
public function mergeMode(MergeMode $mode): self
{
$this->mergeMode = $mode;
return $this;
}
/**
* Creates a new structure by merging this shape with additional properties.
* @param Schema[]|self $shape
*/
public function extend(array|self $shape): self
{
$shape = $shape instanceof self ? $shape->items : $shape;
return new self([...$this->items, ...$shape]);
}
/** @return Schema[] */
public function getShape(): array
{
return $this->items;
}
/********************* inspection ****************d*g**/
/**
* @return array<string, mixed>
* @internal
*/
public function describe(): array
{
return [
'kind' => Kind::Structure,
'shape' => $this->items,
'otherItems' => $this->otherItems,
'min' => $this->range[0],
'max' => $this->range[1],
] + $this->describeBase();
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
}
$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::PreventMerging] = true;
}
}
return $value;
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
return $value;
}
if ($this->mergeWith) {
return ($this->mergeWith)($value, $base);
}
$mode = $this->mergeMode ?? ($this->otherItems === null ? MergeMode::OverwriteKeys : MergeMode::AppendKeys);
if ($mode === MergeMode::Replace) {
return $value;
}
if (is_array($value) && is_array($base)) {
$index = $mode === MergeMode::OverwriteKeys ? null : 0;
foreach ($value as $key => $val) {
if ($key === $index) {
$base[] = $val;
$index++;
} else {
$base[$key] = array_key_exists($key, $base) && ($itemSchema = $this->items[$key] ?? $this->otherItems)
? $itemSchema->merge($val, $base[$key])
: $val;
}
}
return $base;
}
return $value ?? $base;
}
public function complete(mixed $value, Context $context): mixed
{
// the marker travels with the value through normalize() and merge() consumes it; the layer that has
// nothing under it keeps it, and it is not an item of the shape
if (is_array($value)) {
unset($value[Helpers::PreventMerging]);
}
if ($value === null && $context->keepNullAt !== $context->path) {
$value = []; // is unable to distinguish null from array in NEON
}
$this->doDeprecation($context);
$isOk = $context->createChecker();
Helpers::validateType($value, 'array', $context);
$isOk() && Helpers::validateRange($value, $this->range, $context);
$isOk() && $this->validateItems($value, $context);
$isOk() && $value = $this->doTransform($value, $context);
return $isOk() ? $value : null;
}
/** @param array<mixed> $value */
private function validateItems(array &$value, Context $context): void
{
$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\Helpers::getSuggestion($keys, (string) $key);
$context->addError(
'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'),
Nette\Schema\Message::UnexpectedItem,
['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);
}
}
public function completeDefault(Context $context): mixed
{
if (!$this->required) {
return null;
}
// the item is missing in the input, do not report it as used deprecated
$deprecated = $this->deprecated;
$this->deprecated = null;
try {
return $this->complete([], $context);
} finally {
$this->deprecated = $deprecated;
}
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, Kind, Message, Schema};
use function count;
/**
* A fixed-size list where each position has its own schema; a later layer replaces the tuple wholesale.
*/
final class TupleType extends Type
{
/** @var list<Schema> */
private array $items;
/** the rest elements */
private ?Schema $otherItems = null;
/** @param Schema[] $shape */
public function __construct(array $shape)
{
if (!array_is_list($shape)) {
throw new Nette\InvalidArgumentException('Tuple shape must be indexed array.');
}
(function (Schema ...$items) {})(...$shape);
parent::__construct('list');
parent::default(null); // a tuple of nothing is not a value, so null is not coerced to one
$this->items = $shape;
}
/**
* Not supported for tuples; always throws.
*/
public function default(mixed $value): static
{
throw new Nette\InvalidStateException('Tuple cannot have default value.');
}
/**
* Allows positions beyond the shape, validating them against the given type.
*/
public function otherItems(string|Schema $type = 'mixed'): self
{
$this->otherItems = $type instanceof Schema ? $type : Nette\Schema\Expect::type($type);
return $this;
}
/**
* Appends positions to the tuple.
* @param Schema[]|self $shape
*/
public function extend(array|self $shape): self
{
$shape = $shape instanceof self ? $shape->items : $shape;
return new self([...$this->items, ...$shape]);
}
/** @return list<Schema> */
public function getShape(): array
{
return $this->items;
}
public function describe(): array
{
return ['kind' => Kind::Tuple, 'shape' => $this->items, 'otherItems' => $this->otherItems] + parent::describe();
}
protected function mergeValues(mixed $value, mixed $base): mixed
{
return $value;
}
protected function normalizeItems(array $value, Context $context): array
{
foreach ($value as $key => $val) {
if ($itemSchema = $this->items[$key] ?? $this->otherItems) {
$context->path[] = $key;
$value[$key] = $itemSchema->normalize($val, $context);
array_pop($context->path);
}
}
return $value;
}
protected function validateItems(array &$value, Context $context): void
{
foreach ($value as $index => $val) {
$context->path[] = $index;
if ($itemSchema = $this->items[$index] ?? $this->otherItems) {
$value[$index] = $itemSchema->complete($val, $context);
} else {
$context->addError('Unexpected item %path%.', Message::UnexpectedItem);
}
array_pop($context->path);
}
for ($index = count($value); $index < count($this->items); $index++) {
$context->path[] = $index;
$default = $this->items[$index]->completeDefault($context); // checks required item
if (!$context->skipDefaults) {
$value[] = $default;
}
array_pop($context->path);
}
}
}
+359
View File
@@ -0,0 +1,359 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\{Context, DynamicParameter, Helpers, Kind, MergeMode, Message, Schema, TypeExpression};
use Nette\Utils\Validators;
use function array_key_exists, is_array, is_int, is_string;
use const INF;
class Type implements Schema
{
use Base;
private ?Schema $itemsValue = null;
private ?Schema $itemsKey = null;
/** @var array{int|float|null, int|float|null} */
private array $range = [null, null];
private ?string $pattern = null;
private bool $merge = true;
private ?MergeMode $mergeMode = null;
public function __construct(
private string $type,
) {
$defaults = ['list' => [], 'array' => []];
$this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null;
}
/**
* Allows the value to be null in addition to the declared type.
*/
public function nullable(): static
{
$this->type = 'null|' . $this->type;
return $this;
}
/**
* Controls whether the default value is merged with the input array (enabled by default).
*/
public function mergeDefaults(bool $state = true): static
{
$this->unionDeprecated('mergeDefaults');
$this->merge = $state;
return $this;
}
/** @internal */
protected function mergeMode(MergeMode $mode): static
{
$this->mergeMode = $mode;
return $this;
}
/**
* Allows the value to be a DynamicParameter, which is recorded for deferred validation.
*/
public function dynamic(): static
{
$this->type = DynamicParameter::class . '|' . $this->type;
return $this;
}
public function min(int|float|null $min): static
{
$this->unionDeprecated('min');
$this->range[0] = $min;
return $this;
}
public function max(int|float|null $max): static
{
$this->unionDeprecated('max');
$this->range[1] = $max;
return $this;
}
/**
* @internal use arrayOf() or listOf()
*/
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): static
{
$this->unionDeprecated('items');
$this->itemsValue = $valueType instanceof Schema
? $valueType
: Nette\Schema\Expect::type($valueType);
$this->itemsKey = $keyType instanceof Schema || $keyType === null
? $keyType
: Nette\Schema\Expect::type($keyType);
return $this;
}
/**
* Sets a regex pattern the string value must match entirely (anchored to start and end).
*/
public function pattern(?string $pattern): static
{
$this->unionDeprecated('pattern');
$this->pattern = $pattern;
return $this;
}
/**
* A union of kinds ('int|string') becomes anyOf() in the next major and takes no options of its own;
* they belong to the variants: anyOf(Expect::int()->min(1), Expect::string()->min(1)).
*/
private function unionDeprecated(string $option): void
{
if (static::class === self::class && $this->getParsed()['kind'] === Kind::Union) {
trigger_error(
"$option() on the union '$this->type' is deprecated, give it to the variants of anyOf() instead.",
E_USER_DEPRECATED,
);
}
}
/********************* inspection ****************d*g**/
/**
* Reports what the type accepts as a plain array (see TypeExpression::parse()); min(), max(), pattern()
* and items() narrow every variant they apply to, child schemas are reported as they are.
* @return array<string, mixed>
* @internal
*/
public function describe(): array
{
return $this->narrow($this->getParsed()) + $this->describeBase();
}
/**
* The parsed expression; 'kind', 'nullable', 'dynamic' and the keys of the kind.
* @return array<string, mixed>
*/
protected function getParsed(): array
{
return TypeExpression::parse($this->type);
}
/**
* Puts min(), max(), pattern() and items() into every variant of the parsed expression that has the key.
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private function narrow(array $item): array
{
if ($item['kind'] === Kind::Union) {
$item['variants'] = array_map($this->narrow(...), $item['variants']);
}
if (array_key_exists('min', $item)) { // both bounds are checked, so the tighter one holds
$item['min'] = $this->range[0] === null ? $item['min'] : max($this->range[0], $item['min'] ?? -INF);
$item['max'] = $this->range[1] === null ? $item['max'] : min($this->range[1], $item['max'] ?? INF);
}
if (array_key_exists('pattern', $item)) {
$item['pattern'] = $this->pattern ?? $item['pattern'];
}
if (array_key_exists('items', $item)) {
$item['items'] = $this->itemsValue ?? $item['items'];
$item['keys'] = $this->itemsKey ?? $item['keys'];
}
return $item;
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
}
$value = $this->doNormalize($value, $context);
if (is_array($value)) {
$value = $this->normalizeItems($value, $context);
}
if ($prevent && is_array($value)) {
$value[Helpers::PreventMerging] = true;
}
return $value;
}
/**
* @param array<mixed> $value
* @return array<mixed>
* @internal
*/
protected function normalizeItems(array $value, Context $context): array
{
if (!$this->itemsValue) {
return $value;
}
$res = [];
foreach ($value as $key => $val) {
$context->path[] = $key;
$context->isKey = true;
$key = $this->itemsKey
? $this->itemsKey->normalize($key, $context)
: $key;
if (!is_int($key) && !is_string($key)) {
$context->addError(
'The %label% %path% expects to be int|string, %value% given.',
Message::TypeMismatch,
['value' => $key, 'expected' => 'int|string'],
);
$context->isKey = false;
array_pop($context->path);
continue;
}
$context->isKey = false;
$res[$key] = $this->itemsValue->normalize($val, $context);
array_pop($context->path);
}
return $res;
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
return $value;
}
if ($this->mergeWith) {
return ($this->mergeWith)($value, $base);
}
return $this->mergeValues($value, $base);
}
/**
* Without a mode, an array without described items merges deeply.
* @internal
*/
protected function mergeValues(mixed $value, mixed $base): mixed
{
if ($this->mergeMode === MergeMode::Replace) {
return $value;
}
if (is_array($value) && is_array($base) && ($this->itemsValue || $this->mergeMode)) {
$index = $this->mergeMode === MergeMode::OverwriteKeys ? null : 0;
foreach ($value as $key => $val) {
if ($key === $index) {
$base[] = $val;
$index++;
} else {
$base[$key] = array_key_exists($key, $base) && $this->itemsValue
? $this->itemsValue->merge($val, $base[$key])
: $val;
}
}
return $base;
}
return Helpers::merge($value, $base);
}
public function complete(mixed $value, Context $context): mixed
{
$merge = $this->merge;
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
$merge = false;
}
if ($value === null && is_array($this->default) && !Validators::is(null, $this->type) && $context->keepNullAt !== $context->path) {
$value = []; // is unable to distinguish null from array in NEON
}
$this->doDeprecation($context);
$isOk = $context->createChecker();
Helpers::validateType($value, $this->type, $context);
$isOk() && Helpers::validateRange($value, $this->range, $context, $this->type);
$isOk() && $value !== null && $this->pattern !== null && Helpers::validatePattern($value, $this->pattern, $context);
$isOk() && is_array($value) && $this->validateItems($value, $context);
$isOk() && $merge && $value !== null && $value = Helpers::merge($value, $this->default);
$isOk() && $value = $this->doTransform($value, $context);
if (!$isOk()) {
return null;
}
if ($value instanceof DynamicParameter && $this->type !== DynamicParameter::class) {
$expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range));
$context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path];
}
return $value;
}
/**
* @param array<mixed> $value
* @internal
*/
protected function validateItems(array &$value, Context $context): void
{
if (!($itemsValue = $this->itemsValue)) {
return;
}
$res = [];
foreach ($value as $key => $val) {
$context->path[] = $key;
$context->isKey = true;
$isKeyOk = $context->createChecker();
$key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key;
if ($isKeyOk() && !is_int($key) && !is_string($key)) {
$context->addError(
'The %label% %path% expects to be int|string, %value% given.',
Message::TypeMismatch,
['value' => $key, 'expected' => 'int|string'],
);
}
$context->isKey = false;
$keyOk = $isKeyOk();
$val = $itemsValue->complete($val, $context);
if ($keyOk) {
$res[$key] = $val;
}
array_pop($context->path);
}
$value = $res;
}
}
+188
View File
@@ -0,0 +1,188 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
use Nette\Schema\Elements\{AnyOf, ArrayType, EnumType, NumberType, StringType, Structure, Type};
use function array_key_exists, count, is_object;
/**
* Schema generator.
*
* @method static Type scalar($default = null)
* @method static StringType string($default = null)
* @method static NumberType int($default = null)
* @method static NumberType float($default = null)
* @method static Type bool($default = null)
* @method static Type null()
* @method static ArrayType list($default = [])
* @method static Type mixed($default = null)
* @method static StringType email($default = null)
* @method static StringType unicode($default = null)
*/
final class Expect
{
/** @param array<int|string, mixed> $args */
public static function __callStatic(string $name, array $args): Type
{
$type = self::type($name);
if ($args) {
$type->default(array_key_exists('default', $args) ? $args['default'] : $args[0]);
}
return $type;
}
/**
* Creates a schema for a type expression (e.g., 'int|string', 'null|float', 'email'); an expression
* of a single kind of value gets its dedicated StringType, NumberType or ArrayType. An enum class means
* instanceof, as any class; Expect::enum() accepts its backing values.
*/
public static function type(string $type): Type
{
$class = self::typeClass(TypeExpression::parse($type));
return new $class($type);
}
/**
* The subclass of Type that Expect::type() returns for a parsed expression: the dedicated one when
* every variant is of its kind, the plain Type otherwise.
* @param array<string, mixed> $item
* @return class-string<Type>
* @internal
*/
public static function typeClass(array $item): string
{
$variants = $item['kind'] === Kind::Union ? $item['variants'] : [$item];
$classes = array_unique(array_map(fn(array $variant) => match ($variant['kind']) {
Kind::String => StringType::class,
Kind::Int, Kind::Float, Kind::Number => NumberType::class,
Kind::Array, Kind::List, Kind::Iterable => ArrayType::class,
default => Type::class,
}, $variants));
return count($classes) === 1 ? reset($classes) : Type::class;
}
/**
* Creates a schema for a backed enum: a case or its backing value is accepted, the case is returned.
* @param class-string<\BackedEnum> $enum
*/
public static function enum(string $enum): EnumType
{
return new EnumType($enum);
}
/**
* Creates a union schema that accepts any of the given values or sub-schemas.
*/
public static function anyOf(mixed ...$set): AnyOf
{
return new AnyOf(...$set);
}
/**
* Creates a structure schema with defined properties; output is stdClass.
* @param Schema[] $shape
*/
public static function structure(array $shape): Structure
{
return new Structure($shape);
}
/**
* Generates a structure schema from a class instance by reflecting its properties or constructor parameters.
* @param array<string, Schema> $items Optional overrides for specific properties.
*/
public static function from(object $object, array $items = []): Structure
{
$ro = new \ReflectionObject($object);
$props = $ro->hasMethod('__construct')
? $ro->getMethod('__construct')->getParameters()
: array_filter($ro->getProperties(\ReflectionProperty::IS_PUBLIC), fn($prop) => !$prop->isStatic());
foreach ($props as $prop) {
$name = $prop->getName();
if ($prop instanceof \ReflectionParameter && $prop->isVariadic()) {
throw new Nette\InvalidArgumentException("Variadic parameter \$$name of {$ro->getName()}::__construct() is not supported by Expect::from().");
} elseif (!isset($items[$name])) {
$type = Helpers::getPropertyType($prop) ?? 'mixed';
if (is_subclass_of($enum = ltrim($type, '?'), \BackedEnum::class)) {
$item = self::enum($enum);
$enum === $type || $item->nullable();
} else {
$item = self::type($type);
}
if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) {
$def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue());
if (is_object($def) && !$def instanceof \UnitEnum) {
$item = static::from($def);
} elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) {
$item->required();
} else {
$item->default($def);
}
} else {
$item->required();
}
$items[$name] = $item;
}
}
return (new Structure($items))->castTo($ro->getName());
}
/**
* Creates an array schema. When passed Schema elements, behaves like structure() but outputs an array.
* Without Schema elements, creates a plain array type with the given default value.
* @param mixed[] $shape
*/
public static function array(?array $shape = []): Structure|ArrayType
{
$shape ??= [];
return Nette\Utils\Arrays::first($shape) instanceof Schema
? (new Structure($shape))->castTo('array')
: (new ArrayType('array'))->default($shape);
}
/**
* Creates an associative or indexed array schema where every value matches the given type.
*/
public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): ArrayType
{
return (new ArrayType('array'))->items($valueType, $keyType);
}
/**
* Creates a list schema (sequentially indexed from 0) where every element matches the given type.
* With $wrap, a single value is also accepted and wrapped into a one-item list.
*/
public static function listOf(string|Schema $type, bool $wrap = false): ArrayType
{
return (new ArrayType('list', $wrap))->items($type);
}
/**
* Creates a fixed-size array where each position has its own schema; a later layer replaces the tuple wholesale.
* @param Schema[] $shape
*/
public static function tuple(array $shape): Elements\TupleType
{
return new Elements\TupleType($shape);
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
use Nette\Utils\Reflection;
use function count, is_array, is_float, is_int, is_object, is_scalar, is_string, strlen;
/**
* @internal
*/
final class Helpers
{
use Nette\StaticClass;
public const PreventMerging = '_prevent_merging';
/**
* Merges dataset. Left has higher priority than right one.
*/
public static function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[self::PreventMerging])) {
unset($value[self::PreventMerging]);
return $value;
}
if (is_array($value) && is_array($base)) {
$index = 0;
foreach ($value as $key => $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;
}
}
/**
* Returns the type of a property or parameter as a string, or null if not determinable.
*/
public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string
{
if ($type = Nette\Utils\Type::fromReflection($prop)) {
return (string) $type;
} elseif (
($prop instanceof \ReflectionProperty)
&& ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var')))
) {
$class = Reflection::getPropertyDeclaringClass($prop);
return preg_replace_callback('#[\w\\\]+#', fn($m) => Reflection::expandClassName($m[0], $class), $type);
}
return null;
}
/**
* Returns an annotation value.
* @param \ReflectionClass<object>|\ReflectionProperty $ref
*/
public static function parseAnnotation(\ReflectionClass|\ReflectionProperty $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;
}
/**
* Formats a value for use in error messages (e.g., 'hello', true, object stdClass).
*/
public static function formatValue(mixed $value): string
{
if ($value instanceof DynamicParameter) {
return 'dynamic';
} elseif (is_object($value)) {
return 'object ' . $value::class;
} elseif (is_string($value)) {
return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'";
} elseif (is_scalar($value)) {
return var_export($value, return: true);
} else {
return get_debug_type($value);
}
}
/**
* Adds a TypeMismatch error to the context if the value does not match the expected type.
*/
public static function validateType(mixed $value, string $expected, Context $context): void
{
if (!Nette\Utils\Validators::is($value, $expected)) {
$expected = str_replace(DynamicParameter::class . '|', '', $expected);
$expected = str_replace(['|', ':'], [' or ', ' in range '], $expected);
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Message::TypeMismatch,
['value' => $value, 'expected' => $expected],
);
}
}
/**
* Adds a range error to the context if the value (or its length for strings/arrays) is outside the given range.
* @param array{int|float|null, int|float|null} $range
*/
public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void
{
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.",
Message::LengthOutOfRange,
['value' => $value, 'length' => $length, 'expected' => implode('..', $range)],
);
}
} elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) {
$context->addError(
'The %label% %path% expects to be in range %expected%, %value% given.',
Message::ValueOutOfRange,
['value' => $value, 'expected' => implode('..', $range)],
);
}
}
/**
* Checks whether a value falls within the given [min, max] range (null means no bound).
* @param array{int|float|null, int|float|null} $range
*/
public static function isInRange(mixed $value, array $range): bool
{
return ($range[0] === null || $value >= $range[0])
&& ($range[1] === null || $value <= $range[1]);
}
/**
* Adds a PatternMismatch error to the context if the value does not match the pattern.
*/
public static function validatePattern(string $value, string $pattern, Context $context): void
{
$res = @preg_match("\x01^(?:$pattern)$\x01Du", $value); // @ - an invalid pattern is thrown below
if ($res === false && preg_last_error() === PREG_INTERNAL_ERROR) {
throw new Nette\InvalidStateException("Invalid pattern '$pattern': " . Nette\Utils\Helpers::getLastError());
} elseif (!$res) {
$context->addError(
"The %label% %path% expects to match pattern '%pattern%', %value% given.",
Message::PatternMismatch,
['value' => $value, 'pattern' => $pattern],
);
}
}
/**
* Returns a closure that casts a value to the given type (built-in, backed enum, class with constructor, or plain class).
* A null stays null for an enum or a class, and for a built-in type only when written as ?type.
* @return \Closure(mixed, Context): mixed
*/
public static function getCastStrategy(string $type): \Closure
{
if (str_starts_with($type, '?')) {
$cast = self::getCastStrategy(substr($type, 1));
return static fn($value, Context $context) => $value === null ? null : $cast($value, $context);
} elseif (Nette\Utils\Validators::isBuiltinType($type)) {
return static function ($value) use ($type) {
settype($value, $type);
return $value;
};
} elseif (is_subclass_of($type, \BackedEnum::class)) {
return static function ($value, Context $context) use ($type) {
if ($value === null) {
return null;
}
try {
return $type::from($value);
} catch (\TypeError|\ValueError) {
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Message::TypeMismatch,
[
'value' => $value,
'expected' => implode('|', array_map(fn(\BackedEnum $case) => self::formatValue($case->value), $type::cases())),
],
);
return null;
}
};
} elseif (is_subclass_of($type, \UnitEnum::class)) {
throw new Nette\InvalidStateException("Cannot cast value to pure enum $type.");
}
$factory = method_exists($type, '__construct')
? static fn($value) => is_array($value) || $value instanceof \stdClass
? new $type(...(array) $value)
: new $type($value)
: static fn($value) => Nette\Utils\Arrays::toObject((array) $value, new $type);
return static function ($value) use ($factory, $type) {
if ($value === null) {
return null;
}
try {
return $factory($value);
} catch (\Error $e) {
throw new Nette\InvalidStateException("Unable to cast value to $type: " . $e->getMessage(), 0, $e);
}
};
}
}
+292
View File
@@ -0,0 +1,292 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
use function count, is_bool, is_float, is_int, is_string;
/**
* Exports a schema as JSON Schema.
*/
final class JsonSchema
{
private const Formats = ['email' => 'email', 'url' => 'uri', 'uri' => 'uri'];
/**
* @return array<string, mixed>|\stdClass
* @throws Nette\NotSupportedException when the schema contains a class type or another PHP-only type
*/
public static function export(Schema $schema): array|\stdClass
{
return self::build($schema);
}
/**
* @param Schema|array<string, mixed> $schema a schema, or a description as describe() returns it
* @return array<string, mixed>|\stdClass
*/
private static function build(Schema|array $schema): array|\stdClass
{
$item = self::describe($schema);
$kind = $item['kind'];
if (!$kind instanceof Kind) {
throw new Nette\InvalidStateException('describe() must report a Kind.');
}
$res = match ($kind) {
Kind::Any => [],
Kind::Null => ['type' => 'null'],
Kind::Bool => ['type' => 'boolean'],
Kind::Int => ['type' => 'integer'] + self::range($item, 'minimum', 'maximum'),
Kind::Float, Kind::Number => ['type' => 'number'] + self::range($item, 'minimum', 'maximum'),
Kind::String => self::buildString($item),
// an iterable of items is narrowed to a JSON array, which PHP accepts too
Kind::List, Kind::Iterable => self::buildList($item),
Kind::Array => self::buildArray($item),
Kind::Structure => self::buildStructure($item),
Kind::Tuple => self::buildTuple($item),
Kind::Enum => self::buildEnum($item['values']),
Kind::Union => self::buildUnion($item),
Kind::Instance, Kind::Other, Kind::Object, Kind::Callable => throw new Nette\NotSupportedException(
"Type '" . ($item['type'] ?? strtolower($kind->name)) . "' cannot be expressed in JSON Schema.",
),
};
if ($item['nullable'] ?? false) {
if (isset($res['enum'])) {
$res['enum'][] = null;
}
if (isset($res['type']) && $res['type'] !== 'null') {
$res['type'] = [$res['type'], 'null'];
} elseif (isset($res['anyOf'])) {
$res['anyOf'][] = ['type' => 'null'];
}
}
if (($item['description'] ?? null) !== null) {
$res['description'] = $item['description'];
}
return $res ?: new \stdClass;
}
/**
* @param Schema|array<string, mixed> $schema
* @return array<string, mixed>
*/
private static function describe(Schema|array $schema): array
{
if (!$schema instanceof Schema) {
return $schema;
} elseif (
$schema instanceof Elements\Type
|| $schema instanceof Elements\Structure
|| $schema instanceof Elements\AnyOf
) {
return $schema->describe();
}
throw new Nette\NotSupportedException('Element ' . $schema::class . ' cannot be expressed in JSON Schema.');
}
/**
* @param Schema|array<string, mixed>|null $schema
* @return array<string, mixed>|\stdClass
*/
private static function buildOrAny(Schema|array|null $schema): array|\stdClass
{
return $schema === null ? new \stdClass : self::build($schema);
}
/**
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildString(array $item): array
{
$res = ['type' => 'string'] + self::countRange($item, 'minLength', 'maxLength');
if ($item['pattern'] !== null) {
$res['pattern'] = '^(?:' . $item['pattern'] . ')$';
}
// only the formats JSON Schema knows; the others are checked by PHP alone, like assert()
if ($format = self::Formats[$item['format'] ?? ''] ?? null) {
$res['format'] = $format;
}
return $res;
}
/**
* A list that wraps a single value accepts the item alone as well.
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildList(array $item): array
{
$res = ['type' => 'array', 'items' => self::buildOrAny($item['items'])] + self::countRange($item, 'minItems', 'maxItems');
$single = ($item['wrap'] ?? false) && ($item['min'] ?? 0) <= 1 && ($item['max'] ?? 1) >= 1;
return $single
? ['anyOf' => [self::buildOrAny($item['items']), $res]]
: $res;
}
/**
* A PHP array is a JSON array when its keys are integers and an object otherwise.
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildArray(array $item): array
{
$keys = $item['keys'] === null ? null : self::describe($item['keys']);
if ($keys && $keys['kind'] === Kind::Int) {
return ['type' => 'array', 'items' => self::buildOrAny($item['items'])]
+ self::countRange($item, 'minItems', 'maxItems');
} elseif ($item['items'] === null && $keys === null) {
throw new Nette\NotSupportedException('An array without item type cannot be expressed in JSON Schema; use listOf(), arrayOf() or structure().');
}
$res = ['type' => 'object', 'additionalProperties' => self::buildOrAny($item['items'])]
+ self::countRange($item, 'minProperties', 'maxProperties');
// a JSON property name is a string, so only a key schema of strings says something about it
if (
$keys
&& ($keys['kind'] === Kind::String
|| ($keys['kind'] === Kind::Enum && array_filter($keys['values'], is_string(...)) === $keys['values']))
) {
$names = self::build($keys);
if ($names !== ['type' => 'string']) {
$res['propertyNames'] = $names;
}
}
return $res;
}
/**
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildStructure(array $item): array
{
$properties = $required = [];
foreach ($item['shape'] as $key => $property) {
$properties[$key] = self::build($property);
if (self::isRequired($property)) {
$required[] = (string) $key;
}
}
return [
'type' => 'object',
'properties' => $properties && !array_is_list($properties) ? $properties : (object) $properties, // integer keys from 0 would encode as a JSON array
'required' => $required,
'additionalProperties' => $item['otherItems'] ? self::build($item['otherItems']) : false,
] + self::countRange($item, 'minProperties', 'maxProperties');
}
/**
* A required position makes all positions before it present too.
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildTuple(array $item): array
{
$res = ['type' => 'array'];
if ($item['shape']) { // prefixItems must not be empty
$res['prefixItems'] = array_map(self::build(...), $item['shape']);
}
$res['items'] = $item['otherItems'] ? self::build($item['otherItems']) : false;
$range = self::countRange($item, 'minItems', 'maxItems');
$positions = array_keys(array_filter($item['shape'], self::isRequired(...)));
if ($positions) {
$range['minItems'] = max($range['minItems'] ?? 0, max($positions) + 1);
}
return $res + $range;
}
/**
* Whether a missing item is an error. A structure is created from its defaults instead,
* so it fails only when something inside it is required or its size has a minimum.
* @param Schema|array<string, mixed> $schema
*/
private static function isRequired(Schema|array $schema): bool
{
$item = self::describe($schema);
return $item['required'] && match ($item['kind']) {
Kind::Structure => ($item['min'] ?? 0) > 0 || array_filter($item['shape'], self::isRequired(...)),
default => true,
};
}
/**
* The type is stated only when every value shares it.
* @param list<mixed> $values
* @return array<string, mixed>
*/
private static function buildEnum(array $values): array
{
$types = array_unique(array_map(fn($value) => match (true) {
is_string($value) => 'string',
is_int($value) => 'integer',
is_float($value) => 'number',
is_bool($value) => 'boolean',
default => null,
}, $values));
return (count($types) === 1 && reset($types) !== null ? ['type' => reset($types)] : []) + ['enum' => $values];
}
/**
* Scalar values of an anyOf() come first as one enum, then the schema variants.
* @param array<string, mixed> $item
* @return array<string, mixed>
*/
private static function buildUnion(array $item): array
{
$variants = array_map(self::build(...), $item['variants']);
if ($item['values'] ?? []) {
array_unshift($variants, self::buildEnum($item['values']));
}
return ['anyOf' => $variants];
}
/**
* A count of characters, items or properties is a non-negative integer.
* @param array<string, mixed> $item
* @return array<string, int>
*/
private static function countRange(array $item, string $minKey, string $maxKey): array
{
return array_filter([
$minKey => $item['min'] === null ? null : max(0, (int) ceil($item['min'])),
$maxKey => $item['max'] === null ? null : max(0, (int) floor($item['max'])),
], fn($v) => $v !== null);
}
/**
* @param array<string, mixed> $item
* @return array<string, int|float>
*/
private static function range(array $item, string $minKey, string $maxKey): array
{
$number = fn(int|float|null $value) => $value === null ? null : ($value == (int) $value ? (int) $value : $value); // intentionally ==, a whole float is exported as int
return array_filter([$minKey => $number($item['min']), $maxKey => $number($item['max'])], fn($v) => $v !== null);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use function array_key_exists;
/**
* Represents a single validation error or warning with a message template, error code, path, and variables.
*/
final class Message
{
/** variables: {value: mixed, expected: string} */
public const TypeMismatch = 'schema.typeMismatch';
/** variables: {value: mixed, expected: string} */
public const ValueOutOfRange = 'schema.valueOutOfRange';
/** variables: {value: mixed, length: int, expected: string} */
public const LengthOutOfRange = 'schema.lengthOutOfRange';
/** variables: {value: string, pattern: string} */
public const PatternMismatch = 'schema.patternMismatch';
/** variables: {value: mixed, assertion: string} */
public const FailedAssertion = 'schema.failedAssertion';
/** no variables */
public const MissingItem = 'schema.missingItem';
/** variables: {hint: string} */
public const UnexpectedItem = 'schema.unexpectedItem';
/** no variables */
public const Deprecated = 'schema.deprecated';
/** @deprecated use Message::TypeMismatch */
public const TYPE_MISMATCH = self::TypeMismatch;
/** @deprecated use Message::ValueOutOfRange */
public const VALUE_OUT_OF_RANGE = self::ValueOutOfRange;
/** @deprecated use Message::LengthOutOfRange */
public const LENGTH_OUT_OF_RANGE = self::LengthOutOfRange;
/** @deprecated use Message::PatternMismatch */
public const PATTERN_MISMATCH = self::PatternMismatch;
/** @deprecated use Message::FailedAssertion */
public const FAILED_ASSERTION = self::FailedAssertion;
/** @deprecated use Message::MissingItem */
public const MISSING_ITEM = self::MissingItem;
/** @deprecated use Message::UnexpectedItem */
public const UNEXPECTED_ITEM = self::UnexpectedItem;
/** @deprecated use Message::Deprecated */
public const DEPRECATED = self::Deprecated;
public function __construct(
public string $message,
public string $code,
/** @var list<int|string> */
public array $path,
/** @var array<string, mixed> */
public array $variables = [],
) {
}
/**
* Formats the message template by substituting %variable% placeholders with their values.
*/
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 array_key_exists($key, $vars)
? ($vars[$key] === null ? '' : $space . $vars[$key])
: $m[0];
}, $this->message);
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
/**
* Schema validator.
*/
final class Processor
{
/** @var list<\Closure(Context): void> */
public array $onNewContext = [];
private Context $context;
private bool $skipDefaults = false;
/**
* When enabled, missing properties are not filled with their default values.
*/
public function skipDefaults(bool $value = true): void
{
$this->skipDefaults = $value;
}
/**
* Normalizes and validates data. Result is a clean completed data.
* @throws ValidationException
*/
public function process(Schema $schema, mixed $data): mixed
{
$context = $this->createContext();
try {
$data = $schema->normalize($data, $context);
$this->throwErrors($context);
$data = $schema->complete($data, $context);
$this->throwErrors($context);
return $data;
} finally {
$this->context = $context;
}
}
/**
* Normalizes and validates and merges multiple data. Result is a clean completed data.
* @param list<mixed> $dataset
* @throws ValidationException
*/
public function processMultiple(Schema $schema, array $dataset): mixed
{
$context = $this->createContext();
try {
$flatten = null;
$first = true;
foreach ($dataset as $data) {
$data = $schema->normalize($data, $context);
$this->throwErrors($context);
$flatten = $first ? $data : $schema->merge($data, $flatten);
$first = false;
}
$data = $schema->complete($flatten, $context);
$this->throwErrors($context);
return $data;
} finally {
$this->context = $context;
}
}
/**
* Returns all deprecation warnings collected during the last processing run.
* @return list<string>
*/
public function getWarnings(): array
{
$res = [];
if (isset($this->context)) {
foreach ($this->context->warnings as $message) {
$res[] = $message->toString();
}
}
return $res;
}
private function throwErrors(Context $context): void
{
if ($context->errors) {
throw new ValidationException(null, $context->errors);
}
}
private function createContext(): Context
{
$context = new Context;
$context->skipDefaults = $this->skipDefaults;
Nette\Utils\Arrays::invoke($this->onNewContext, $context);
return $context;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
/**
* Defines the contract for schema elements used in data validation and normalization.
*/
interface Schema
{
/**
* Applies pre-processing transformations to the raw input value (e.g., via before() hooks).
* @return mixed
*/
function normalize(mixed $value, Context $context);
/**
* Merges two normalized values, with $value taking priority over $base.
* @return mixed
*/
function merge(mixed $value, mixed $base);
/**
* Validates the value and applies defaults, transforms, and assertions.
* @return mixed
*/
function complete(mixed $value, Context $context);
/**
* Returns the default value, or adds a missing-item error if the field is required.
* @return mixed
*/
function completeDefault(Context $context);
}
+150
View File
@@ -0,0 +1,150 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use function count;
/**
* Translates the type-expression language of Expect::type() ('int|string', '?Foo', 'int[]', 'string:1..5',
* 'pattern:\d+') into a plain description.
* @internal
*/
final class TypeExpression
{
/**
* The names Validators::is() knows and what kind of value they are; 'scalar' is a union handled apart,
* any other name is a class.
*/
private const Names = [
'mixed' => Kind::Any,
'bool' => Kind::Bool, 'boolean' => Kind::Bool,
'int' => Kind::Int, 'integer' => Kind::Int,
'float' => Kind::Float, 'number' => Kind::Number,
'string' => Kind::String,
'unicode' => Kind::String, 'email' => Kind::String, 'uri' => Kind::String, 'url' => Kind::String,
'identifier' => Kind::String, 'class' => Kind::String, 'interface' => Kind::String,
'file' => Kind::String, 'directory' => Kind::String, 'alnum' => Kind::String, 'alpha' => Kind::String,
'digit' => Kind::String, 'lower' => Kind::String, 'upper' => Kind::String, 'space' => Kind::String,
'xdigit' => Kind::String, 'pattern' => Kind::String,
'array' => Kind::Array, 'list' => Kind::List, 'iterable' => Kind::Iterable,
'object' => Kind::Object, 'callable' => Kind::Callable,
'resource' => Kind::Other, 'none' => Kind::Other, 'numeric' => Kind::Other, 'numericint' => Kind::Other,
];
/** @var array<string, array<string, mixed>> */
private static array $cache = [];
/** @return array<string, mixed> */
public static function parse(string $expression): array
{
return self::$cache[$expression] ??= self::doParse($expression);
}
/** @return array<string, mixed> */
private static function doParse(string $expression): array
{
$variants = [];
$nullable = $dynamic = false;
foreach (explode('|', $expression) as $part) {
if (str_starts_with($part, '?')) {
$nullable = true;
$part = substr($part, 1);
}
if ($part === 'null') {
$nullable = true;
} elseif ($part === DynamicParameter::class) {
$dynamic = true;
} else {
array_push($variants, ...self::parseAlternative($part));
}
}
$item = match (count($variants)) {
0 => ['kind' => $nullable ? Kind::Null : Kind::Any],
1 => $variants[0],
default => ['kind' => Kind::Union, 'variants' => $variants],
};
return $item + ['nullable' => $nullable && count($variants) > 0, 'dynamic' => $dynamic];
}
/**
* One alternative of the expression; 'scalar' expands to several.
* @return list<array<string, mixed>>
*/
private static function parseAlternative(string $part): array
{
if (str_ends_with($part, '[]')) {
$items = self::parseAlternative(substr($part, 0, -2));
return [[
'kind' => Kind::Iterable,
'items' => count($items) === 1 ? $items[0] : ['kind' => Kind::Union, 'variants' => $items],
'keys' => null,
'min' => null,
'max' => null,
]];
}
if (str_contains($part, '&')) {
return [['kind' => Kind::Other, 'type' => $part]]; // an intersection type cannot be checked
}
$parts = explode(':', $part, 2);
$name = $parts[0];
$arg = $parts[1] ?? null;
[$min, $max] = $arg === null || $name === 'pattern' ? [null, null] : self::parseRange($arg);
$number = fn(Kind $kind) => ['kind' => $kind, 'min' => $min, 'max' => $max];
$string = fn(?string $format = null, ?string $pattern = null) => [
'kind' => Kind::String,
'min' => $min,
'max' => $max,
'pattern' => $pattern,
'format' => $format,
];
$collection = fn(Kind $kind) => ['kind' => $kind, 'items' => null, 'keys' => null, 'min' => $min, 'max' => $max];
$kind = self::Names[$name] ?? Kind::Instance;
return match (true) {
$name === 'scalar' => [['kind' => Kind::Bool], $number(Kind::Number), $string()],
$name === 'pattern' => [$string(pattern: $arg)],
$kind === Kind::String => [$string(format: $name === 'string' ? null : $name)],
$kind === Kind::Int, $kind === Kind::Float, $kind === Kind::Number => [$number($kind)],
$kind === Kind::Array, $kind === Kind::List, $kind === Kind::Iterable => [$collection($kind)],
$kind === Kind::Instance => [['kind' => $kind, 'type' => $name]],
$kind === Kind::Other => [['kind' => $kind, 'type' => $part]],
default => [['kind' => $kind]],
};
}
/**
* Bounds written as 'min..max', '..max', 'min..' or an exact 'value'.
* @return array{int|float|null, int|float|null}
*/
private static function parseRange(string $range): array
{
$bounds = explode('..', $range) + [1 => $range];
return [
$bounds[0] === '' ? null : self::parseBound($bounds[0]),
$bounds[1] === '' ? null : self::parseBound($bounds[1]),
];
}
/**
* An integer bound stays an integer, a float would lose the precision of large ones.
*/
private static function parseBound(string $bound): int|float
{
return is_numeric($bound) ? $bound + 0 : (float) $bound;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
/**
* Validation error.
*/
class ValidationException extends Nette\InvalidStateException
{
public function __construct(
?string $message,
/** @var list<Message> */
private readonly array $messages = [],
) {
parent::__construct($message ?? $messages[0]->toString());
}
/**
* Returns all validation error messages as formatted strings.
* @return list<string>
*/
public function getMessages(): array
{
$res = [];
foreach ($this->messages as $message) {
$res[] = $message->toString();
}
return $res;
}
/**
* Returns all validation error messages as Message objects.
* @return list<Message>
*/
public function getMessageObjects(): array
{
return $this->messages;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
/**
* The category of value a schema element accepts, the 'kind' of describe().
* @internal
*/
enum Kind
{
case Any;
case Null;
case Bool;
case Int;
case Float;
/** int or float */
case Number;
case String;
case Array;
case List;
case Iterable;
case Structure;
case Enum;
case Tuple;
case Union;
case Instance;
case Object;
case Callable;
case Other;
}
/**
* Defines the strategy for merging array values from multiple configuration layers.
*/
enum MergeMode
{
case Replace;
case OverwriteKeys;
case AppendKeys;
}