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
// doctest: run
use Attributes\Strictify\BaseModel;
use Attributes\Strictify\Exceptions\ValidationException;
use function Attributes\Strictify\validate;
class Profile extends BaseModel
{
public string $name; // required (no default)
public ?string $nickname = null; // optional (has a default)
}
try {
validate([], new Profile());
} catch (ValidationException $e) {
print_r($e->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
// doctest: run
use Attributes\Strictify\BaseModel;
use Attributes\Strictify\ModelConfigs;
use function Attributes\Strictify\validate;
#[ModelConfigs(strict: false)]
class User extends BaseModel
{
public int $age;
public string $name;
}
$user = validate(['age' => '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. Bothint|boolandbool|intcoerce'1'toint(1); only values no earlier arm can take fall through tobool, so'abc'becomesbool(true). One exception: for anint|floatunion, a numeric string keeps its natural type —'1'becomesint(1),'1.5'becomesfloat(1.5).
DateTimeInterface properties coerce from date strings in both modes.
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 as1994-01-01T09:00:00+00:00.- Properties typed with a
BaseModelclass 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.
- 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
// doctest: run
use Attributes\Strictify\BaseModel;
use Attributes\Strictify\Exceptions\ValidationException;
use function Attributes\Strictify\validate;
enum Suit: string
{
case Hearts = 'hearts';
case Spades = 'spades';
}
enum Level
{
case Low;
case High;
}
class Card extends BaseModel
{
public Suit $suit; // string-backed enum
public Level $level; // pure (non-backed) enum
}
$card = validate(['suit' => '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
// doctest: run
use Attributes\Strictify\BaseModel;
use Attributes\Strictify\ModelConfigs;
use function Attributes\Strictify\validate;
class Signup extends BaseModel
{
public string $email;
protected function beforeValidation(array $rawData, ModelConfigs $configs): array
{
// normalize input before validation, e.g. lowercase the email
if (isset($rawData['email']) && is_string($rawData['email'])) {
$rawData['email'] = strtolower($rawData['email']);
}
return $rawData;
}
protected function afterValidation(array $rawData, ModelConfigs $configs): void
{
// runs after a successful validation, e.g. audit logging
}
}
$user = validate(['email' => '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.