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,DictandUnionspecs. A value with no matching case still fails with the allowed-cases error.
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\ArgumentCountErrorand implementsStrictifyThrowable. The message isNo value provided for parameter $x of f().It replaces the previous plainError, socatch (StrictifyThrowable $e)now covers the whole call path. Errors thrown inside the callable or inside a dependency container still propagate unwrapped.
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(optionalv4/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.
#[Email] public string $email;
#[Ip(version: 'v4')] public string $ip;
#[ContainsAny('admin', 'owner')] public array $roles;
#[Url(...)]gains$protocoland$domain(string|array|null, defaultnull). Both restrict the accepted URLs. Comparison is full and case-insensitive, with ports and userinfo ignored.https:,https://andhttpscount as the same protocol. Rejections use two new keys:urlProtocol(Must be a URL using an allowed protocol: {expected}) andurlDomain(Must be a URL on an allowed domain: {expected}).
#[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, defaultnull). It restricts the part after the@, compared in full and case-insensitively. A rejection reports the newemailDomainkey (Must be an email address on an allowed domain: {expected}).
#[Sequence(sorted: ...)]gains$sorted.'asc'/'ASC'or'desc'/'DESC'sorts the validated values and renumbers the keys0, 1, 2, .... The defaultnullkeeps the input order. It replaces theSortedconstraint, which is dropped.
#[Sequence(of: T_INT, sorted: 'asc')] public array $scores;
// [3, 1, 2] -> [0 => 1, 1 => 2, 2 => 3]
#[Sequence(...)]and#[Dict(...)]now enforce$uniqueValues(defaultfalse). WithuniqueValues: true, a repeated element is rejected on the array property with the newuniqueValueskey (Must contain only unique values).Dict::__construct()takes the flag as its third argument.
#[Sequence(of: T_STRING, uniqueValues: true)] public array $tags;
// ['a', 'b'] passes, ['a', 'a'] fails
- New
Type::nullcase andT_NULLconstant (MAY_BE_NULL). It works as aUnionarm, and is required when a nullable hint declares#[Union(...)]. It also works as aDictkey spec. Dictkey 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.
#[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$useAliasparameter:toDict(bool $includeSensitive = false, bool $useAlias = false): array. Output is keyed by the raw property names by default. PassuseAlias: trueto key it by the resolved field names (#[Alias]andaliasGenerator, each nested model using its own generator). That output round-trips throughvalidate().
#[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. Theextrakey is discarded: extra inputs have no owning property and keep the translator or default message.
- Constraint attribute arguments are validated once per field compile. An argument that makes a constraint unsatisfiable or a no-op throws an
InvalidBaseModelExceptionnaming the attribute, the model and the property. Covered: inverted orNANnumeric bounds, a negative or invertedSizerange, an emptyIn/StartsWith/EndsWithlist, an empty prefix or suffix, an emptyEmail/Urldomain or protocol restriction, and aRegexpattern that does not compile (previously a PHP warning on every call).
- 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$aBand$a_bontoa_b. Each used to produce a field that could never be satisfied, or two fields that silently shadowed each other.
- New nesting depth guard. A payload nesting models more than 512 levels deep throws a catchable
MaxDepthException(a new\Errorsubclass) instead of exhausting the C stack. Siblings do not add depth. The counter unwinds on every exit path, including a failing deep run. validate()andcall()accept anint $maxDepthargument (default512) 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 aValueError. The exception message reports the limit that fired.
Changed¶
- BC note: the minimum PHP version is now 8.3. PHP 8.2 reached end of life on December 31, 2026, so
composer.jsonrequires"php": "^8.3"and the build checks inconfig.m4andconfig.w32reject older versions. Development dependencies were upgraded to the latest releases supporting PHP 8.3:pestphp/pest4.7.8 (PHPUnit 12.5.33),illuminate/validationandilluminate/translation13.44.1,carthage-software/mago1.61.0,phpbench/phpbench1.7.1 and the symfony 7.4.x patches.
- BC note: the exception hierarchy now follows PHP's split between data and programming errors.
ValidationExceptionextends\Exception.InvalidBaseModelExceptionandMaxDepthExceptionextend\Error.CallExceptionextends\ArgumentCountError.BaseExceptionis removed.Attributes\Strictify\Exceptions\StrictifyThrowableis the new marker interface all four implement, socatch (StrictifyThrowable $e)replacescatch (BaseException $e). Acatch (\Exception $e)no longer swallows a malformed model.
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
ValueErrortoTypeError, where PHP reports a wrong type or a wrong return value: anErrorTranslatorcallable 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.
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/dateas a dependency inconfig.m4andconfig.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 toErrorTranslator::set()(alphaDash,sequenceKeys,urlProtocol,uniqueValues, ...). A translator registered under a snake_case key ('sequence_keys') no longer matches.
ErrorTranslator::set(fn (?string $key, string $message): ?string => $key === 'sequenceKeys' ? 'Bad order' : null);
- BC note: a malformed model declaration now always throws
InvalidBaseModelException, never aValueErrororTypeError. Covered: arguments rejected by a constructor signature (#[Union(1.5)],#[Min('fifteen')]), unresolvable class arms, unsupportedTypevalues, unsupportedDictkey types, emptySequence/Dictarguments, an invalidSequence(sorted:), aDateTimetimezone argument, and the constraint argument rules above. Messages are unchanged; the rule just moved onto the extension's exception hierarchy, socatch (StrictifyThrowable $e)covers every malformed model.ValueErrorandTypeErrorremain for call arguments ($maxDepthbelow 1, the translator,call()dependencies) and for constructing an attribute object directly in userland.
- BC note: the
Attributes\Strictifytype constants are renamed with aT_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(previouslybool,int,float,string,sequence,dict,object). Updateuse constimports and attribute arguments.
- BC note: the
ErrorTranslator::set()translator is now called asfn (?string $key, string $message): ?string. The first parameter is the stable key,nullfor 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 throwsInvalidBaseModelExceptioninstead of narrowing or widening the accepted values. A nullable hint countsnullas a type-hint, so a?stringproperty with#[Union(...)]must includeT_NULL.
#[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
ModelConfigsonto the new final classAttributes\Strictify\ErrorTranslator:ErrorTranslator::set(callable $translator): voidandErrorTranslator::get(): ?callable.ModelConfigs::setDefaultErrorMessages(),ModelConfigs::getDefaultErrorMessages()and the static$defaultErrorMessagesproperty were removed. - BC note: plain
toDict()on models that use#[Alias]oraliasGeneratornow returns property-name keys, not alias keys. PassuseAlias: truefor the previous behavior.
- 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 andstopAtFirstErroreach resolve per model class. This changes the expected input keys of nested models, and their keys intoDict(useAlias: true)output.
#[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 reportsMust be integerunder that key's path. They are also sequential by default: keys must run0, 1, 2, ...in order, otherwise asequenceKeyserror is reported. Passsequential: falseto allow any integer keys, gaps included. String keys stay rejected.
#[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
ModelConfigsoption values are type-checked instead of cast. Abooloption accepts onlytrue/false; a?stringoption accepts only a string (at most 127 chars) ornull. Sostrict: 1orstrToLower: 'yes'throwsInvalidBaseModelExceptioninstead of flipping a flag.
#[Sequence(sorted: ...)]rejects a value outside'asc'/'desc'/null(case-insensitive) with anInvalidBaseModelException, instead of silently leaving the array unsorted.
#[Sequence]/#[Dict]/#[Intersection]on a non-array-like property now throwsInvalidBaseModelException. That coversstring,intandobjecthints, and an intersection type withoutarray. Previously the rule missed those hints and the attribute was ignored.
- Validator fixes:
MultipleOf(0.0)accepts0.0, not only the integer0.DateTimerejects a date that does not exist (1994-02-30,2023-02-29) instead of accepting the rolled-over date.Ibanaccepts either letter case.Ulidrequires a first character in0-7(the 128-bit range).Emailrequires a top-level domain of at least two characters, likeDomain.- A
Regexpattern containing a NUL byte is stored and matched in full. - Constraints are skipped for an explicit
null, exactly like a missing key.
- Error messages render floats at full round-trip precision (
0.30000000000000004, not0.3). call()names the parameter of an internal function in itsNo value providedmessages.
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 unlessincludeSensitive: true. The{value}error placeholder is redacted to***. - New
ModelConfigs::getDefaultErrorMessages()static getter. ModelConfigsextranow defaults tonulland resolves per class.'allow'stores unknown keys as dynamic properties.- A
nullModelConfigsextranow resolves per nested model class at validation time.
See the GitHub releases and pull requests for the full history.