This commit is contained in:
Javier Casares 2026-11-04 17:27:19 +00:00
commit 121c35737d
48 changed files with 1398 additions and 2198 deletions

View file

@ -15,21 +15,16 @@
}
],
"require": {
"php": "8.1 - 8.5",
"nette/utils": "^4.0"
"php": "7.1 - 8.3",
"nette/utils": "^2.5.7 || ^3.1.5 || ^4.0"
},
"require-dev": {
"nette/tester": "^2.6",
"tracy/tracy": "^2.8",
"phpstan/phpstan": "^2.1.39@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0"
"nette/tester": "^2.3 || ^2.4",
"tracy/tracy": "^2.7",
"phpstan/phpstan-nette": "^1.0"
},
"autoload": {
"classmap": ["src/"],
"psr-4": {
"Nette\\": "src"
}
"classmap": ["src/"]
},
"minimum-stability": "dev",
"scripts": {
@ -38,12 +33,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
"dev-master": "1.2-dev"
}
}
}

View file

@ -1,4 +1,5 @@
# Nette Schema
Nette Schema
************
[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema)
[![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions)
@ -20,7 +21,7 @@ Installation:
composer require nette/schema
```
It requires PHP version 8.1 and supports PHP up to 8.5.
It requires PHP version 7.1 and supports PHP up to 8.3.
[Support Me](https://github.com/sponsors/dg)
@ -126,7 +127,7 @@ Expect::null()
Expect::array($default = [])
```
And then all types [supported by the Validators](https://doc.nette.org/validators#toc-expected-types) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`.
And then all types [supported by the Validators](https://doc.nette.org/validators#toc-validation-rules) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`.
You can also use union notation:
@ -438,7 +439,7 @@ Expect::structure([
// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount
```
If the class has a constructor, the elements of the structure are passed as named parameters to the constructor:
If the class has a constructor, the elements of the structure are passed as named parameters to the constructor (requires PHP 8):
```php
class Info

View file

@ -1,38 +1,40 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use function count;
use Nette;
/**
* Accumulates errors and warnings during schema validation and tracks the current path.
*/
final class Context
{
public bool $skipDefaults = false;
use Nette\SmartObject;
/** @var list<int|string> */
public array $path = [];
/** @var bool */
public $skipDefaults = false;
public bool $isKey = false;
/** @var string[] */
public $path = [];
/** @var list<Message> */
public array $errors = [];
/** @var bool */
public $isKey = false;
/** @var list<Message> */
public array $warnings = [];
/** @var Message[] */
public $errors = [];
/** @var list<array{DynamicParameter, string, list<int|string>}> */
public array $dynamics = [];
/** @var Message[] */
public $warnings = [];
/** @var array[] */
public $dynamics = [];
/** @param array<string, mixed> $variables */
public function addError(string $message, string $code, array $variables = []): Message
{
$variables['isKey'] = $this->isKey;
@ -40,20 +42,18 @@ final class Context
}
/** @param array<string, mixed> $variables */
public function addWarning(string $message, string $code, array $variables = []): Message
{
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
*/
/** @return \Closure(): bool */
public function createChecker(): \Closure
{
$count = count($this->errors);
return fn(): bool => $count === count($this->errors);
return function () use ($count): bool {
return $count === count($this->errors);
};
}
}

View file

@ -1,10 +1,12 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;

View file

@ -1,31 +1,33 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use function array_merge, array_unique, implode, 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;
use Nette\SmartObject;
/** @var mixed[] */
private array $set;
/** @var array */
private $set;
public function __construct(mixed ...$set)
/**
* @param mixed|Schema ...$set
*/
public function __construct(...$set)
{
if (!$set) {
throw new Nette\InvalidStateException('The enumeration must not be empty.');
@ -35,9 +37,6 @@ final class AnyOf implements Schema
}
/**
* Sets the first variant as the default value (instead of null).
*/
public function firstIsDefault(): self
{
$this->default = $this->set[0];
@ -45,9 +44,6 @@ final class AnyOf implements Schema
}
/**
* Allows null as an accepted value in addition to the defined variants.
*/
public function nullable(): self
{
$this->set[] = null;
@ -55,9 +51,6 @@ final class AnyOf implements Schema
}
/**
* Allows the value to be a DynamicParameter as an accepted variant.
*/
public function dynamic(): self
{
$this->set[] = new Type(Nette\Schema\DynamicParameter::class);
@ -68,13 +61,13 @@ final class AnyOf implements Schema
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
public function normalize($value, Context $context)
{
return $this->doNormalize($value, $context);
}
public function merge(mixed $value, mixed $base): mixed
public function merge($value, $base)
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
@ -85,7 +78,7 @@ final class AnyOf implements Schema
}
public function complete(mixed $value, Context $context): mixed
public function complete($value, Context $context)
{
$isOk = $context->createChecker();
$value = $this->findAlternative($value, $context);
@ -94,19 +87,16 @@ final class AnyOf implements Schema
}
private function findAlternative(mixed $value, Context $context): mixed
private function findAlternative($value, Context $context)
{
$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;
$res = $item->complete($item->normalize($value, $dolly), $dolly);
if (!$dolly->errors) {
$context->warnings = array_merge($context->warnings, $dolly->warnings);
$context->dynamics = array_merge($context->dynamics, $dolly->dynamics);
return $res;
}
@ -135,20 +125,18 @@ final class AnyOf implements Schema
[
'value' => $value,
'expected' => implode('|', array_unique($expecteds)),
],
]
);
}
return null;
}
public function completeDefault(Context $context): mixed
public function completeDefault(Context $context)
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
Nette\Schema\Message::MissingItem
);
return null;
}

View file

@ -1,16 +1,17 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use function count, is_string;
/**
@ -18,18 +19,23 @@ use function count, is_string;
*/
trait Base
{
private bool $required = false;
private mixed $default = null;
/** @var bool */
private $required = false;
/** @var ?\Closure(mixed): mixed */
private ?\Closure $before = null;
/** @var mixed */
private $default;
/** @var list<\Closure(mixed, Context): mixed> */
private array $transforms = [];
private ?string $deprecated = null;
/** @var callable|null */
private $before;
/** @var callable[] */
private $transforms = [];
/** @var string|null */
private $deprecated;
public function default(mixed $value): self
public function default($value): self
{
$this->default = $value;
return $this;
@ -43,44 +49,29 @@ trait Base
}
/**
* Sets a pre-normalization callback applied to the raw input value before any validation.
* @param callable(mixed): mixed $handler
*/
public function before(callable $handler): self
{
$this->before = $handler(...);
$this->before = $handler;
return $this;
}
/**
* Casts the validated value to a built-in type or instantiates the given class.
*/
public function castTo(string $type): self
{
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): self
{
$this->transforms[] = $handler(...);
$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): self
{
$expected = $description ?? (is_string($handler) ? "$handler()" : '#' . count($this->transforms));
$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;
@ -88,16 +79,13 @@ trait Base
$context->addError(
'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.',
Nette\Schema\Message::FailedAssertion,
['value' => $value, 'assertion' => $expected],
['value' => $value, 'assertion' => $expected]
);
return null;
});
}
/**
* Marks the item as deprecated; emits a warning with the given message when the item is used.
*/
/** Marks as deprecated */
public function deprecated(string $message = 'The item %path% is deprecated.'): self
{
$this->deprecated = $message;
@ -105,12 +93,12 @@ trait Base
}
public function completeDefault(Context $context): mixed
public function completeDefault(Context $context)
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
Nette\Schema\Message::MissingItem
);
return null;
}
@ -119,7 +107,7 @@ trait Base
}
public function doNormalize(mixed $value, Context $context): mixed
public function doNormalize($value, Context $context)
{
if ($this->before) {
$value = ($this->before)($value);
@ -134,13 +122,13 @@ trait Base
if ($this->deprecated !== null) {
$context->addWarning(
$this->deprecated,
Nette\Schema\Message::Deprecated,
Nette\Schema\Message::Deprecated
);
}
}
private function doTransform(mixed $value, Context $context): mixed
private function doTransform($value, Context $context)
{
$isOk = $context->createChecker();
foreach ($this->transforms as $handler) {
@ -153,8 +141,8 @@ trait Base
}
/** @deprecated use Nette\Schema\Helpers::validateType() */
private function doValidate(mixed $value, string $expected, Context $context): bool
/** @deprecated use Nette\Schema\Validators::validateType() */
private function doValidate($value, string $expected, Context $context): bool
{
$isOk = $context->createChecker();
Helpers::validateType($value, $expected, $context);
@ -162,11 +150,8 @@ trait Base
}
/**
* @deprecated use Nette\Schema\Helpers::validateRange()
* @param array{?float, ?float} $range
*/
private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool
/** @deprecated use Nette\Schema\Validators::validateRange() */
private static function doValidateRange($value, array $range, Context $context, string $types = ''): bool
{
$isOk = $context->createChecker();
Helpers::validateRange($value, $range, $context, $types);
@ -175,7 +160,7 @@ trait Base
/** @deprecated use doTransform() */
private function doFinalize(mixed $value, Context $context): mixed
private function doFinalize($value, Context $context)
{
return $this->doTransform($value, $context);
}

View file

@ -1,48 +1,51 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use function array_diff_key, array_fill_keys, array_key_exists, array_keys, array_map, array_merge, array_pop, array_values, is_array, is_object, strval;
final class Structure implements Schema
{
use Base;
use Nette\SmartObject;
/** @var Schema[] */
private array $items;
private $items;
/** for array|list */
private ?Schema $otherItems = null;
/** @var Schema|null for array|list */
private $otherItems;
/** @var array{?int, ?int} */
private array $range = [null, null];
private bool $skipDefaults = false;
private $range = [null, null];
/** @var bool */
private $skipDefaults = false;
/** @param Schema[] $shape */
public function __construct(array $shape)
/**
* @param Schema[] $items
*/
public function __construct(array $items)
{
(function (Schema ...$items) {})(...array_values($shape));
$this->items = $shape;
(function (Schema ...$items) {})(...array_values($items));
$this->items = $items;
$this->castTo('object');
$this->required = true;
}
/**
* Not supported for structures; always throws.
*/
public function default(mixed $value): self
public function default($value): self
{
throw new Nette\InvalidStateException('Structure cannot have default value.');
}
@ -63,18 +66,15 @@ final class Structure implements Schema
/**
* Allows extra keys not defined in the shape, validating their values against the given type.
* @param string|Schema $type
*/
public function otherItems(string|Schema $type = 'mixed'): self
public function otherItems($type = 'mixed'): self
{
$this->otherItems = $type instanceof Schema ? $type : new Type($type);
return $this;
}
/**
* When enabled, properties whose value equals the default are omitted from the output.
*/
public function skipDefaults(bool $state = true): self
{
$this->skipDefaults = $state;
@ -82,28 +82,10 @@ final class Structure implements Schema
}
/**
* 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(array_merge($this->items, $shape));
}
/** @return Schema[] */
public function getShape(): array
{
return $this->items;
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
public function normalize($value, Context $context)
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
@ -133,7 +115,7 @@ final class Structure implements Schema
}
public function merge(mixed $value, mixed $base): mixed
public function merge($value, $base)
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
@ -141,26 +123,29 @@ final class Structure implements Schema
}
if (is_array($value) && is_array($base)) {
$index = $this->otherItems === null ? null : 0;
$index = 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)
} elseif (array_key_exists($key, $base)) {
$itemSchema = $this->items[$key] ?? $this->otherItems;
$base[$key] = $itemSchema
? $itemSchema->merge($val, $base[$key])
: $val;
: Helpers::merge($val, $base[$key]);
} else {
$base[$key] = $val;
}
}
return $base;
}
return $value ?? $base;
return Helpers::merge($value, $base);
}
public function complete(mixed $value, Context $context): mixed
public function complete($value, Context $context)
{
if ($value === null) {
$value = []; // is unable to distinguish null from array in NEON
@ -177,7 +162,6 @@ final class Structure implements Schema
}
/** @param array<mixed> $value */
private function validateItems(array &$value, Context $context): void
{
$items = $this->items;
@ -185,13 +169,13 @@ final class Structure implements Schema
if ($this->otherItems) {
$items += array_fill_keys($extraKeys, $this->otherItems);
} else {
$keys = array_map(strval(...), array_keys($items));
$keys = array_map('strval', array_keys($items));
foreach ($extraKeys as $key) {
$hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key);
$hint = Nette\Utils\ObjectHelpers::getSuggestion($keys, (string) $key);
$context->addError(
'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'),
Nette\Schema\Message::UnexpectedItem,
['hint' => $hint],
['hint' => $hint]
)->path[] = $key;
}
}
@ -213,19 +197,10 @@ final class Structure implements Schema
}
public function completeDefault(Context $context): mixed
public function completeDefault(Context $context)
{
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;
}
return $this->required
? $this->complete([], $context)
: null;
}
}

