# Strictify > A type-hint validation library for PHP Strictify is a Pydantic-inspired data-validation system for PHP 8.3+ that validates raw data against class type hints: a model's public property types are the schema, with no YAML and no config files. It ships as two interchangeable packages sharing one `Attributes\Strictify` API: the pure-PHP Composer library `attributes-php/strictify` (`composer require attributes-php/strictify`) for the widest compatibility, and the C extension `attributes-php/strictify-ext` (`pie install attributes-php/strictify-ext`, roughly an order of magnitude faster) for hosts you control. Core entry points: `Attributes\Strictify\validate()` hydrates a `BaseModel` from an array and throws `ValidationException` on invalid data, `BaseModel::toDict()` serializes a model back to an array, and `Attributes\Strictify\call()` invokes any callable with validated model parameters. Models are configured with `#[ModelConfigs]`, values are constrained with the constraint attributes, and failures are reported per field path via `ValidationException::getErrors()`. Source code: library https://github.com/Attributes-PHP/strictify, extension https://github.com/Attributes-PHP/strictify-ext # Getting started # Strictify ![Strictify]() **Strictify** validates data via type-hinting at lightning speed. Your model types are the schema: no configuration files, no YAML. The same `Attributes\Strictify` API ships as two interchangeable packages, and this documentation covers both: | | Package | Install | | --- | --- | --- | | **Strictify** (pure PHP) | [`attributes-php/strictify`]() | `composer require attributes-php/strictify` | | **Strictify Extension** | [`attributes-php/strictify-ext`]() | `pie install attributes-php/strictify-ext` | Same models, same functions, same behavior. The library offers the widest compatibility: it runs anywhere Composer runs — shared hosting, managed platforms, serverless. The extension offers maximum performance for those who control the host and can install a PHP extension — on average roughly an order of magnitude faster, up to \~96x on nested payloads (see [Benchmarks]()). ```php 30, 'birthday' => '1994-01-01T09:00:00+00:00', ]; $user = validate($rawData, new User()); var_dump($user->age); // int(30) var_dump($user->birthday); // object(DateTime) "1994-01-01 09:00:00.000000" (+00:00) ``` ## How it works ```text $rawData ──▶ validate($rawData, new User()) │ ├─ valid ───▶ hydrated User model (typed properties) └─ invalid ─▶ ValidationException ─▶ getErrors(): ['field.path' => ['message', ...]] ``` ## Requirements - PHP 8.3 or later ## Installation Pick one flavor — they expose the same `Attributes\Strictify` API: ```bash # Pure-PHP library — widest compatibility, runs anywhere Composer runs composer require attributes-php/strictify # C extension — maximum performance, for hosts you control pie install attributes-php/strictify-ext ``` New here? The [Quickstart]() takes under a minute. ## What's next - [Quickstart]() — install, first model, first validation error. - **Guides** — task-oriented: [validating payloads](), [nested models and arrays](), [aliases](), [error messages](), [sensitive data](), [calling functions](), [serializing models](). - **Reference** — [validate()](), [toDict()](), [call()](), [ModelConfigs](), [Constraints](), [Exceptions](), [API](). - **Resources** — [Benchmarks](), [FAQ]() and [Changelog](). ## Using with AI assistants This documentation is also available in LLM-friendly Markdown: [llms.txt]() indexes every page (each page is also served as Markdown at its own URL), and [llms-full.txt]() contains the full documentation in a single file. # Quickstart ## Installation Strictify ships as two interchangeable packages with the same `Attributes\Strictify` API. Pick one: ```bash # Pure-PHP library — runs anywhere Composer runs, no compiled extension needed composer require attributes-php/strictify # C extension — same API and behavior, roughly an order of magnitude faster (see Benchmarks) pie install attributes-php/strictify-ext ``` The library is the widest-compatibility option: it runs anywhere Composer runs, including shared hosting and managed platforms where PHP extensions cannot be installed. The extension targets those who control the host and can install a PHP extension — same API and behavior, roughly an order of magnitude faster (see Benchmarks). Requires PHP 8.3 or later. ## Your first model A model is a class extending `BaseModel`. Its public property type hints **are** the schema — no configuration files, no YAML: ```php 'John', 'age' => 30, 'birthday' => '1994-01-01T09:00:00+00:00', ], new User()); echo $user->name, "\n"; // John echo $user->age, "\n"; // 30 echo $user->birthday->format('Y-m-d'), "\n"; // 1994-01-01 ``` `validate()` returns the same model instance with every property hydrated to its declared type: `DateTimeInterface` properties hydrate from date strings, nested models hydrate recursively. ## Invalid data When any field fails, `validate()` throws a `ValidationException`. `getErrors()` returns every problem at once, keyed by field path: ```php 123, 'age' => 'old'], new Signup()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array // ( // [email] => Array ( [0] => Must be string ) // [age] => Array ( [0] => Must be integer ) // ) } ``` Nested structures report dot-notation paths (`address.street`, `users.0.email`). ## Serialize back to an array Once hydrated, a model serializes back to a plain array with `toDict()`: ```php 'John', 'age' => 30], new User()); print_r($user->toDict()); // Array ( [name] => John [age] => 30 ) ``` ## What's next - [Validating payloads]() — required fields, strict vs loose mode, hooks. - [Nested models and arrays]() — `Sequence`, `Union`, `Dict`, nested models. - [Aliases and aliasGenerator]() — accept `snake_case` payloads for `camelCase` properties. - [Error messages]() — custom and translated messages. - [Reference: validate()](), [toDict()](), [call()](), [Constraints](). # Guides # Validating payloads `validate($rawData, $model)` checks a raw array against the model's public property type hints and attributes, and returns the hydrated model. See the [validate() reference]() for the signature. ## Required fields Every property without a default value is required — typed or not, nullable or not. A missing key produces a `Field is required` error. A property with a declared default value is optional and keeps the default when the key is missing; a nullable property also accepts an explicit `null`: ```php getErrors()); // Array ( [name] => Array ( [0] => Field is required ) ) } ``` ## Strict and loose mode Validation is **strict by default**: a value must already have the declared type. Declare loose mode on the model to enable scalar coercion: ```php '30', 'name' => 123], new User()); var_dump($user->age); // int(30) var_dump($user->name); // string(3) "123" ``` In loose mode: - Exact type matches always win over coercion, regardless of declaration order. - When coercion is needed on a union of basic types, the declaration order is lost — the engine stores the union as a bitmask and tries the arms in the fixed order `int` → `float` → `string` → `bool`. Both `int|bool` and `bool|int` coerce `'1'` to `int(1)`; only values no earlier arm can take fall through to `bool`, so `'abc'` becomes `bool(true)`. One exception: for an `int|float` union, a numeric string keeps its natural type — `'1'` becomes `int(1)`, `'1.5'` becomes `float(1.5)`. `DateTimeInterface` properties coerce from date strings in both modes. > [!TIP] > > **When to use loose mode** > > Loose mode is convenient for form and query-string input, where everything arrives as a string. Keep strict mode for JSON API payloads, where a number in a string field usually signals a client bug. ## Return value semantics `validate()` returns the passed `$model` instance with every property populated from `$rawData`. Values are written with the type declared on the property: - Scalars are coerced to the declared type in loose mode. - `DateTimeInterface`-typed properties hydrate from date strings such as `1994-01-01T09:00:00+00:00`. - Properties typed with a `BaseModel` class hydrate recursively from nested arrays — see [Nested models and arrays](). - Enum-typed properties accept cases of that enum and coerce backing values (backed enums) or case names (pure enums) to the matching case in both modes — see [Enums](<#enums>). - Union-typed properties keep the raw value's type when it already matches one of the arms; otherwise coercion follows the fixed arm order described above. ## Enums A property typed with a PHP enum accepts that enum's cases — backed (`string` or `int`) and pure (non-backed) alike — and also coerces a scalar to the matching case, in both strict and loose mode: the backing value for backed enums, the case name for pure enums. A value with no matching case fails with an error listing the allowed cases: backing values for backed enums, case names for pure ones: ```php 'hearts', 'level' => 'Low'], new Card()); echo $card->suit->value, ' ', $card->level->name, "\n"; // hearts Low try { validate(['suit' => 'diamonds', 'level' => 'Low'], new Card()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [suit] => Array ( [0] => Must be 'hearts' or 'spades' ) ) } ``` ## Hooks Models may override two protected hooks, called by `validate()` around the validation run: ```php 'JOHN@EXAMPLE.COM'], new Signup()); echo $user->email, "\n"; // john@example.com ``` `beforeValidation()` may return a modified copy of `$rawData`; `afterValidation()` runs only when validation succeeded. The resolved `ModelConfigs` object is passed to both — see [ModelConfigs](). ## See also - [Nested models and arrays]() - [Aliases and aliasGenerator]() - [Error messages]() - [Exceptions and error catalog]() - [validate() reference]() # Nested models and arrays ## Nested models A property typed with another `BaseModel` class hydrates recursively from a nested array. Errors report dot-notation paths, including array element keys (`users.0.email`): ```php 'John', 'address' => ['street' => 'Main St', 'city' => 123], ], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [address.city] => Array ( [0] => Must be string ) ) } ``` Each nested model resolves its own [`#[ModelConfigs]`]() (for example its own `aliasGenerator`) — configs are inherited only from parent *classes*, never from the enclosing model. See [Aliases](). ## Typed arrays: Sequence, Union, Intersection, Dict Typed `array` properties declare their element shape with attributes from `Attributes\Strictify\Fields`: ```php ['php', 'dev'], 'mixed' => [1, 'two', [3]], 'lookup' => [1 => new stdClass()], ], new Blog()); ``` - `Sequence` validates every element against one element type. Keys must always be integers — a string key reports `Must be integer` under that key's path (e.g. `tags.x`). By default the array must additionally be a **list** with keys `0, 1, 2, ...` in order; a gap or out-of-order key reports a `sequenceKeys` error. Pass `sequential: false` to allow any integer keys. Pass `sorted: 'asc'` (or `'ASC'` / `'desc'` / `'DESC'`) to sort the validated values and renumber the keys `0, 1, 2, ...`; the default `null` keeps the input order, and any other value throws an `InvalidBaseModelException` instead of being ignored. Pass `uniqueValues: true` to reject repeated elements (`uniqueValues` error on the property). - `Union` accepts an element matching any declared arm — but only nested inside `Sequence(of: new Union(...))` or `Dict(of: new Union(...))`. Declared directly on an `array` property it throws an `InvalidBaseModelException`; on a non-array property it checks the whole value instead (below). - `Intersection` requires an element to match every declared class or interface. Its arms must name classes or interfaces only — enums are rejected, mirroring PHP intersection type hints. - `Dict` validates keys against `$key` and values against `$of`. The key spec accepts every PHP-castable key type — integer, string, float, boolean and null ([language.types.array]()). The engine casts float and bool keys to int and null to the empty string, so those arms match the post-cast key: a `T_FLOAT` or `T_BOOL` arm accepts integer keys, a `T_NULL` arm accepts the `""` key (`[null => ...]`). E.g. `#[Dict(key: T_INT | T_STRING | T_NULL, of: ...)]`. Pass `uniqueValues: true` to reject repeated values (`uniqueValues` error on the property). `Sequence`, `Dict` and `Intersection` may only be declared on array-like properties — an `array` hint (alone or inside a union), `mixed`, or untyped. On anything else they throw an `InvalidBaseModelException` naming the property, whether the hint is scalar (`string`, `int`), the `object` class type, or an intersection type without `array`. On `mixed` or untyped properties a non-array value fails with `Must be array`. ## Union on non-array properties Declared directly on a property whose value is not an array — `int|float`, `string`, `mixed`, untyped — `#[Union(...)]` checks the whole value against its arms, exactly (never coerced; in loose mode it sees the coerced value): ```php 1.5], new Measurement()); ``` On a **union-typed** property the arms must repeat the native hint's type-hints exactly — order-insensitive, class names matched case-insensitively. A subset or an extra type is a malformed model and throws an `InvalidBaseModelException` at validation. A **nullable** hint (`?string`) counts `null` as one of its type-hints, so the arms must include `T_NULL`: ```php [1, 'two', [3]], 'lookup' => [1 => 'a', 'k' => 2], ], new Shapes()); ``` (Masks are built from the `T_*` constants — enum cases don't support `|`, so `Type::int | Type::string` is not valid PHP; write `T_INT | T_STRING`.) The bitmask form loses the declaration order that a `new Union(...)` argument list keeps: values that already match an arm are still accepted as-is, but in loose mode coercions then run in a fixed order (bool, integer, float, string) instead of declaration order — see [Strict and loose mode](). ```php ['a', 'b'], 'map' => [7 => 'a']], new Tags()); echo count($model->list), ' ', count($model->map), "\n"; // 2 1 ``` The same attributes compose with `new` expressions to describe nested arrays: ```php ) and [`call()`](), 512 by default. Raise it when a legitimately deep payload is expected, or lower it to reject deep nesting earlier than the stack would; the value must be greater than 0, and the exception message reports the limit that fired (`... depth of 10 exceeded ...`). ## See also - [Validating payloads]() - [Constraints]() — value-level rules on elements' parent property - [validate() reference]() # Aliases and aliasGenerator Payloads often use a different naming convention than the PHP properties (a JSON API sending `first_name` for a `$firstName` property). Strictify resolves input keys through aliases: 1. An explicit `#[Alias('...')]` on the property always wins. 2. Otherwise, the model's `aliasGenerator` transforms the property name (`'pascal'`, `'camel'`, `'snake'`, `'kebab'`). 3. Otherwise the property name is used as-is. ## The Alias attribute Map one input key to one property: ```php 'John'], new User()); echo $user->name, "\n"; // John ``` ### Malformed alias declarations Two alias mistakes are model-definition errors, so they throw an `InvalidBaseModelException` instead of producing a field nothing can satisfy: - `#[Alias('')]` — an empty alias would expect the empty-string key. - Two properties resolving to the same input key: `#[Alias('id')]` on both `$a` and `$b`, or an alias generator collapsing two names onto one key (`snake` maps `$aB` and `$a_b` to `a_b`). The message names both properties and the key. ```php 1], new User()); // InvalidBaseModelException: Properties User::$userId and User::$accountId both resolve to the input key "id". ``` ## The aliasGenerator option Transform every property name with one `#[ModelConfigs]` declaration: ```php 'John', 'user2_id' => 123], new User()); echo $user->firstName, ' ', $user->user2Id, "\n"; // John 123 ``` Names are split on case boundaries and separators, so digits stay attached (`$user2Id` → `user2_id`). Acronyms are split letter by letter: `snake` maps `$HTTPResponse` to `h_t_t_p_response`, not `http_response` — declare `#[Alias('http_response')]` when the payload uses the acronym as a word. Resolved names are also used in **error paths**, so clients see the key they sent: ```php 'John'], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [last] => Array ( [0] => Field is required ) ) } ``` ## Serializing back: toDict(useAlias: true) `toDict()` is keyed by the raw property names by default. Pass `useAlias: true` to get the resolved names, so the output round-trips through `validate()`: ```php 'John', 'last_name' => 'Doe'], new User()); print_r($user->toDict()); // Array ( [firstName] => John [lastName] => Doe ) print_r($user->toDict(useAlias: true)); // Array ( [first_name] => John [last_name] => Doe ) validate($user->toDict(useAlias: true), new User()); // works ``` ## Nested models A nested model uses **only its own** `aliasGenerator` (inherited at most from its parent class) — both when validating and when serializing with `useAlias: true`. It never inherits the enclosing model's generator: without one, it expects the raw property names. See [Nested models]() and the [ModelConfigs reference](). ## See also - [Serializing models]() - [ModelConfigs reference]() - [validate() reference]() # Error messages Default messages follow the `Must be ` pattern, joined for unions (`Must be boolean, integer or string`). Every message has a stable translation key — the full catalog is [below](<#default-error-messages>). ## Default error messages Each default message has a stable translation key passed as the first argument to the translator registered with `ErrorTranslator::set()` (the default message itself is the second argument): | Key | Default message | | --- | --- | | `required` | `Field is required` | | `type` | `Must be {expected}` | | `alphaDash` / `alphaDashType` | `Must only contain letters, numbers, dashes and underscores` | | `ascii` / `asciiType` | `Must only contain ASCII characters` | | `between` / `betweenType` | `Must be between {expected}` | | `contains` | `Must contain {expected}` | | `datetime` | `Must be a datetime in the format {expected}` | | `endsWith` | `Must end with one of: {expected}` | | `in` | `Must be one of: {expected}` | | `max` / `min` | `Must be at most/least {expected}` | | `multipleOf` | `Must be a multiple of {expected}` | | `regex` | `Must match the pattern {expected}` | | `size` | `Must have a size {expected}` | | `startsWith` | `Must start with one of: {expected}` | | `ulid` / `uuid` | `Must be a valid ULID/UUID` | | `union` | `Must be {expected}` | | `sequenceKeys` | `Must be a sequential list (keys 0, 1, 2, ...)` (gapped or out-of-order integer key in a `#[Sequence]` array) | | `extra` | `Extra inputs are not permitted` (unknown key under `extra: 'forbid'`) | See [Placeholders](<#placeholders>) for the `{field}`, `{value}` and `{expected}` substitutions available in every template. ## Placeholders Every template — the defaults, translated messages and `ErrorMessage` overrides — supports the same three placeholders, substituted after translation: | Placeholder | Renders | | --- | --- | | `{field}` | The resolved field name — the dot-notation path for nested fields, the [alias]() when one is declared | | `{value}` | The rejected value: strings are quoted (`'abc'`), `null`/`true`/`false` render literally, numbers as-is, arrays as `array`, stringable objects via `__toString()` — redacted to `***` for [`#[Sensitive]`]() properties | | `{expected}` | For `type`/`union` errors the expected type list (`Must be integer, float or string`); for constraint errors the constraint parameters (`18`, a regex pattern, ...) | `{expected}` renders as an empty string for the `extra` error (unknown key under `extra: 'forbid'`), which has no owning property. Userland constraint `message()` output goes through the same substitution, so `{field}` and `{value}` work there too — see [Constraints](). ## Per-property overrides: ErrorMessage Override any of a property's templates with the `ErrorMessage` attribute — one named argument per key from the [default catalog](<#default-error-messages>) above (`required`, `type`, `min`, `max`, `sequenceKeys`, ...), each defaulting to that key's default message: ```php #[ErrorMessage(required: 'Name is mandatory', min: 'Too small, at least {expected}')] ``` The catalog keys, the `#[ErrorMessage]` arguments and the keys handed to the translator are the same strings, so `#[ErrorMessage(sequenceKeys: ...)]` overrides the message reported under `sequenceKeys`. The `extra` key is discarded: extra inputs have no owning property, so that error always uses the translator or its default. ```php 123], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [name] => Array ( [0] => Expected string ) ) } try { validate([], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [name] => Array ( [0] => Name is mandatory ) ) } ``` The `{expected}` placeholder renders the expected type list. `{field}` and `{value}` are also available. ## Translating error messages Register a translator once per request with `ErrorTranslator::set()`. The callable receives the stable message key as `?string $key` (`null` for custom `#[ErrorMessage]` values, which have no key) and the default message template as `string $message`, and returns the translated template — or `null` to keep the default: ```php match ($key) { 'required' => 'Campo obrigatório', 'type' => 'Deve ser {expected}', 'min' => 'Deve ser no mínimo {expected}', default => null, }); class User extends BaseModel { #[Min(18)] public int $age; public string $name; } try { validate(['age' => 5], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [age] => Array ( [0] => Deve ser no mínimo 18 ) // [name] => Array ( [0] => Campo obrigatório ) ) } ``` Multiple languages — a catalog keyed by locale; switch locale by re-registering the translator (takes effect immediately, the per-property template cache is cleared): ```php [ 'required' => 'Field is required', 'type' => 'Must be {expected}', 'min' => 'Must be at least {expected}', ], 'pt_BR' => [ 'required' => 'Campo obrigatório', 'type' => 'Deve ser {expected}', 'min' => 'Deve ser no mínimo {expected}', ], ]; public static function useLocale(string $locale): void { ErrorTranslator::set( fn (?string $key, string $message): ?string => $key === null ? null : (self::MESSAGES[$locale][$key] ?? null) ); } } class User extends BaseModel { #[Min(18)] public int $age; } Catalog::useLocale('pt_BR'); try { validate(['age' => 5], new User()); } catch (ValidationException $e) { print_r($e->getErrors()); // Array ( [age] => Array ( [0] => Deve ser no mínimo 18 ) ) } ``` Notes: - `ErrorMessage` attribute values have no stable key: the translator receives `null` as `$key` and the attribute value as `$message`. Since attribute arguments must be constant expressions (no callables), use a key string or a class constant there; when the translator returns `null`, the literal attribute string is used as-is, so existing attributes keep working unchanged: ```php ) — exception types and the `getErrors()` structure - [Constraints]() — constraint error messages and their keys - [Sensitive data]() — `{value}` redaction for sensitive fields # Sensitive data Mark a property with `#[Sensitive]` to keep its value out of the library's output — like `#[\SensitiveParameter]` keeps parameter values out of stack traces. The property itself still holds the real value after `validate()`: ```php 'andre', 'password' => 'hunter2'], new Credentials()); echo $model->password, "\n"; // hunter2 print_r($model->toDict()); // Array ( [username] => andre ) — password omitted print_r($model->toDict(includeSensitive: true)); // Array ( [username] => andre [password] => hunter2 ) ``` ## What is masked, and where - **`toDict()`** omits sensitive properties entirely; pass `includeSensitive: true` to serialize their real values. The omission composes with [aliases]() (the key — property name by default, alias with `useAlias: true` — is dropped) and with nested models (each level omits its own sensitive fields). - **Error messages**: the `{value}` placeholder in error message templates is always redacted to `***` for sensitive properties, so secrets do not leak into `ValidationException` messages. - **Debug output** masks them as well: `var_dump()`, `print_r()`, `debug_zval_dump()` — including model objects dumped as arguments inside exception traces — render a sensitive property as `***`, for every property type (ints, floats, strings, bools, arrays, objects and nested `BaseModel` properties): ```php 'andre', 'password' => 'hunter2'], new Credentials()); print_r($model, true); // Credentials Object ( [username] => andre [password] => *** ) json_encode($model); // {"username":"andre","password":"hunter2"} — real values ``` `BaseModel` installs a custom `get_properties_for` object handler that only alters the engine's debug view (`ZEND_PROP_PURPOSE_DEBUG`); property access, `foreach`, `(array)` casts, `get_object_vars()`, `json_encode()`, `serialize()` and `var_export()` all keep the real values. ## Sensitive parameters in call() When the target's parameter is marked `#[\SensitiveParameter]`, [call()]() keeps it out of the errors it raises itself and the engine redacts it in stack traces. See [Calling functions](). ## See also - [Serializing models]() - [Error messages]() - [toDict() reference]() # Calling functions `call($function, $params, $dependencies)` invokes a function or callable: every `BaseModel`-typed parameter hydrates from `$params` through the same engine [validate()]() uses, and every other parameter is injected from `$dependencies`. See the [call() reference]() for the signature. ```php name}"; } echo call('registerUser', ['age' => 30, 'name' => 'Andre']), "\n"; // registered Andre ``` A `ValidationException` thrown while hydrating a parameter propagates out of `call()` unchanged, with the same dot-notation field paths. ## Dependencies Non-model parameters take their values from `$dependencies` (an array or any `ArrayAccess` container): - Matched by parameter name first, then in positional order. - Internal functions (whose signatures cannot declare models) receive them positionally: `call('str_repeat', [], ['x', 3])` returns `xxx`. - A missing value for an optional parameter lets the engine apply the declared default. - A missing value for a required parameter throws a `CallException` (an `ArgumentCountError` subclass): `No value provided for parameter $second of registerUser().` - Variadic targets receive the leftover positional dependencies. ```php 'Andre']), "\n"; // Hello Andre! ``` ## Lazy containers Instead of an array, pass any `ArrayAccess` instance — `ArrayObject` or a lazy DI container. The container is only asked for the dependencies the call actually consumes: `offsetGet()` runs solely for parameters that look a value up, so a service inside a lazy container is constructed only when a parameter needs it: ```php (object) ['name' => 'app']]); function ship(stdClass $logger): string { return "shipping with {$logger->name}"; } echo call('ship', [], $container), "\n"; // shipping with app ``` Exceptions thrown by a container's `offsetExists()`/`offsetGet()` propagate as-is. Passing anything other than an `array` or `ArrayAccess` throws a `TypeError`. ## Sensitive parameters When the target's parameter is marked `#[\SensitiveParameter]`, `call()` reports a missing dependency positionally (`No value provided for parameter 2 of login().`) instead of naming the parameter, and the engine replaces the argument with a `\SensitiveParameterValue` object in `getTrace()`/`getTraceAsString()` of any exception the callable throws — while the callable still receives the real value: ```php 'andre', 'password' => $secret]); // RuntimeException trace frame: login('andre', Object(SensitiveParameterValue)) ``` ## See also - [call() reference]() - [Validating payloads]() - [Sensitive data]() # Serializing models `BaseModel::toDict()` returns the model's public properties as an array, so a hydrated model can be serialized back to plain data. See the [toDict() reference]() for the full signature. ```php 'John', 'age' => 30], new User()); print_r($user->toDict()); // Array ( [name] => John [age] => 30 ) ``` ## Field names: property names vs aliases By default the output is keyed by the **raw PHP property names**. Pass `useAlias: true` to key it by the resolved field names ([aliases]() and `aliasGenerator` are applied; each nested model uses only its own generator, never the enclosing model's) — the output then round-trips through `validate()`: ```php 'John', 'first_name' => 'John'], new User()); print_r($user->toDict()); // Array ( [name] => John [firstName] => John ) print_r($user->toDict(useAlias: true)); // Array ( [user_name] => John [first_name] => John ) validate($user->toDict(useAlias: true), new User()); // round-trips ``` ## Value serialization - Scalars and arrays (including `Sequence`/`Dict` shapes) are returned as-is, recursing into nested elements. - `DateTimeInterface` values are formatted as ISO 8601 strings (`Y-m-d\TH:i:sP`), or with the format/timezone of a `#[DateTime]` constraint on the property. - Nested `BaseModel` properties are serialized recursively. - Properties marked with [`#[Sensitive]`]() are omitted unless `includeSensitive: true` is passed (the flag propagates into nested models and arrays). - Uninitialized typed properties are omitted from the output. ```php 'John', 'address' => ['street' => 'Main St'], 'birthday' => '1994-01-01', ], new User()); print_r($user->toDict()); // Array ( [name] => John [address] => Array ( [street] => Main St ) [birthday] => 1994-01-01 ) ``` ## See also - [Aliases and aliasGenerator]() - [Sensitive data]() - [toDict() reference]() # Reference # validate() Validates a raw data array against the type hints and attributes of a `BaseModel` instance, and returns the hydrated model. ```php ), then the [guides](). ## Parameters | Parameter | Type | Description | | --- | --- | --- | | `$rawData` | `array` | The input data, keyed by property name (or by [alias]()). Missing keys fail validation unless the property is nullable or declares a default value. | | `$model` | `BaseModel` | The model instance to hydrate. Its public property type hints and attribute declarations define the validation schema. | | `$maxDepth` | `int` | Nesting limit for this run: how many models deep the payload may nest before a `MaxDepthException` is thrown. Defaults to 512; the value must be greater than 0. The limit only applies to this call — a nested `validate()` from a hook starts from the default again. | ## Return value Returns the passed `$model` instance with every property populated from `$rawData`. Values are written with the type declared on the property: - Scalars are coerced to the declared type in [loose mode](). - `DateTimeInterface`-typed properties hydrate from date strings such as `1994-01-01T09:00:00+00:00`. - Properties typed with a `BaseModel` class hydrate recursively from nested arrays. - Enum-typed properties accept cases of that enum and coerce backing values (backed enums) or case names (pure enums) to the matching case in both modes — see [Enums](). - Union-typed properties keep the raw value's type when it already matches one of the arms; otherwise the engine coerces them in its fixed order (`int` → `float` → `string` → `bool`), never in declaration order — see [Strict and loose mode](). ## Exceptions | Exception | Thrown when | | --- | --- | | `Attributes\Strictify\Exceptions\ValidationException` | Any field fails validation. Call `getErrors()` for the error list — see [Exceptions](). | | `Attributes\Strictify\Exceptions\InvalidBaseModelException` | The model declaration is malformed, for example an attribute argument with the wrong type (`#[Min('fifteen')]`), an unresolvable class arm, or a `#[ModelConfigs]` option with an unknown value or the wrong type. | | `Attributes\Strictify\Exceptions\MaxDepthException` | The payload nests models deeper than `$maxDepth` (512 by default). | | `ValueError` | A call argument is unusable: `$maxDepth` below 1, or a translator returning something other than `?string`. | ## Validation rules at a glance | Rule | Behavior | Guide | | --- | --- | --- | | Required fields | Every property without a default value is required (typed or nullable); defaulted properties are optional | [Validating payloads]() | | Union on union hints | `#[Union(...)]` on a union-typed property must repeat the hint's type-hints exactly, else `InvalidBaseModelException` | [Nested models and arrays]() | | Strict vs loose mode | Strict by default; `#[ModelConfigs(strict: false)]` enables scalar coercion | [Validating payloads]() | | Aliases | `#[Alias]` maps one input key; `aliasGenerator` transforms all keys; resolved names appear in error paths | [Aliases]() | | Nested models & arrays | `BaseModel` properties hydrate recursively; `Sequence`/`Union`/`Intersection`/`Dict` shape arrays | [Nested models and arrays]() | | Enums | Enum-typed properties accept cases of the enum and coerce a scalar (backing value, or case name for pure enums) to the matching case in both strict and loose mode; the error lists the allowed cases | [Validating payloads]() | | Constraints | Value-level rules via constraint attributes, running after the type check | [Constraints]() | | Error messages | `Must be ` defaults; per-property `ErrorMessage`; translatable via `ErrorTranslator::set()` | [Error messages]() | | Sensitive fields | `#[Sensitive]` keeps values out of `toDict()`, error messages and debug output | [Sensitive data]() | | Model configuration | `#[ModelConfigs(...)]` options: `aliasGenerator`, `strict`, `stopAtFirstError`, `extra`, `strToLower`/`strToUpper`/`stripWhitespace`. Resolved per model class — inherited from parent classes only, never from an enclosing model | [ModelConfigs]() | | Hooks | `beforeValidation()` / `afterValidation()` around the validation run | [Validating payloads]() | ## Serializing back to an array `BaseModel::toDict()` returns the model's public properties as an array. See [toDict()]() and the [serializing guide](). ## See also - [call()]() — invoke a callable with hydrated model parameters - [Exceptions and error catalog]() - [API reference]() # toDict() `BaseModel::toDict()` returns the model's public properties as an array, so a hydrated model can be serialized back to plain data. ```php toDict(); ``` ## Field names By default the output is keyed by the raw PHP property names. Pass `useAlias: true` to key it by the resolved field names [validate()]() expects instead: [aliases]() and the `aliasGenerator` from `#[ModelConfigs]` are applied, and each nested model uses only its own generator (inherited at most from its parent class, never from the enclosing model). With `useAlias: true` the output therefore round-trips through `validate()`: ```php 'John', 'birthday' => '1994-01-01T09:00:00+00:00'], new User()); $user->toDict(); // ['name' => 'John', 'birthday' => '1994-01-01T09:00:00+00:00'] $user->toDict(useAlias: true); // ['user_name' => 'John', 'birthday' => '1994-01-01T09:00:00+00:00'] validate($user->toDict(useAlias: true), new User()); // works ``` ## Value serialization - Scalars and arrays (including `Sequence`/`Dict` shapes) are returned as-is, recursing into nested elements. - `DateTimeInterface` values are formatted as ISO 8601 strings (`Y-m-d\TH:i:sP`). - Nested `BaseModel` properties are serialized recursively. - Properties marked with [`#[Sensitive]`]() are omitted from the output. Pass `includeSensitive: true` to `toDict()` to serialize their real values (the flag propagates into nested models and arrays). The key is the property name by default and the resolved alias with `useAlias: true`. - Uninitialized typed properties are omitted from the output. ```php 'John', 'address' => ['street' => 'Main St']], new User()); $user->toDict(); // ['name' => 'John', 'address' => ['street' => 'Main St']] ``` ### DateTime constraints When a property has a `#[DateTime(format: ..., timezone: ...)]` constraint, `toDict()` uses that format and timezone instead of the ISO 8601 default: ```php '1994-01-01'], new Event()); $event->toDict(); // ['startsAt' => '1994-01-01'] (Madrid is UTC+1 in January, formatted as Y-m-d) ``` ## See also - [Serializing models guide]() - [Aliases and aliasGenerator]() - [Sensitive data]() - [validate() reference]() # call() Calls a function or callable with validated models: `BaseModel` parameters hydrate from the raw data array through the same engine [validate()]() uses, and every other parameter is injected from a dependencies array or `ArrayAccess` container. ```php ). | | `$dependencies` | `array\\|ArrayAccess` | Values for the non-model parameters, matched by parameter name first and then positionally. Defaults to `[]`. | | `$maxDepth` | `int` | Nesting limit for this run: how many models deep the hydrated parameters may nest before a `MaxDepthException` is thrown. Defaults to 512; the value must be greater than 0. | ## Model hydration Every `BaseModel`-typed parameter of the callable is hydrated from `$params` through the full validate() flow: strict/loose mode, [aliases](), array type-hint attributes, hooks and `ValidationException` with dot-notation field paths all behave identically. ```php name}"; } call('registerUser', ['age' => 30, 'name' => 'Andre']); // "registered Andre" ``` A `ValidationException` thrown while hydrating a parameter propagates out of `call()` unchanged. ## Dependencies Non-model parameters take their values from `$dependencies`: - Matched by parameter name first, then in positional order. - Internal functions (whose signatures cannot declare models) receive them positionally: `call('str_repeat', [], ['x', 3])` returns `xxx`. - A missing value for an optional parameter lets the engine apply the declared default. - A missing value for a required parameter throws a `CallException` (an `ArgumentCountError` subclass): `No value provided for parameter $second of registerUser().`. - Variadic targets receive the leftover positional dependencies. ## Lazy ArrayAccess containers Instead of an array, pass any `ArrayAccess` instance — `ArrayObject` or a lazy DI container. The container is only asked for the dependencies the call actually consumes: `offsetGet()` runs solely for parameters that look a value up by name or position, so a service inside a lazy container is constructed only when a parameter needs it. ```php $logger]); function ship(stdClass $logger): string { return "shipping with {$logger->name}"; } call('ship', [], $container); ``` Exceptions thrown by a container's `offsetExists()`/`offsetGet()` propagate as-is. Passing anything other than an `array` or `ArrayAccess` (an integer, a plain object, a string) throws a `TypeError`. ## Sensitive parameters When the target's parameter is marked `#\SensitiveParameter`, `call()` keeps it out of the errors it raises itself: a missing required dependency is reported positionally (`No value provided for parameter 2 of login().`) instead of naming the parameter. Stack-trace redaction is unchanged — the engine replaces the argument with a `\SensitiveParameterValue` object in `getTrace()`/`getTraceAsString()` of any exception the callable throws, while the callable still receives the real value: ```php 'andre', 'password' => $secret]); // RuntimeException trace frame: login('andre', Object(SensitiveParameterValue)) ``` ## Return value `call()` returns the callable's return value, unchanged. ## See also - [Calling functions guide]() - [validate() reference]() - [Sensitive data]() # ModelConfigs Declare `#[ModelConfigs(...)]` on the model class to change how `validate()` resolves and checks input. Every option is optional, and a child class inherits its parent's `ModelConfigs` unless it declares its own: ```php [!NOTE] > > **Inheritance is class-based only** > > `ModelConfigs` is inherited **only through the class hierarchy** (a child class from its parent class). A nested model — a `BaseModel` used as a property of another model — **never** inherits the enclosing model's configs: each model class resolves its own `#[ModelConfigs]` (or its parent class's), so `aliasGenerator`, `strict`, `extra`, the string normalizations and `stopAtFirstError` apply per model class. An invalid option value throws an `InvalidBaseModelException` listing the valid options (e.g. `aliasGenerator` accepts `pascal, camel, snake, kebab`). ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `aliasGenerator` | `?string` | `null` | `'pascal'` \| `'camel'` \| `'snake'` \| `'kebab'` — derives the expected input keys from property names, see [Aliases]() | | `strict` | `bool` | `true` | `false` enables loose-mode coercion, see [Strict and loose mode]() | | `stopAtFirstError` | `bool` | `false` | `true` aborts the validation run at the first error | | `extra` | `?string` | `null` | `null` resolves to `'allow'` when the class is marked `#[\AllowDynamicProperties]`, `'ignore'` otherwise; `'ignore'` \| `'forbid'` \| `'allow'` — what to do with unknown input keys | | `strToLower` | `bool` | `false` | lowercase string values before validation | | `strToUpper` | `bool` | `false` | uppercase string values before validation (wins over `strToLower`) | | `stripWhitespace` | `bool` | `false` | trim string values before validation | Error message translation is not a `ModelConfigs` option: it is a static callable on the dedicated `ErrorTranslator` class, set with `ErrorTranslator::set()` and read back with `ErrorTranslator::get()` (null until set) — see [Error messages](). Option values are read from the attribute arguments and checked against the types above: a `bool` option only accepts `true`/`false`, a `?string` option only a string (at most 127 characters) or `null`. A wrong type throws an `InvalidBaseModelException` instead of being cast, so `#[ModelConfigs(strict: 1)]` or `#[ModelConfigs(strToLower: 'yes')]` never silently flips a flag: ```php 'John', 'user2_id' => 123], new User()); // ok validate(['firstName' => 'John'], new User()); // ValidationException: ['first_name' => ['Field is required']] ``` ## strict `strict: false` enables loose mode: scalar values are coerced to the declared type instead of rejected. See [Strict and loose mode]() for the coercion rules. ## stopAtFirstError By default every failing field is collected into `ValidationException::getErrors()`. With `stopAtFirstError: true` the run aborts at the first error: ```php ['Field is required']] — email is not reported ``` ## extra Controls what happens with input keys that resolve to no property of the model: - `null` (default): resolved per model class — `'allow'` when the class is marked `#[\AllowDynamicProperties]`, `'ignore'` otherwise. - `'ignore'`: unknown keys are silently dropped. - `'allow'`: unknown keys are stored as dynamic properties on the model instance. Integer keys have no property name and keys naming a declared property (e.g. the raw property name when `aliasGenerator` renames the expected key) are never stored. - `'forbid'`: every unknown key produces an error keyed by the raw key (dot path for nested models), with the default message `Extra inputs are not permitted`, translatable under the `extra` key. Keys produced by `aliasGenerator`/`Alias` count as known, integer keys are reported under their numeric name, and `stopAtFirstError` reports only the first one. Each model validates with its own class's configs: a `null` extra is resolved per model class at validation time, against that class's own `#[\AllowDynamicProperties]`, and a non-null `extra` declared on an enclosing model never applies to its nested models. A subclass without its own `#[ModelConfigs]` inherits the ancestor's `extra` along with the rest of the declaration; when nothing in the chain declares it, it stays `null` and each class resolves it against its own `#[\AllowDynamicProperties]` flag. ```php 'John', 'junk' => 1], new User()); // ValidationException: ['junk' => ['Extra inputs are not permitted']] ``` ## strToLower, strToUpper, stripWhitespace Normalize string input values before the type check, so constraints and the written property see the normalized value. Applied only to values of properties whose hint accepts `string` (including `mixed` and string arms of unions) — non-string values, and strings bound for non-string hints such as `DateTime` coercion, are left untouched. The order is strip → lower → upper, so `strToUpper` wins when both case flags are set. Works in strict and loose mode. Normalization applies to the model's own properties only — nested models resolve their own configs: ```php ' JOHN DOE ', 'age' => 30], new User())->name; // "john doe" ``` Case conversion is byte-wise ASCII: `'ÄNDRE'` lowercases to `'Ändre'`, not `'ändre'`, and no locale rule applies. Array elements are never normalized — only the string value bound to a property is, so a `string` property holding a serialized list keeps its inner casing. The normalized value is what the constraints and the type check see. ## Resolved-config getters All options are also exposed through getters on the resolved `ModelConfigs` object — `getExtra()`, `isStrToLower()`, `isStrToUpper()`, `isStripWhitespace()` (plus `getAliasGenerator()`, `isStrict()`, `isStopAtFirstError()`) — which `validate()` passes to the model hooks (`beforeValidation()`/`afterValidation()`, see [Hooks]()) and to `ConfigAwareConstraint::setModelConfigs()`. ## See also - [Aliases and aliasGenerator guide]() - [Error messages guide]() - [validate() reference]() # Constraints Constraints are attributes that add value-level rules on top of the native type hints. They run after the property's type check succeeds (so they always see a value of the declared type, or the coerced value in loose mode) and before the value is written to the model — a failing constraint keeps the value out of the model. ```php 5], new User()); // InvalidBaseModelException: Attribute "Attributes\Strictify\Fields\Constraints\Between" on User::$age: // $min (99) must be less than or equal to $max (18). ``` | Constraint | Rejected arguments | | --- | --- | | `Between` | a `NAN` bound; `$min` greater than `$max` | | `Max`, `Min`, `MultipleOf` | a `NAN` bound | | `Size` | a negative `$min` or `$max`; `$min` greater than `$max` | | `In` | no declared value | | `StartsWith`, `EndsWith` | no declared value; an empty string entry (it matches every value) | | `Regex` | a pattern that cannot compile: missing or unterminated delimiter, unknown or duplicate modifier, invalid body, embedded NUL byte | | `Email` | `domain: ''`, `domain: []`, or an empty string entry in the list | | `Url` | `protocol`/`domain` set to `''`, `[]`, or a list holding an empty string | Degenerate-but-satisfiable arguments are accepted: `Between(5, 5)`, `Between(-INF, INF)`, `Size` with no bounds, `MultipleOf(0)`, `MultipleOf(-5)`, and a pattern with every supported modifier (`/^[a-z]+$/iDSUXn`). Because the rule runs during the field's first compile, the check is per model class: the `InvalidBaseModelException` fires even when the payload has no value for the property, and it never caches a partial result. ## Built-in constraints at a glance All built-ins live in `Attributes\Strictify\Fields\Constraints` and may be declared on properties and parameters. | Attribute | Category | Constructor | Fails when | | --- | --- | --- | --- | | [`AlphaDash`](<#alphadash>) | string | `()` | the string contains characters other than letters, numbers, dashes and underscores | | [`Ascii`](<#ascii>) | string | `()` | the string contains bytes outside 7-bit ASCII (0x00-0x7F) | | [`Regex`](<#regex>) | string | `(string $regex)` | the string does not match the pattern (`preg_match` semantics: a partial match passes) | | [`StartsWith`](<#startswith>) | string | `(string\\|int\\|float ...$values)` | the string starts with none of the declared values | | [`EndsWith`](<#endswith>) | string | `(string\\|int\\|float ...$values)` | the string ends with none of the declared values | | [`Ulid`](<#ulid>) | string | `()` | the string is not a valid ULID (26 Crockford base32 characters, either letter case) | | [`Uuid`](<#uuid>) | string | `()` | the string is not a canonical UUID (8-4-4-4-12 hex groups separated by dashes, either letter case) | | [`Between`](<#between>) | numeric | `(int\\|float $min, int\\|float $max)` | the number is outside the inclusive range | | [`Max`](<#max>) | numeric | `(int\\|float $value)` | the number exceeds the inclusive upper bound | | [`Min`](<#min>) | numeric | `(int\\|float $value)` | the number is below the inclusive lower bound | | [`MultipleOf`](<#multipleof>) | numeric | `(int\\|float $value)` | the number is not a multiple of the divisor | | [`In`](<#in>) | membership | `(string\\|int\\|float\\|bool ...$values)` | the value matches none of the declared values | | [`Contains`](<#contains>) | membership | `(string\\|int\\|float ...$values, at least one)` | an array is missing one of the declared values, or a string is missing one of them as a substring | | [`Size`](<#size>) | size | `(?int $min = null, ?int $max = null)` | the string length or array count is outside the inclusive bounds | | [`DateTime`](<#datetime>) | date/time | `(string $format = 'X-m-d\\TH:i:sP', DateTimeZone\\|string\\|null $timezone = null)` | the value does not parse in the declared format and timezone | | [`Email`](<#email>) | format | `(?string\\|array $domain = null)` | the string is not a valid email address, or its domain is not in the declared `$domain` list | | [`Url`](<#url>) | format | `(?string\\|array $protocol = null, ?string\\|array $domain = null)` | the string is not a URL with a scheme (`https://...`), or its scheme/host is not in the declared `$protocol`/`$domain` | | [`Domain`](<#domain>) | format | `()` | the string is not a valid domain name | | [`Ip`](<#ip>) | format | `(?string $version = null)` | the string is not an IP address (`v4`/`v6` restricts the family) | | [`Iban`](<#iban>) | format | `()` | the string is not a valid IBAN (mod-97 checksum) | | [`Isbn`](<#isbn>) | format | `()` | the string is not a valid ISBN-10 or ISBN-13 | | [`CreditCard`](<#creditcard>) | format | `()` | the string is not a 12-19 digit number passing the Luhn check | | [`Version`](<#version>) | format | `()` | the string is not a semantic version (`1.2.3`, `v2.0.0-rc.1+build`) | | [`MacAddress`](<#macaddress>) | format | `()` | the string is not a MAC address (`00:1A:2B:3C:4D:5E`) | | [`Alnum`](<#alnum>) | string | `(string $extra = '')` | the string contains characters other than letters, numbers and `$extra` | | [`Alpha`](<#alpha>) | string | `(string $extra = '')` | the string contains non-letter characters (beyond `$extra`) | | [`Digit`](<#digit>) | string | `()` | the string is empty or contains non-digit characters | | [`Xdigit`](<#xdigit>) | string | `()` | the string is empty or contains non-hexadecimal characters | | [`Slug`](<#slug>) | string | `()` | the string is not a lowercase slug (`hello-world-2`) | | [`Base64`](<#base64>) | string | `()` | the string is not valid base64 (length a multiple of 4, padding only at the end) | | [`Json`](<#json>) | string | `()` | the string is not valid JSON | | [`HexRgbColor`](<#hexrgbcolor>) | string | `()` | the string is not a hex RGB(A) color (`#fff`, `#ff0080`) | | [`Even`](<#even>) | numeric | `()` | the number is not even | | [`Odd`](<#odd>) | numeric | `()` | the number is not odd | | [`Positive`](<#positive>) | numeric | `()` | the number is not greater than zero | | [`Negative`](<#negative>) | numeric | `()` | the number is not less than zero | | [`PrimeNumber`](<#primenumber>) | numeric | `()` | the integer is not prime | | [`ContainsAny`](<#containsany>) | membership | `(string\\|int\\|float ...$values, at least one)` | an array contains none of the declared values, or a string contains none of them as a substring | Named constructor arguments work everywhere: `#[Size(min: 3)]` validates only the lower bound, `#[DateTime(timezone: 'Europe/London')]` parses in that timezone. ## String constraints One section per built-in constraint, covering every scenario of that constraint. All examples assume `use Attributes\Strictify\BaseModel;` and the constraint class imported from `Attributes\Strictify\Fields\Constraints`. ### `AlphaDash` Letters, numbers, dashes and underscores only. ```php ). ### `StartsWith` The string must start with one of the declared values; numeric values match by their string representation. ```php ) — it is the same check with the "at least one" quantifier, and reports `Must contain at least one of: ...`. ## Size ### `Size` String length in bytes or array element count, within inclusive bounds; either bound may be omitted. ```php [!TIP] > > **Type-level rules on union-typed properties** > > Declare [`Union`]() directly on the property to check the whole value against its arms — on a union hint such as `int|float` the arms must repeat the hint's type-hints exactly, otherwise an `InvalidBaseModelException` is thrown. ## Format and network constraints ### `Email` A valid email address, optionally restricted to a domain or a list of domains. Constructor: `(?string|array $domain = null)`. ```php ). Passes: `andre@example.com`, `a.b+tag@sub.domain.co`. Fails: `not-an-email`, `missing@tld`, `@example.com`, `a b@example.com`, and — with `$domain` declared — `andre@gmail.com` (`Must be an email address on an allowed domain: 'example.com'`) or `andre@mail.example.com`. ### `Url` An absolute URL with a scheme, optionally restricted to a protocol and a host. Constructor: `(?string|array $protocol = null, ?string|array $domain = null)`. ```php null]` and `[]`. A non-null value is checked as usual. - **The empty string** is accepted by `Alnum`, `Alpha`, `Ascii` and `Base64`, and rejected by `Digit`, `Xdigit`, `Slug` and `HexRgbColor`. Length-based rules reject it through their bound (`Size(min: 1)`). ## Error messages Each constraint has a default message following the `Must be ...` pattern, with the constraint parameters rendered in place of `{expected}`: ```php ['Must be between 18 and 99']] // ['username' => ["Must match the pattern '/^[a-z][a-z0-9-]*$/'"]] // ['size' => ['Must have a size of at least 3'] // ['tag' => ["Must be one of: 'a', 'b', true"]] ``` A constraint error of one property can be overridden with `#[ErrorMessage]` under its catalog key — e.g. `#[ErrorMessage(min: 'At least {expected}')]` — see [per-property overrides](). Constraints applied through userland classes can return any message they want (see below). Every default message has a stable translation key (`between`, `min`, `regex`, ...) — see the [error catalog]() and [translating error messages](). Userland `message()` output is used verbatim and is not passed through the translator; translate inside `message()` yourself. ## Custom constraints Write a constraint in PHP userland by implementing `Attributes\Strictify\Fields\Constraint`. Any attribute class implementing it is applied during `validate()` exactly like the built-ins — the same run order, error collection and `stopFirstError` handling. PHP enforces the interface methods and their signatures at class declaration time. ```php 3], new Product()); // ValidationException: ['quantity' => ['Must be an even number']] ``` The contract: - `validate(mixed $value): bool` receives the value after the native type check and returns whether it satisfies the constraint. - `message(): string` is called only on failure and returns the error message. It supports the `{field}` and `{value}` placeholders, substituted the same way as in built-in templates. - Constructor arguments are passed through unchanged, named arguments included: `#[LessThan(bound: 10)]` reaches the constructor as a named parameter. - Exceptions thrown inside `validate()` or `message()` propagate to the caller of `validate()`, like model hook errors. The built-in constraint classes are final: custom constraints implement the `Constraint` interface rather than extending a built-in. Unlike the built-ins, userland constraints may declare `Attribute::IS_REPEATABLE` and be declared multiple times on one property. Instances are compiled once per property and reused for every `validate()` call of the request. Attribute classes that do not exist or do not implement `Constraint` are ignored, exactly like any other attribute the validation engine does not know — a property can carry unrelated documentation attributes without affecting validation. # Exceptions ## At a glance | Exception | Extends | Raised when | | --- | --- | --- | | `ValidationException` | `\Exception` | a field fails validation: missing key, wrong type, failing constraint, `Sequence`/`Dict` shape errors, unknown keys under `extra: 'forbid'`. Carries `getErrors()` | | `InvalidBaseModelException` | `\Error` | the model declaration is malformed: any attribute argument the declaration rejects — a wrong argument type (`#[Union(1.5)]`), an unresolvable class arm, an unsupported `Type` value, a `Dict` key type outside the permitted ones, empty `Sequence`/`Dict` arguments, an invalid `Sequence(sorted:)`, a timezone or `Ip`/`DateTime` argument, a constraint argument that is unsatisfiable (inverted/`NAN` bounds, empty lists, a pattern that does not compile) — plus `Union` on an `array` property or with arms that differ from its hint, `Sequence`/`Dict`/`Intersection` on a non-array-like property, an empty `#[Alias]`, two properties resolving to the same key, and a `#[ModelConfigs]` option with an unknown value or the wrong type | | `MaxDepthException` | `\Error` | the payload nests models deeper than the limit (512 by default, or `$maxDepth`) | | `CallException` | `\ArgumentCountError` | `call()` cannot build the argument list: a required parameter has no dependency (`No value provided for parameter $x of f().`) | | `StrictifyThrowable` | `\Throwable` | an interface, not a class: the four above implement it, so one catch covers every extension error | | `ValueError` | `\ValueError` | a call argument is unusable (`$maxDepth` below 1), or a constraint constructor called directly in userland rejects an argument as a value | | `TypeError` | `\TypeError` | `call()` receives a `$dependencies` value that is neither `array` nor `ArrayAccess`, registering a non-callable translator, an `ErrorTranslator` callable that returns something other than `?string`, a non-string `#[ErrorMessage]` value, or an attribute object constructed directly in userland with a wrong argument type | | `Error` | `\Error` | an unknown named argument in `#[ModelConfigs]` (`#[ModelConfigs(bogus: 1)]` → `Unknown named parameter $bogus`), or an `Error` thrown inside the callable or a dependency container, which propagates as-is. Neither is a `StrictifyThrowable`, so `catch (StrictifyThrowable $e)` misses them | `catch (StrictifyThrowable $e)` covers every error the extension raises on purpose: malformed models (`InvalidBaseModelException`, including the argument errors the attribute constructors raise, rewritten when the attribute is read from a declaration), failed validation, an exceeded nesting limit and an unbuildable `call()` argument list. `TypeError` remains for bad call arguments, a non-string `#[ErrorMessage]` value, an `ErrorTranslator` return value and plain `new Email(...)` construction in userland; `ValueError` for a `$maxDepth` below 1 and unusable constraint arguments in userland; `Error` covers an unknown named argument in `#[ModelConfigs]` and anything user code throws. The four classes split like PHP's own: a failed validation extends `\Exception` (a data error, like `JsonException`), while a malformed model, an exceeded nesting limit and an unbuildable argument list extend the `\Error` family (programming errors, like `TypeError`). `catch (\Exception $e)` therefore no longer swallows a malformed model. ## ValidationException `Attributes\Strictify\Exceptions\ValidationException` is thrown by [validate()]() and [call()]() when any field fails validation. Call `getErrors()` for the error list: ```php getErrors(); // [ // 'name' => ['Field is required'], // 'address.street' => ['Must be string'], // ] } ``` `getErrors()` returns an array keyed by field path, each value holding one or more messages. Nested structures report dot-notation paths, including array element keys: ```php ['Must be string'], 'scores.5' => ['Must be integer']] ``` Field paths use the resolved field names — the [alias]() when one is declared. ## InvalidBaseModelException `Attributes\Strictify\Exceptions\InvalidBaseModelException` extends `\Error` and is thrown when a model declares an attribute on an invalid property type, or when two properties claim the same input key — a malformed model definition, not a data error: - `Union` declared directly on an `array` property, or receiving an array value on `mixed`/untyped (use `Sequence(of: new Union(...))` / `Dict(of: ...)` instead), - `Union` declared directly on a union-typed property whose arms do not repeat the hint's type-hints exactly, - `Sequence`/`Dict`/`Intersection` declared on a property that is not array-like (not `array`, a union containing `array`, `mixed` or untyped), - an empty `#[Alias('')]` on a property, - two properties resolving to the same input key — `#[Alias('id')]` on `$a` and `$b`, or `aliasGenerator: 'snake'` mapping `$aB` and `$a_b` to `a_b`. The message names both properties and the key, - a `#[ModelConfigs]` option that cannot be used — an unknown `aliasGenerator` or `extra` value (the message lists the valid ones), a non-boolean for a `bool` option (`strict: 1`, `strToLower: 'yes'`), a non-string for a `?string` option, or a string longer than the accepted length. Attribute arguments bypass the engine's parameter checks, so these are model-definition errors rather than argument errors, - an attribute argument with the wrong type — `#[Min('fifteen')]`, `#[Union(1.5)]`, `#[Alias(123)]`, - an array type-hint spec that cannot be built — an unresolvable class-name arm in `Union`/`Intersection`/`Dict`, an unsupported `Type` value, a `Dict` key type outside the permitted ones, empty `Sequence`/`Dict` arguments, a `Sequence(sorted:)` value outside `'asc'`/`'desc'`/`null`, - a constraint argument that makes the constraint unsatisfiable or a no-op — an inverted or `NAN` bound, a negative `Size` bound, an empty `In`/`StartsWith`/`EndsWith` list, an empty prefix or suffix, an empty `Email`/`Url` restriction, an invalid `DateTime` timezone, an `Ip` `version` outside `'v4'`/`'v6'`, and a `Regex` pattern that does not compile (see [malformed constraint arguments]()). The same constraint constructors called directly from userland keep the engine's `TypeError`/`ValueError`: `new Size('x')` and `new Union('NoSuchClass')` are not model declarations. ```php 'John'], new User()); // InvalidBaseModelException: The #[Alias] name of User::$name must not be empty. ``` ## ValueError Attribute arguments declared on a model raise `InvalidBaseModelException`; a `ValueError` is left for the calls that are not model declarations: - a `$maxDepth` argument below 1, - constructing a constraint object directly in userland with an argument the constructor rejects as a value — `new Union('NoSuchClass')`, `new DateTime(timezone: 'Nope/Nope')`. The same constraint arguments in a declaration (`#[Union('NoSuchClass')]`, `#[DateTime(timezone: 'Nope/Nope')]`) raise `InvalidBaseModelException` instead. ## TypeError A `TypeError` covers the wrong-type and wrong-return cases PHP reports that way: - a non-callable `ErrorTranslator::set()` argument — `must be a valid callback, function "nope" not found or invalid function name`, - an `ErrorTranslator` callable that returns something other than `?string`, - a non-string `#[ErrorMessage]` argument (`#[ErrorMessage(min: 5)]`), reported when the template is first resolved during validation instead of when the model is compiled, - `call()` receiving a `$dependencies` value that is neither `array` nor `ArrayAccess`, - constructing an attribute object in userland with a wrong argument type — `new Size('x')`. The `ErrorTranslator` return and the non-string `#[ErrorMessage]` value surface during a run rather than while the model is compiled, so they are not rewritten into `InvalidBaseModelException`. ## MaxDepthException `Attributes\Strictify\Exceptions\MaxDepthException` extends `\Error` and is thrown when the payload nests models deeper than the limit: ```php ) and [`call()`]() take a `$maxDepth` argument to override it per run, and the message reports the limit that fired. Depth is counted per run and unwound on the way out, including when the deep run fails with a `ValidationException`, so a caught failure does not affect the next call. Only nesting counts — siblings do not — so a long list is fine while a deep chain is not. The limit turns an otherwise unbounded recursion (a self-referencing model fed a deep payload) into a catchable error instead of a stack overflow. ## CallException `Attributes\Strictify\Exceptions\CallException` extends `\ArgumentCountError` and is thrown by [`call()`]() when the argument list cannot be built — a required parameter has neither a dependency nor a model value: ```php 'John']); // CallException: No value provided for parameter $email of registerUser(). ``` Optional parameters never reach it: the engine applies their declared defaults. A `#[\SensitiveParameter]` parameter is reported positionally (`parameter 2`), so the message does not disclose its name. Exceptions thrown inside the callable or inside a dependency container propagate as-is — they are not wrapped. ## StrictifyThrowable `Attributes\Strictify\Exceptions\StrictifyThrowable` is an interface extending `\Throwable`, implemented by all four classes, so `catch (StrictifyThrowable $e)` handles every error the extension raises on purpose. It has no methods and no parent class of its own: `ValidationException` extends `\Exception`, while `InvalidBaseModelException`, `MaxDepthException` and `CallException` extend `\Error`, `\Error` and `\ArgumentCountError`. ## See also - [Error messages guide]() — `ErrorMessage`, translators and the default error catalog - [validate() reference]() # API reference > Auto-generated from `stubs/*.stub.php` by `tools/generate_api_docs.py` — do not edit by hand. Regenerate with `python tools/generate_api_docs.py`. ## `Attributes\Strictify` ### Functions | Function | Signature | | --- | --- | | `validate()` | `function validate(array $rawData, BaseModel $model, int $maxDepth = 512): BaseModel` | | `call()` | `function call(string\|callable $function, array $params, array\|\ArrayAccess $dependencies = [], int $maxDepth = 512): mixed` | ### `Attributes\Strictify\BaseModel` — abstract class - Attribute: no **Properties** | Property | Default | | --- | --- | | `protected array $errors` | — | **Methods** | Method | | --- | | `protected function beforeValidation(array $rawData, ModelConfigs $configs): array` | | `protected function afterValidation(array $rawData, ModelConfigs $configs): void` | | `public function toDict(bool $includeSensitive = false, bool $useAlias = false): array` | ### `Attributes\Strictify\ModelConfigs` — abstract class - Attribute: yes **Properties** | Property | Default | | --- | --- | | `private ?string $aliasGenerator` | `null` | | `private bool $strToLower` | `false` | | `private bool $strToUpper` | `false` | | `private bool $stripWhitespace` | `false` | | `private ?string $extra` | `null` | | `private bool $strict` | `true` | | `private bool $stopAtFirstError` | `false` | **Methods** | Method | | --- | | `public function getAliasGenerator(): ?string` | | `public function isStrToLower(): bool` | | `public function isStrToUpper(): bool` | | `public function isStripWhitespace(): bool` | | `public function getExtra(): ?string` | | `public function isStrict(): bool` | | `public function isStopAtFirstError(): bool` | ### `Attributes\Strictify\ErrorTranslator` — final class - Attribute: no **Properties** | Property | Default | | --- | --- | | `private static ?callable $translator` | `null` | **Methods** | Method | | --- | | `public static function get(): ?callable` | | `public static function set(callable $translator): void` | ### `Attributes\Strictify\Type` — enum (backed by `int`) - Attribute: no **Cases** | Case | Value | | --- | --- | | `bool` | `12` | | `int` | `16` | | `float` | `32` | | `string` | `64` | | `null` | `2` | | `sequence` | `128` | | `dict` | `268435456` | | `object` | `256` | ## `Attributes\Strictify\Exceptions` ### `Attributes\Strictify\Exceptions\StrictifyThrowable` — interface extends `\Throwable` - Attribute: no ### `Attributes\Strictify\Exceptions\ValidationException` — class extends `\Exception` implements StrictifyThrowable - Attribute: no **Methods** | Method | | --- | | `public function __construct(array $allErrors)` | | `public function getErrors(): array` | ### `Attributes\Strictify\Exceptions\InvalidBaseModelException` — class extends `\Error` implements StrictifyThrowable - Attribute: no ### `Attributes\Strictify\Exceptions\MaxDepthException` — class extends `\Error` implements StrictifyThrowable - Attribute: no ### `Attributes\Strictify\Exceptions\CallException` — class extends `\ArgumentCountError` implements StrictifyThrowable - Attribute: no ## `Attributes\Strictify\Fields` ### `Attributes\Strictify\Fields\Alias` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string $name` | — | **Methods** | Method | | --- | | `public function __construct(string $name)` | ### `Attributes\Strictify\Fields\ConfigAwareConstraint` — interface extends `Constraint` - Attribute: no **Methods** | Method | | --- | | `public function setModelConfigs(\Attributes\Strictify\ModelConfigs $configs): void` | ### `Attributes\Strictify\Fields\Constraint` — interface extends `Field` - Attribute: no **Methods** | Method | | --- | | `public function validate(mixed $value): bool` | | `public function message(): string` | ### `Attributes\Strictify\Fields\Dict` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|\Attributes\Strictify\Type\|Union $key` | — | | `public int\|string\|\Attributes\Strictify\Type\|Union\|Intersection\|Sequence\|Dict $of` | — | | `public bool $uniqueValues` | — | **Methods** | Method | | --- | | `public function __construct(int\|\Attributes\Strictify\Type\|Union $key, int\|string\|\Attributes\Strictify\Type\|Union\|Intersection\|Sequence\|Dict $of, bool $uniqueValues = false)` | ### `Attributes\Strictify\Fields\ErrorMessage` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string $required` | `'Field is required'` | | `public string $type` | `'Must be {expected}'` | | `public string $alphaDash` | `'Must only contain letters, numbers, dashes and underscores'` | | `public string $alphaDashType` | `'Must be a string containing only letters, numbers, dashes and underscores'` | | `public string $ascii` | `'Must only contain ASCII characters'` | | `public string $asciiType` | `'Must be a string containing only ASCII characters'` | | `public string $between` | `'Must be between {expected}'` | | `public string $betweenType` | `'Must be a number between {expected}'` | | `public string $contains` | `'Must contain {expected}'` | | `public string $datetime` | `'Must be a datetime in the format {expected}'` | | `public string $endsWith` | `'Must end with one of: {expected}'` | | `public string $in` | `'Must be one of: {expected}'` | | `public string $max` | `'Must be at most {expected}'` | | `public string $min` | `'Must be at least {expected}'` | | `public string $multipleOf` | `'Must be a multiple of {expected}'` | | `public string $regex` | `'Must match the pattern {expected}'` | | `public string $size` | `'Must have a size {expected}'` | | `public string $startsWith` | `'Must start with one of: {expected}'` | | `public string $ulid` | `'Must be a valid ULID'` | | `public string $uuid` | `'Must be a valid UUID'` | | `public string $email` | `'Must be a valid email address'` | | `public string $emailDomain` | `'Must be an email address on an allowed domain: {expected}'` | | `public string $url` | `'Must be a valid URL'` | | `public string $urlProtocol` | `'Must be a URL using an allowed protocol: {expected}'` | | `public string $urlDomain` | `'Must be a URL on an allowed domain: {expected}'` | | `public string $domain` | `'Must be a valid domain name'` | | `public string $ip` | `'Must be a valid IP address'` | | `public string $iban` | `'Must be a valid IBAN'` | | `public string $isbn` | `'Must be a valid ISBN'` | | `public string $creditCard` | `'Must be a valid credit card number'` | | `public string $version` | `'Must be a valid version string'` | | `public string $macAddress` | `'Must be a valid MAC address'` | | `public string $alnum` | `'Must contain only letters and numbers'` | | `public string $alpha` | `'Must contain only letters'` | | `public string $digit` | `'Must contain only digits'` | | `public string $xdigit` | `'Must contain only hexadecimal digits'` | | `public string $slug` | `'Must be a valid slug'` | | `public string $base64` | `'Must be valid base64'` | | `public string $json` | `'Must be valid JSON'` | | `public string $hexRgbColor` | `'Must be a valid hex RGB color'` | | `public string $even` | `'Must be an even number'` | | `public string $odd` | `'Must be an odd number'` | | `public string $positive` | `'Must be a positive number'` | | `public string $negative` | `'Must be a negative number'` | | `public string $primeNumber` | `'Must be a prime number'` | | `public string $containsAny` | `'Must contain at least one of: {expected}'` | | `public string $union` | `'Must be {expected}'` | | `public string $sequenceKeys` | `'Must be a sequential list (keys 0, 1, 2, ...)'` | | `public string $uniqueValues` | `'Must contain only unique values'` | ### `Attributes\Strictify\Fields\Field` — interface - Attribute: no ### `Attributes\Strictify\Fields\Intersection` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $of` | — | **Methods** | Method | | --- | | `public function __construct(string ...$of)` | ### `Attributes\Strictify\Fields\Sensitive` — readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Sequence` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|string\|\Attributes\Strictify\Type\|Sequence\|Union\|Intersection\|Dict $of` | — | | `public bool $uniqueValues` | — | | `public bool $sequential` | — | | `public ?string $sorted` | — | **Methods** | Method | | --- | | `public function __construct(int\|string\|\Attributes\Strictify\Type\|Sequence\|Union\|Intersection\|Dict $of, bool $uniqueValues = false, bool $sequential = true, ?string $sorted = null)` | ### `Attributes\Strictify\Fields\Union` — readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $of` | — | **Methods** | Method | | --- | | `public function __construct(int\|string\|\Attributes\Strictify\Type\|Sequence\|Union\|Intersection\|Dict ...$of)` | ## `Attributes\Strictify\Fields\Constraints` ### `Attributes\Strictify\Fields\Constraints\Alnum` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string $extra` | — | **Methods** | Method | | --- | | `public function __construct(string $extra = '')` | ### `Attributes\Strictify\Fields\Constraints\Alpha` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string $extra` | — | **Methods** | Method | | --- | | `public function __construct(string $extra = '')` | ### `Attributes\Strictify\Fields\Constraints\AlphaDash` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Ascii` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Base64` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Between` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|float $min` | — | | `public int\|float $max` | — | **Methods** | Method | | --- | | `public function __construct(int\|float $min, int\|float $max)` | ### `Attributes\Strictify\Fields\Constraints\Contains` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $values` | — | **Methods** | Method | | --- | | `public function __construct(string\|int\|float ...$values)` | ### `Attributes\Strictify\Fields\Constraints\ContainsAny` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $values` | — | **Methods** | Method | | --- | | `public function __construct(string\|int\|float ...$values)` | ### `Attributes\Strictify\Fields\Constraints\CreditCard` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\DateTime` — final class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public readonly string $format` | — | | `public readonly \DateTimeZone\|string\|null $timezone` | — | | `private \DateTimeZone\|string\|null $timezone_obj` | — | **Methods** | Method | | --- | | `public function __construct(string $format = 'X-m-d\\TH:i:sP', \DateTimeZone\|string\|null $timezone = null)` | ### `Attributes\Strictify\Fields\Constraints\Digit` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Domain` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Email` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string\|array\|null $domain` | — | **Methods** | Method | | --- | | `public function __construct(string\|array\|null $domain = null)` | ### `Attributes\Strictify\Fields\Constraints\EndsWith` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $values` | — | **Methods** | Method | | --- | | `public function __construct(string\|int\|float ...$values)` | ### `Attributes\Strictify\Fields\Constraints\Even` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\HexRgbColor` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Iban` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\In` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $values` | — | **Methods** | Method | | --- | | `public function __construct(string\|int\|float\|bool ...$values)` | ### `Attributes\Strictify\Fields\Constraints\Ip` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public ?string $version` | — | **Methods** | Method | | --- | | `public function __construct(?string $version = null)` | ### `Attributes\Strictify\Fields\Constraints\Isbn` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Json` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\MacAddress` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Max` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|float $value` | — | **Methods** | Method | | --- | | `public function __construct(int\|float $value)` | ### `Attributes\Strictify\Fields\Constraints\Min` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|float $value` | — | **Methods** | Method | | --- | | `public function __construct(int\|float $value)` | ### `Attributes\Strictify\Fields\Constraints\MultipleOf` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public int\|float $value` | — | **Methods** | Method | | --- | | `public function __construct(int\|float $value)` | ### `Attributes\Strictify\Fields\Constraints\Negative` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Odd` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Positive` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\PrimeNumber` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Regex` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string $regex` | — | **Methods** | Method | | --- | | `public function __construct(string $regex)` | ### `Attributes\Strictify\Fields\Constraints\Size` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public ?int $min` | — | | `public ?int $max` | — | **Methods** | Method | | --- | | `public function __construct(?int $min = null, ?int $max = null)` | ### `Attributes\Strictify\Fields\Constraints\Slug` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\StartsWith` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public array $values` | — | **Methods** | Method | | --- | | `public function __construct(string\|int\|float ...$values)` | ### `Attributes\Strictify\Fields\Constraints\Ulid` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Url` — final readonly class implements Field - Attribute: yes **Properties** | Property | Default | | --- | --- | | `public string\|array\|null $protocol` | — | | `public string\|array\|null $domain` | — | **Methods** | Method | | --- | | `public function __construct(string\|array\|null $protocol = null, string\|array\|null $domain = null)` | ### `Attributes\Strictify\Fields\Constraints\Uuid` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Version` — final readonly class implements Field - Attribute: yes ### `Attributes\Strictify\Fields\Constraints\Xdigit` — final readonly class implements Field - Attribute: yes # Resources # Benchmarks Strictify ships as a pure-PHP library and as a C extension with the same API; both flavors are measured below. The extension validates in C, so its per-call cost is close to the engine's own type checks. This page documents the benchmark suite and how Strictify compares against the popular pure-PHP validation libraries. ## Running the benchmarks The suite uses [PHPBench]() and lives in `tests/Benchmark`: ```bash composer install task build # phpize && ./configure --enable-attributes-strictify && make task bench # phpbench run — the strictify scenarios ``` Each scenario validates the same input arrays defined once in `tests/Benchmark/Scenarios.php`, so every implementation validates identical data. Validators/rules are built once per benchmark class, so subjects measure steady-state per-call cost, not one-off compilation. The cross-framework comparison benches live in `tests/Benchmark/Frameworks` (Symfony Validator, Respect/Validation, Laravel's validator) and run with: ```bash vendor/bin/phpbench run --group=frameworks ``` ## Measured comparison Environment: PHP 8.4.24 (NTS, no opcache/xdebug), single pinned core, min of 30x200 interleaved repetitions per subject. Strictify (ext) = the extension built from `main`; strictify (pure PHP) = [attributes-php/strictify]() `dev-main`, measured in a separate process (it redeclares the same API, so it cannot be autoloaded alongside the extension). Framework columns are ordered fastest-first by geomean. Framework versions are the latest stable releases at measurement time: **symfony/validator 8.1.11**, **illuminate/validation 13.43.0** (Laravel), **respect/validation 2.5.0** (3.x requires PHP \>= 8.5). Times are per validation call. | Scenario | Strictify (ext) | strictify (pure PHP) | respect/validation 2.5.0 | symfony/validator 8.1.11 | illuminate/validation 13.43.0 | Strictify vs slowest | | --- | ---: | ---: | ---: | ---: | ---: | ---: | | SimpleModel (5 scalar fields) | 107ns | 2.01µs | 935ns | 10.62µs | 23.51µs | 221x | | LooseModel (stringly scalars) | 106ns | 3.12µs | 936ns | 10.75µs | 23.83µs | 225x | | ConstrainedModel (15 constraints) | 1.08µs | 11.99µs | 6.79µs | 37.32µs | 195.44µs | 181x | | ConstrainedModelFailing (1 violation) | 1.65µs | 14.73µs | 891ns | 39.68µs | 209.73µs | 127x | | NestedModel (10 nested models) | 117ns | 15.15µs | 4.57µs | 56.59µs | 169.82µs | 1455x | | 32FieldModel | 449ns | 9.19µs | 8.98µs | 58.16µs | 123.90µs | 276x | | NestedSequences (20x50 int matrix) | 3.17µs | 156.45µs | 71.70µs | 1320µs | 6401µs | 2019x | | DictOfSequences (20 keyed lists) | 3.09µs | 155.41µs | 72.33µs | 1310µs | 6467µs | 2093x | | UnionExactScalars (100 int/string/bool) | 101ns | 208ns | 8.25µs | 148.36µs | 630µs | 6231x | | NineDistinctModels | 645ns | 12.56µs | 5.76µs | 69.31µs | 177.84µs | 276x | Against the pure-PHP strictify library, the extension is on average **\~12x faster** (geomean over these scenarios measured in one session; up to **96x** on nested payloads). Against the **fastest** framework per scenario (usually Respect/Validation), Strictify is on average **\~12x faster** (geomean; 6x–82x per scenario). Against the second-fastest (Symfony Validator) it is on average **\~165x faster** (24x–1467x). The gap grows with payload size — nested lists and unions — because the pure-PHP frameworks pay per-element interpreter overhead while Strictify walks the hash table in C. One exception: on the *failing* constrained case Respect's `validate()` is \~2x faster than Strictify, because it just returns `false` while Strictify builds the error collection and renders message templates. ## Caveats - Rules are mapped per framework idiom, not rule-for-rule identical: Symfony never coerces (the "loose" scenario uses union types there), while Laravel/Respect accept numeric strings natively; Laravel has no built-in union rule, so the union scenario uses a closure rule there. - Absolute numbers vary with hardware and PHP version; the *ratios* are the stable signal. Re-run locally with the commands above to reproduce. - Versions drift: newer framework majors measured slightly *slower* than the previous ones (symfony 7.4 / laravel 12.73 were \~5–10% faster than 8.1.11 / 13.43.0 in these scenarios). # FAQ ## Which package should I use: the library or the extension? They expose the same `Attributes\Strictify` API and behave identically, so the choice is about your environment. [`attributes-php/strictify`]() is the pure-PHP library (`composer require attributes-php/strictify`) — the widest-compatibility option, it runs anywhere Composer runs, including hosts where PHP extensions cannot be installed. [`attributes-php/strictify-ext`]() is the C extension (`pie install attributes-php/strictify-ext`) — for those who control the host and can install a PHP extension; it is on average \~12x faster, up to \~96x on nested payloads (see [Benchmarks]()). Your model code does not change between them. ## Why is my numeric string rejected? Validation is **strict by default**: a value must already have the declared type, so `validate(['age' => '30'], ...)` on an `int $age` property fails with `Must be integer`. Declare `#[ModelConfigs(strict: false)]` on the model to enable loose-mode coercion. See [Strict and loose mode](). ## I get "Extra inputs are not permitted" — what does that mean? Your input contains a key that resolves to no property of the model. Control this with the `extra` option of [`#[ModelConfigs]`](): `'ignore'` (default) silently drops unknown keys, `'allow'` stores them as dynamic properties, `'forbid'` reports them as errors. ## Why do error keys look like `address.street` or `users.0.email`? `ValidationException::getErrors()` keys errors by dot-notation field path, so nested models and array elements report exactly where the failure happened. Paths use the resolved field name — the [alias]() when one is declared. ## My payload uses `snake_case` but my properties are `camelCase` Use `#[ModelConfigs(aliasGenerator: 'snake')]` on the model, or `#[Alias('...')]` on individual properties. See [Aliases and aliasGenerator](). ## Does toDict() output work as input to validate() again? Yes, with `useAlias: true`: `toDict()` is keyed by raw property names by default, and by the resolved alias names with `useAlias: true`, which is what `validate()` expects. See [Serializing models](). ## Do property hooks work? Yes — on PHP 8.4+, hooked (including virtual) properties run their `get` hook when hydrated by `validate()` and when read by `toDict()`. On older versions, plain properties are used. ## Is validation slow on the second call? No. The model class is compiled once per request (field names, constraints, type arms are resolved and cached), so steady-state validation is a flat iteration over the property slots. ## Can I use Strictify without Composer/PIE? The library is a plain Composer package (`composer require attributes-php/strictify`); without Composer, clone the repository and wire up its PSR-4 autoloader manually. The extension is distributed through PIE (`pie install attributes-php/strictify-ext`); to build it from source: `phpize && ./configure --enable-attributes-strictify && make`, then load `modules/attributes_strictify.so`. See [DEVELOPMENT.md](). ## Where do I report bugs or request features? Open an issue on the GitHub repository of the flavor you use: [attributes-php/strictify]() (library) or [attributes-php/strictify-ext]() (extension). # Changelog All notable changes to Strictify are documented here, newest first. Install the pure-PHP library with `composer require attributes-php/strictify`, or the extension with `pie install attributes-php/strictify-ext`. ## Unreleased ### Added - Enum-typed properties now coerce a scalar to the matching case in both strict and loose mode: the backing value for backed enums, the case name for pure enums. The same coercion applies to enum class arms inside `Sequence`, `Dict` and `Union` specs. A value with no matching case still fails with the allowed-cases error. ```php enum Level { case Low; case High; } class Task extends BaseModel { public Level $level; } $task = validate(['level' => 'Low'], new Task()); // Level::Low, strict or loose ``` - `CallException`: a new exception class. `call()` throws it when a required parameter has no dependency. It extends `\ArgumentCountError` and implements `StrictifyThrowable`. The message is `No value provided for parameter $x of f().` It replaces the previous plain `Error`, so `catch (StrictifyThrowable $e)` now covers the whole call path. Errors thrown inside the callable or inside a dependency container still propagate unwrapped. ```php function hello(string $name): string { return "Hi $name"; } try { call('hello', []); } catch (CallException $e) { // No value provided for parameter $name of hello(). } ``` - New built-in constraints ported from Respect/Validation: `Email`, `Url`, `Domain`, `Ip` (optional `v4`/`v6`), `Iban`, `Isbn`, `CreditCard` (Luhn), `Version` (semver), `MacAddress`, `Alnum`/`Alpha` (optional extra characters), `Digit`, `Xdigit`, `Slug`, `Base64`, `Json`, `HexRgbColor`, `Even`, `Odd`, `Positive`, `Negative`, `PrimeNumber`, `ContainsAny`. Each has its own default message and translation key. ```php #[Email] public string $email; #[Ip(version: 'v4')] public string $ip; #[ContainsAny('admin', 'owner')] public array $roles; ``` - `#[Url(...)]` gains `$protocol` and `$domain` (`string|array|null`, default `null`). Both restrict the accepted URLs. Comparison is full and case-insensitive, with ports and userinfo ignored. `https:`, `https://` and `https` count as the same protocol. Rejections use two new keys: `urlProtocol` (`Must be a URL using an allowed protocol: {expected}`) and `urlDomain` (`Must be a URL on an allowed domain: {expected}`). ```php #[Url(protocol: 'https', domain: ['example.com', 'example.org'])] public string $homepage; // 'ftp://example.com' and 'https://evil.test' both fail ``` - `#[Email(...)]` gains `$domain` (`string|array|null`, default `null`). It restricts the part after the `@`, compared in full and case-insensitively. A rejection reports the new `emailDomain` key (`Must be an email address on an allowed domain: {expected}`). ```php #[Email(domain: 'example.com')] public string $email; // 'a@other.test' fails ``` - `#[Sequence(sorted: ...)]` gains `$sorted`. `'asc'`/`'ASC'` or `'desc'`/`'DESC'` sorts the validated values and renumbers the keys `0, 1, 2, ...`. The default `null` keeps the input order. It replaces the `Sorted` constraint, which is dropped. ```php #[Sequence(of: T_INT, sorted: 'asc')] public array $scores; // [3, 1, 2] -> [0 => 1, 1 => 2, 2 => 3] ``` - `#[Sequence(...)]` and `#[Dict(...)]` now enforce `$uniqueValues` (default `false`). With `uniqueValues: true`, a repeated element is rejected on the array property with the new `uniqueValues` key (`Must contain only unique values`). `Dict::__construct()` takes the flag as its third argument. ```php #[Sequence(of: T_STRING, uniqueValues: true)] public array $tags; // ['a', 'b'] passes, ['a', 'a'] fails ``` - New `Type::null` case and `T_NULL` constant (`MAY_BE_NULL`). It works as a `Union` arm, and is required when a nullable hint declares `#[Union(...)]`. It also works as a `Dict` key spec. - `Dict` key specs now accept every PHP-castable key type: integer, string, float, boolean, null. Per [language.types.array]() the engine casts float and bool keys to int and null to `""`. Those arms therefore match the post-cast key. ```php #[Dict(key: T_INT | T_STRING | T_NULL, of: T_STRING)] public array $meta; // [2.0 => 'a'] becomes key 2, [null => 'a'] becomes key "" ``` - `BaseModel::toDict()` gains a `$useAlias` parameter: `toDict(bool $includeSensitive = false, bool $useAlias = false): array`. Output is keyed by the raw property names by default. Pass `useAlias: true` to key it by the resolved field names (`#[Alias]` and `aliasGenerator`, each nested model using its own generator). That output round-trips through `validate()`. ```php $user->toDict(); // ['name' => 'John'] $user->toDict(useAlias: true); // ['user_name' => 'John'] ``` - `#[ErrorMessage]` accepts every key of the default error catalog as a named argument: `required`, `type`, `alphaDash`, `between`, `min`, `max`, `sequenceKeys`, and so on. Each defaults to that key's message, so any per-property template can be overridden, constraint errors included. The `extra` key is discarded: extra inputs have no owning property and keep the translator or default message. ```php #[ErrorMessage(required: 'Name is mandatory', min: 'At least {expected}')] public string $name; ``` - Constraint attribute arguments are validated once per field compile. An argument that makes a constraint unsatisfiable or a no-op throws an `InvalidBaseModelException` naming the attribute, the model and the property. Covered: inverted or `NAN` numeric bounds, a negative or inverted `Size` range, an empty `In`/`StartsWith`/`EndsWith` list, an empty prefix or suffix, an empty `Email`/`Url` domain or protocol restriction, and a `Regex` pattern that does not compile (previously a PHP warning on every call). ```php #[Between(10, 5)] public int $age; // InvalidBaseModelException: inverted bounds ``` - Two alias mistakes now throw `InvalidBaseModelException`: an empty `#[Alias('')]`, and two properties resolving to the same input key. The second covers `#[Alias('id')]` on two properties, or a generator collapsing `$aB` and `$a_b` onto `a_b`. Each used to produce a field that could never be satisfied, or two fields that silently shadowed each other. ```php #[Alias('id')] public int $a; #[Alias('id')] public int $b; // InvalidBaseModelException ``` - New nesting depth guard. A payload nesting models more than 512 levels deep throws a catchable `MaxDepthException` (a new `\Error` subclass) instead of exhausting the C stack. Siblings do not add depth. The counter unwinds on every exit path, including a failing deep run. - `validate()` and `call()` accept an `int $maxDepth` argument (default `512`) to override the nesting limit for one run. Raise it for legitimately deep payloads, or lower it to reject deep nesting earlier. A value below 1 throws a `ValueError`. The exception message reports the limit that fired. ```php validate($payload, new Tree(), maxDepth: 32); ``` ### Changed - **BC note:** the minimum PHP version is now 8.3. PHP 8.2 reached end of life on December 31, 2026, so `composer.json` requires `"php": "^8.3"` and the build checks in `config.m4` and `config.w32` reject older versions. Development dependencies were upgraded to the latest releases supporting PHP 8.3: `pestphp/pest` 4.7.8 (PHPUnit 12.5.33), `illuminate/validation` and `illuminate/translation` 13.44.1, `carthage-software/mago` 1.61.0, `phpbench/phpbench` 1.7.1 and the symfony 7.4.x patches. ```json "require": { "php": "^8.3" } ``` - **BC note:** the exception hierarchy now follows PHP's split between data and programming errors. `ValidationException` extends `\Exception`. `InvalidBaseModelException` and `MaxDepthException` extend `\Error`. `CallException` extends `\ArgumentCountError`. `BaseException` is removed. `Attributes\Strictify\Exceptions\StrictifyThrowable` is the new marker interface all four implement, so `catch (StrictifyThrowable $e)` replaces `catch (BaseException $e)`. A `catch (\Exception $e)` no longer swallows a malformed model. ```php use Attributes\Strictify\Exceptions\StrictifyThrowable; try { validate($payload, new User()); } catch (StrictifyThrowable $e) { // ValidationException, InvalidBaseModelException, MaxDepthException or CallException } ``` - **BC note:** two run-time errors move from `ValueError` to `TypeError`, where PHP reports a wrong type or a wrong return value: an `ErrorTranslator` callable that returns something other than `?string`, and a non-string `#[ErrorMessage]` argument. `ErrorTranslator::set()` now uses the engine's wording for a non-callable argument. ```php ErrorTranslator::set('nope'); // TypeError: Attributes\Strictify\ErrorTranslator::set(): Argument #1 ($translator) // must be a valid callback, function "nope" not found or invalid function name ``` - The build declares `ext/date` as a dependency in `config.m4` and `config.w32`. The extension no longer checks for it at startup. - **BC note:** error catalog keys are camelCase everywhere: the `#[ErrorMessage]` arguments and properties, and the key handed to `ErrorTranslator::set()` (`alphaDash`, `sequenceKeys`, `urlProtocol`, `uniqueValues`, ...). A translator registered under a snake\_case key (`'sequence_keys'`) no longer matches. ```php ErrorTranslator::set(fn (?string $key, string $message): ?string => $key === 'sequenceKeys' ? 'Bad order' : null); ``` - **BC note:** a malformed model declaration now always throws `InvalidBaseModelException`, never a `ValueError` or `TypeError`. Covered: arguments rejected by a constructor signature (`#[Union(1.5)]`, `#[Min('fifteen')]`), unresolvable class arms, unsupported `Type` values, unsupported `Dict` key types, empty `Sequence`/`Dict` arguments, an invalid `Sequence(sorted:)`, a `DateTime` timezone argument, and the constraint argument rules above. Messages are unchanged; the rule just moved onto the extension's exception hierarchy, so `catch (StrictifyThrowable $e)` covers every malformed model. `ValueError` and `TypeError` remain for call arguments (`$maxDepth` below 1, the translator, `call()` dependencies) and for constructing an attribute object directly in userland. ```php #[Min('fifteen')] public int $age; // InvalidBaseModelException, not TypeError ``` - **BC note:** the `Attributes\Strictify` type constants are renamed with a `T_` prefix, so they no longer collide with PHP's reserved type-hint keywords: `T_BOOL`, `T_INT`, `T_FLOAT`, `T_STRING`, `T_SEQUENCE`, `T_DICT`, `T_OBJECT` (previously `bool`, `int`, `float`, `string`, `sequence`, `dict`, `object`). Update `use const` imports and attribute arguments. ```php #[Union(T_INT, T_STRING)] // was #[Union(int, string)] ``` - **BC note:** the `ErrorTranslator::set()` translator is now called as `fn (?string $key, string $message): ?string`. The first parameter is the stable key, `null` for custom `#[ErrorMessage]` values (whose text arrives as `$message`). The second is the default message template. Declare the first parameter nullable. - **BC note:** `#[Union(...)]` on a union-typed property (e.g. `int|float`) must now repeat the native hint's type-hints exactly. A subset or an extra arm throws `InvalidBaseModelException` instead of narrowing or widening the accepted values. A nullable hint counts `null` as a type-hint, so a `?string` property with `#[Union(...)]` must include `T_NULL`. ```php #[Union(T_STRING, T_NULL)] public ?string $name; // ok #[Union(T_STRING)] public ?string $name; // InvalidBaseModelException ``` - **BC note:** the default error-message translator moved off `ModelConfigs` onto the new final class `Attributes\Strictify\ErrorTranslator`: `ErrorTranslator::set(callable $translator): void` and `ErrorTranslator::get(): ?callable`. `ModelConfigs::setDefaultErrorMessages()`, `ModelConfigs::getDefaultErrorMessages()` and the static `$defaultErrorMessages` property were removed. - **BC note:** plain `toDict()` on models that use `#[Alias]` or `aliasGenerator` now returns property-name keys, not alias keys. Pass `useAlias: true` for the previous behavior. ```php $user->toDict(); // ['name' => 'John'] $user->toDict(useAlias: true); // ['user_name' => 'John'] ``` - **BC note:** `#[ModelConfigs]` is now inherited **only via the class hierarchy** (parent classes). A nested model no longer inherits the enclosing model's configs: `aliasGenerator`, `strict`, `extra`, the string normalizations and `stopAtFirstError` each resolve per model class. This changes the expected input keys of nested models, and their keys in `toDict(useAlias: true)` output. ```php #[ModelConfigs(aliasGenerator: 'snake')] class Order extends BaseModel { public Customer $customer; // Customer keeps raw names unless it declares its own generator } ``` - **BC note:** `#[Sequence]` arrays now require **integer keys**. A string key reports `Must be integer` under that key's path. They are also **sequential by default**: keys must run `0, 1, 2, ...` in order, otherwise a `sequenceKeys` error is reported. Pass `sequential: false` to allow any integer keys, gaps included. String keys stay rejected. ```php #[Sequence(of: T_STRING)] public array $tags; // ['a', 'b'] ok // [1 => 'b', 0 => 'a'] sequenceKeys error // ['x' => 'a'] Must be integer #[Sequence(of: T_STRING, sequential: false)] public array $sparse; // [1 => 'b', 5 => 'a'] ok ``` - `ModelConfigs` option values are type-checked instead of cast. A `bool` option accepts only `true`/`false`; a `?string` option accepts only a string (at most 127 chars) or `null`. So `strict: 1` or `strToLower: 'yes'` throws `InvalidBaseModelException` instead of flipping a flag. ```php #[ModelConfigs(strict: 1)] // InvalidBaseModelException ``` - `#[Sequence(sorted: ...)]` rejects a value outside `'asc'`/`'desc'`/`null` (case-insensitive) with an `InvalidBaseModelException`, instead of silently leaving the array unsorted. ```php #[Sequence(of: T_INT, sorted: 'up')] // InvalidBaseModelException ``` - `#[Sequence]`/`#[Dict]`/`#[Intersection]` on a non-array-like property now throws `InvalidBaseModelException`. That covers `string`, `int` and `object` hints, and an intersection type without `array`. Previously the rule missed those hints and the attribute was ignored. ```php #[Sequence(of: T_INT)] public string $ids; // InvalidBaseModelException ``` - Validator fixes: - `MultipleOf(0.0)` accepts `0.0`, not only the integer `0`. - `DateTime` rejects a date that does not exist (`1994-02-30`, `2023-02-29`) instead of accepting the rolled-over date. - `Iban` accepts either letter case. - `Ulid` requires a first character in `0`-`7` (the 128-bit range). - `Email` requires a top-level domain of at least two characters, like `Domain`. - A `Regex` pattern containing a NUL byte is stored and matched in full. - Constraints are skipped for an explicit `null`, exactly like a missing key. ```php #[Regex('/^\w+$/')] public ?string $name = null; validate(['name' => null], new User()); // passes ``` - Error messages render floats at full round-trip precision (`0.30000000000000004`, not `0.3`). - `call()` names the parameter of an internal function in its `No value provided` messages. ## Recent history - `#[Sensitive]` properties are masked as `***` in debug output: `var_dump()`, `print_r()`, `debug_zval_dump()`, and models inside exception traces. Property access, `json_encode()`, `serialize()` etc. keep the real values. - Restored string concatenation in `CallFunctionHooksUser::afterValidation`. - `call()` respects `#[\SensitiveParameter]` on target parameters. Missing dependencies are reported positionally, and stack traces redact the argument. - New `#[Sensitive]` field attribute. `toDict()` omits it unless `includeSensitive: true`. The `{value}` error placeholder is redacted to `***`. - New `ModelConfigs::getDefaultErrorMessages()` static getter. - `ModelConfigs` `extra` now defaults to `null` and resolves per class. `'allow'` stores unknown keys as dynamic properties. - A `null` `ModelConfigs` `extra` now resolves per nested model class at validation time. See the [GitHub releases and pull requests]() for the full history.