View file

@ -1,32 +1,43 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\DynamicParameter;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use Nette\Utils\Validators;
use function array_key_exists, array_pop, implode, is_array, str_replace, strpos;
final class Type implements Schema
{
use Base;
use Nette\SmartObject;
private string $type;
private ?Schema $itemsValue = null;
private ?Schema $itemsKey = null;
/** @var string */
private $type;
/** @var Schema|null for arrays */
private $itemsValue;
/** @var Schema|null for arrays */
private $itemsKey;
/** @var array{?float, ?float} */
private array $range = [null, null];
private ?string $pattern = null;
private bool $merge = true;
private $range = [null, null];
/** @var string|null */
private $pattern;
/** @var bool */
private $merge = true;
public function __construct(string $type)
@ -37,9 +48,6 @@ final class Type implements Schema
}
/**
* Allows the value to be null in addition to the declared type.
*/
public function nullable(): self
{
$this->type = 'null|' . $this->type;
@ -47,9 +55,6 @@ final class Type implements Schema
}
/**
* Controls whether the default value is merged with the input array (enabled by default).
*/
public function mergeDefaults(bool $state = true): self
{
$this->merge = $state;
@ -57,9 +62,6 @@ final class Type implements Schema
}
/**
* Allows the value to be a DynamicParameter, which is recorded for deferred validation.
*/
public function dynamic(): self
{
$this->type = DynamicParameter::class . '|' . $this->type;
@ -82,9 +84,11 @@ final class Type implements Schema
/**
* @param string|Schema $valueType
* @param string|Schema|null $keyType
* @internal use arrayOf() or listOf()
*/
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): self
public function items($valueType = 'mixed', $keyType = null): self
{
$this->itemsValue = $valueType instanceof Schema
? $valueType
@ -96,9 +100,6 @@ final class Type implements Schema
}
/**
* Sets a regex pattern the string value must match entirely (anchored to start and end).
*/
public function pattern(?string $pattern): self
{
$this->pattern = $pattern;
@ -109,7 +110,7 @@ final class Type implements Schema
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
public function normalize($value, Context $context)
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
@ -140,7 +141,7 @@ final class Type implements Schema
}
public function merge(mixed $value, mixed $base): mixed
public function merge($value, $base)
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
@ -167,7 +168,7 @@ final class Type implements Schema
}
public function complete(mixed $value, Context $context): mixed
public function complete($value, Context $context)
{
$merge = $this->merge;
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
@ -175,7 +176,7 @@ final class Type implements Schema
$merge = false;
}
if ($value === null && is_array($this->default) && !Validators::is(null, $this->type)) {
if ($value === null && is_array($this->default)) {
$value = []; // is unable to distinguish null from array in NEON
}
@ -186,13 +187,13 @@ final class Type implements Schema
$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() && $merge && $value = Helpers::merge($value, $this->default);
$isOk() && $value = $this->doTransform($value, $context);
if (!$isOk()) {
return null;
}
if ($value instanceof DynamicParameter && $this->type !== DynamicParameter::class) {
if ($value instanceof DynamicParameter) {
$expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range));
$context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path];
}
@ -200,10 +201,9 @@ final class Type implements Schema
}
/** @param array<mixed> $value */
private function validateItems(array &$value, Context $context): void
{
if (!($itemsValue = $this->itemsValue)) {
if (!$this->itemsValue) {
return;
}
@ -211,15 +211,9 @@ final class Type implements Schema
foreach ($value as $key => $val) {
$context->path[] = $key;
$context->isKey = true;
$isKeyOk = $context->createChecker();
$key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key;
$context->isKey = false;
$keyOk = $isKeyOk();
$val = $itemsValue->complete($val, $context);
if ($keyOk) {
$res[$key] = $val;
}
$res[$key] = $this->itemsValue->complete($val, $context);
array_pop($context->path);
}
$value = $res;

View file

@ -1,17 +1,18 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use Nette;
use Nette\Schema\Elements\AnyOf;
use Nette\Schema\Elements\Structure;
use Nette\Schema\Elements\Type;
use function is_object;
/**
@ -23,6 +24,7 @@ use function is_object;
* @method static Type float($default = null)
* @method static Type bool($default = null)
* @method static Type null()
* @method static Type array($default = [])
* @method static Type list($default = [])
* @method static Type mixed($default = null)
* @method static Type email($default = null)
@ -30,7 +32,8 @@ use function is_object;
*/
final class Expect
{
/** @param list<mixed> $args */
use Nette\SmartObject;
public static function __callStatic(string $name, array $args): Type
{
$type = new Type($name);
@ -42,9 +45,6 @@ final class Expect
}
/**
* Creates a schema for a custom type expression (e.g., 'int|string', 'null|float').
*/
public static function type(string $type): Type
{
return new Type($type);
@ -52,42 +52,38 @@ final class Expect
/**
* Creates a union schema that accepts any of the given values or sub-schemas.
* @param mixed|Schema ...$set
*/
public static function anyOf(mixed ...$set): AnyOf
public static function anyOf(...$set): AnyOf
{
return new AnyOf(...$set);
}
/**
* Creates a structure schema with defined properties; output is stdClass.
* @param Schema[] $shape
* @param Schema[] $items
*/
public static function structure(array $shape): Structure
public static function structure(array $items): Structure
{
return new Structure($shape);
return new Structure($items);
}
/**
* 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.
* @param object $object
*/
public static function from(object $object, array $items = []): Structure
public static function from($object, array $items = []): Structure
{
$ro = new \ReflectionObject($object);
$props = $ro->hasMethod('__construct')
? $ro->getMethod('__construct')->getParameters()
: $ro->getProperties();
foreach ($props as $prop) {
$name = $prop->getName();
if (!isset($items[$name])) {
$type = Helpers::getPropertyType($prop) ?? 'mixed';
foreach ($ro->getProperties() as $prop) {
$type = Helpers::getPropertyType($prop) ?? 'mixed';
$item = &$items[$prop->getName()];
if (!$item) {
$item = new Type($type);
if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) {
$def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue());
if (PHP_VERSION_ID >= 70400 && !$prop->isInitialized($object)) {
$item->required();
} else {
$def = $prop->getValue($object);
if (is_object($def)) {
$item = static::from($def);
} elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) {
@ -95,10 +91,7 @@ final class Expect
} else {
$item->default($def);
}
} else {
$item->required();
}
$items[$name] = $item;
}
}
@ -107,32 +100,19 @@ final class Expect
/**
* 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
* @param string|Schema $valueType
* @param string|Schema|null $keyType
*/
public static function array(?array $shape = []): Structure|Type
{
$shape ??= [];
return Nette\Utils\Arrays::first($shape) instanceof Schema
? (new Structure($shape))->castTo('array')
: (new Type('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): Type
public static function arrayOf($valueType, $keyType = null): Type
{
return (new Type('array'))->items($valueType, $keyType);
}
/**
* Creates a list schema (sequentially indexed from 0) where every element matches the given type.
* @param string|Schema $type
*/
public static function listOf(string|Schema $type): Type
public static function listOf($type): Type
{
return (new Type('list'))->items($type);
}

View file

@ -1,15 +1,16 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use Nette;
use Nette\Utils\Reflection;
use function array_map, count, explode, get_debug_type, implode, in_array, is_array, is_float, is_int, is_object, is_scalar, is_string, is_subclass_of, method_exists, preg_match, preg_quote, preg_replace, preg_replace_callback, settype, str_replace, strlen, trim, var_export;
/**
@ -20,12 +21,14 @@ final class Helpers
use Nette\StaticClass;
public const PreventMerging = '_prevent_merging';
public const PREVENT_MERGING = self::PreventMerging;
/**
* Merges dataset. Left has higher priority than right one.
* @return array|string
*/
public static function merge(mixed $value, mixed $base): mixed
public static function merge($value, $base)
{
if (is_array($value) && isset($value[self::PreventMerging])) {
unset($value[self::PreventMerging]);
@ -54,19 +57,17 @@ final class Helpers
}
/**
* Returns the type of a property or parameter as a string, or null if not determinable.
*/
public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string
public static function getPropertyType(\ReflectionProperty $prop): ?string
{
if ($type = Nette\Utils\Type::fromReflection($prop)) {
if (!class_exists(Nette\Utils\Type::class)) {
throw new Nette\NotSupportedException('Expect::from() requires nette/utils 3.x');
} elseif ($type = Nette\Utils\Type::fromReflection($prop)) {
return (string) $type;
} elseif (
($prop instanceof \ReflectionProperty)
&& ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var')))
) {
} elseif ($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 preg_replace_callback('#[\w\\\\]+#', function ($m) use ($class) {
return Reflection::expandClassName($m[0], $class);
}, $type);
}
return null;
@ -75,9 +76,9 @@ final class Helpers
/**
* Returns an annotation value.
* @param \ReflectionClass<object>|\ReflectionProperty $ref
* @param \ReflectionProperty $ref
*/
public static function parseAnnotation(\ReflectionClass|\ReflectionProperty $ref, string $name): ?string
public static function parseAnnotation(\Reflector $ref, string $name): ?string
{
if (!Reflection::areCommentsAvailable()) {
throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.');
@ -93,28 +94,23 @@ final class Helpers
/**
* Formats a value for use in error messages (e.g., 'hello', true, object stdClass).
* @param mixed $value
*/
public static function formatValue(mixed $value): string
public static function formatValue($value): string
{
if ($value instanceof DynamicParameter) {
return 'dynamic';
} elseif (is_object($value)) {
return 'object ' . $value::class;
if (is_object($value)) {
return 'object ' . get_class($value);
} elseif (is_string($value)) {
return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'";
} elseif (is_scalar($value)) {
return var_export($value, return: true);
return var_export($value, true);
} else {
return get_debug_type($value);
return strtolower(gettype($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
public static function validateType($value, string $expected, Context $context): void
{
if (!Nette\Utils\Validators::is($value, $expected)) {
$expected = str_replace(DynamicParameter::class . '|', '', $expected);
@ -122,22 +118,18 @@ final class Helpers
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Message::TypeMismatch,
['value' => $value, 'expected' => $expected],
['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{?float, ?float} $range
*/
public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void
public static function validateRange($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), strict: true)
: (in_array('unicode', explode('|', $types), true)
? [Nette\Utils\Strings::length($value), 'characters']
: [strlen($value), 'bytes']);
@ -145,87 +137,62 @@ final class Helpers
$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)],
['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)],
['value' => $value, 'expected' => implode('..', $range)]
);
}
}
/**
* Checks whether a value falls within the given [min, max] range (null means no bound).
* @param array{?float, ?float} $range
*/
public static function isInRange(mixed $value, array $range): bool
public static function isInRange($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
{
if (!preg_match("\x01^(?:$pattern)$\x01Du", $value)) {
$context->addError(
"The %label% %path% expects to match pattern '%pattern%', %value% given.",
Message::PatternMismatch,
['value' => $value, 'pattern' => $pattern],
['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).
* @return \Closure(mixed, Context): mixed
*/
public static function getCastStrategy(string $type): \Closure
{
if (Nette\Utils\Validators::isBuiltinType($type)) {
if (Nette\Utils\Reflection::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) {
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 (method_exists($type, '__construct')) {
return static function ($value) use ($type) {
if (PHP_VERSION_ID < 80000 && is_array($value)) {
throw new Nette\NotSupportedException("Creating $type objects is supported since PHP 8.0");
}
return is_array($value)
? new $type(...$value)
: new $type($value);
};
} else {
return static function ($value) use ($type) {
$object = new $type;
foreach ($value as $k => $v) {
$object->$k = $v;
}
return $object;
};
} 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) {
try {
return $factory($value);
} catch (\Error $e) {
throw new Nette\InvalidStateException("Unable to cast value to $type: " . $e->getMessage(), 0, $e);
}
};
}
}

View file

@ -1,20 +1,21 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use function array_key_exists, implode, preg_replace_callback;
use Nette;
/**
* Represents a single validation error or warning with a message template, error code, path, and variables.
*/
final class Message
{
use Nette\SmartObject;
/** variables: {value: mixed, expected: string} */
public const TypeMismatch = 'schema.typeMismatch';
@ -39,45 +40,38 @@ final class Message
/** no variables */
public const Deprecated = 'schema.deprecated';
/** @deprecated use Message::TypeMismatch */
/** Deprecated */
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;
/** @var string */
public $message;
public function __construct(
public string $message,
public string $code,
/** @var list<int|string> */
public array $path,
/** @var array<string, mixed> */
public array $variables = [],
) {
/** @var string */
public $code;
/** @var string[] */
public $path;
/** @var string[] */
public $variables;
public function __construct(string $message, string $code, array $path, array $variables = [])
{
$this->message = $message;
$this->code = $code;
$this->path = $path;
$this->variables = $variables;
}
/**
* Formats the message template by substituting %variable% placeholders with their values.
*/
public function toString(): string
{
$vars = $this->variables;
@ -89,9 +83,7 @@ final class Message
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];
return $vars[$key] === null ? '' : $space . $vars[$key];
}, $this->message);
}
}

View file

@ -1,10 +1,12 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use Nette;
@ -15,16 +17,19 @@ use Nette;
*/
final class Processor
{
/** @var list<\Closure(Context): void> */
public array $onNewContext = [];
private Context $context;
private bool $skipDefaults = false;
use Nette\SmartObject;
/** @var array */
public $onNewContext = [];
/** @var Context|null */
private $context;
/** @var bool */
private $skipDefaults;
/**
* When enabled, properties with default values are omitted from the output.
*/
public function skipDefaults(bool $value = true): void
public function skipDefaults(bool $value = true)
{
$this->skipDefaults = $value;
}
@ -32,60 +37,58 @@ final class Processor
/**
* Normalizes and validates data. Result is a clean completed data.
* @return mixed
* @throws ValidationException
*/
public function process(Schema $schema, mixed $data): mixed
public function process(Schema $schema, $data)
{
$this->createContext();
$data = $schema->normalize($data, $this->context);
$this->throwErrors();
$this->throwsErrors();
$data = $schema->complete($data, $this->context);
$this->throwErrors();
$this->throwsErrors();
return $data;
}
/**
* Normalizes and validates and merges multiple data. Result is a clean completed data.
* @param list<mixed> $dataset
* @return mixed
* @throws ValidationException
*/
public function processMultiple(Schema $schema, array $dataset): mixed
public function processMultiple(Schema $schema, array $dataset)
{
$this->createContext();
$flatten = null;
$first = true;
foreach ($dataset as $data) {
$data = $schema->normalize($data, $this->context);
$this->throwErrors();
$this->throwsErrors();
$flatten = $first ? $data : $schema->merge($data, $flatten);
$first = false;
}
$data = $schema->complete($flatten, $this->context);
$this->throwErrors();
$this->throwsErrors();
return $data;
}
/**
* Returns all deprecation warnings collected during the last processing run.
* @return list<string>
* @return string[]
*/
public function getWarnings(): array
{
$res = [];
if (isset($this->context)) {
foreach ($this->context->warnings as $message) {
$res[] = $message->toString();
}
foreach ($this->context->warnings as $message) {
$res[] = $message->toString();
}
return $res;
}
private function throwErrors(): void
private function throwsErrors(): void
{
if ($this->context->errors) {
throw new ValidationException(null, $this->context->errors);
@ -93,10 +96,10 @@ final class Processor
}
private function createContext(): void
private function createContext()
{
$this->context = new Context;
$this->context->skipDefaults = $this->skipDefaults;
Nette\Utils\Arrays::invoke($this->onNewContext, $this->context);
$this->onNewContext($this->context);
}
}

View file

@ -1,38 +1,36 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
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).
* Normalization.
* @return mixed
*/
function normalize(mixed $value, Context $context);
function normalize($value, Context $context);
/**
* Merges two normalized values, with $value taking priority over $base.
* Merging.
* @return mixed
*/
function merge(mixed $value, mixed $base);
function merge($value, $base);
/**
* Validates the value and applies defaults, transforms, and assertions.
* Validation and finalization.
* @return mixed
*/
function complete(mixed $value, Context $context);
function complete($value, Context $context);
/**
* Returns the default value, or adds a missing-item error if the field is required.
* @return mixed
*/
function completeDefault(Context $context);

View file

@ -1,10 +1,12 @@
<?php declare(strict_types=1);
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Schema;
use Nette;
@ -15,18 +17,22 @@ use Nette;
*/
class ValidationException extends Nette\InvalidStateException
{
public function __construct(
?string $message,
/** @var list<Message> */
private readonly array $messages = [],
) {
parent::__construct($message ?? $messages[0]->toString());
/** @var Message[] */
private $messages;
/**
* @param Message[] $messages
*/
public function __construct(?string $message, array $messages = [])
{
parent::__construct($message ?: $messages[0]->toString());
$this->messages = $messages;
}
/**
* Returns all validation error messages as formatted strings.
* @return list<string>
* @return string[]
*/
public function getMessages(): array
{
@ -40,8 +46,7 @@ class ValidationException extends Nette\InvalidStateException
/**
* Returns all validation error messages as Message objects.
* @return list<Message>
* @return Message[]
*/
public function getMessageObjects(): array
{

View file

@ -15,14 +15,12 @@
}
],
"require": {
"php": "8.2 - 8.5"
"php": "8.0 - 8.6"
},
"require-dev": {
"nette/tester": "^2.5",
"tracy/tracy": "^2.9",
"phpstan/phpstan": "^2.1@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0",
"phpstan/phpstan-nette": "^2.0@stable",
"jetbrains/phpstorm-attributes": "^1.2"
},
"conflict": {
@ -30,7 +28,7 @@
"nette/schema": "<1.2.2"
},
"suggest": {
"ext-iconv": "to use Strings::chr(), ord() and reverse()",
"ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()",
"ext-json": "to use Nette\\Utils\\Json",
"ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()",
"ext-mbstring": "to use Strings::lower() etc...",
@ -50,12 +48,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "4.1-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
"dev-master": "4.0-dev"
}
}
}

View file

@ -41,7 +41,7 @@ The recommended way to install is via Composer:
composer require nette/utils
```
Nette Utils 4.1 is compatible with PHP 8.2 to 8.5.
Nette Utils 4.0 is compatible with PHP 8.0 to 8.6.
 <!---->

View file

@ -8,13 +8,10 @@
namespace Nette;
/**
* Represents object convertible to HTML string.
*/
interface HtmlStringable
{
/**
* Returns string in HTML format.
* Returns string in HTML format
*/
function __toString(): string;
}

View file

@ -11,19 +11,16 @@ use Nette;
/**
* Enhanced caching iterator with first/last/counter tracking.
* Smarter caching iterator.
*
* @template TKey
* @template TValue
* @extends \CachingIterator<TKey, TValue, \Iterator<TKey, TValue>>
* @property-read bool $first
* @property-read bool $last
* @property-read bool $empty
* @property-read bool $odd
* @property-read bool $even
* @property-read int $counter
* @property-read TKey $nextKey
* @property-read TValue $nextValue
* @property-read mixed $nextKey
* @property-read mixed $nextValue
*/
class CachingIterator extends \CachingIterator implements \Countable
{
@ -32,7 +29,6 @@ class CachingIterator extends \CachingIterator implements \Countable
private int $counter = 0;
/** @param iterable<TKey, TValue>|\stdClass $iterable */
public function __construct(iterable|\stdClass $iterable)
{
$iterable = $iterable instanceof \stdClass
@ -60,30 +56,45 @@ class CachingIterator extends \CachingIterator implements \Countable
}
/**
* Is the iterator empty?
*/
public function isEmpty(): bool
{
return $this->counter === 0;
}
/**
* Is the counter odd?
*/
public function isOdd(): bool
{
return $this->counter % 2 === 1;
}
/**
* Is the counter even?
*/
public function isEven(): bool
{
return $this->counter % 2 === 0;
}
/**
* Returns the counter.
*/
public function getCounter(): int
{
return $this->counter;
}
/**
* Returns the count of elements.
*/
public function count(): int
{
$inner = $this->getInnerIterator();
@ -118,14 +129,18 @@ class CachingIterator extends \CachingIterator implements \Countable
}
/** @return TKey */
/**
* Returns the next key.
*/
public function getNextKey(): mixed
{
return $this->getInnerIterator()->key();
}
/** @return TValue */
/**
* Returns the next element.
*/
public function getNextValue(): mixed
{
return $this->getInnerIterator()->current();

View file

@ -13,13 +13,14 @@ namespace Nette\Iterators;
*/
class Mapper extends \IteratorIterator
{
private \Closure $callback;
/** @var callable */
private $callback;
public function __construct(\Traversable $iterator, callable $callback)
{
parent::__construct($iterator);
$this->callback = $callback(...);
$this->callback = $callback;
}

View file

@ -20,7 +20,6 @@ use Nette\Utils\ObjectHelpers;
trait SmartObject
{
/**
* @param mixed[] $args
* @return mixed
* @throws MemberAccessException
*/
@ -46,8 +45,6 @@ trait SmartObject
/**
* @param mixed[] $args
* @return never
* @throws MemberAccessException
*/
public static function __callStatic(string $name, array $args)

Some files were not shown because too many files have changed in this diff Show more