Validation Overview
antares-validation provides two things: a Hydrator that maps raw arrays to typed PHP DTOs, and a Validator that checks those DTOs against PHP attributes.
composer require fatjon-lleshi/antares-validationThis package has no dependency on the Antares framework core and can be used in any PHP 8.2+ project.
How It Works
Section titled “How It Works”- Mark a class with
#[Dto]and add validation attributes to its constructor parameters. - Pass raw data (a decoded JSON body, form fields, etc.) to
$hydrator->hydrate(). - The Hydrator maps and casts the data, builds the object, then runs the Validator on it.
Two different things can go wrong, and they are reported differently:
| Problem | Exception | In the framework | Errors reported |
|---|---|---|---|
The data doesn’t fit the DTO’s shape: a required field is missing, a value can’t be cast to its type, or (with #[Strict]) an unknown field is sent | HydrationException | 400 Bad Request | The first problem found |
The data fits, but breaks a validation rule (#[Email], #[MinLength], …) | ValidationException | 422 Unprocessable Entity | Every failed rule, per field |
use Antares\Hydration\Exceptions\HydrationException;use Antares\Hydration\Hydrator;use Antares\Validation\Exceptions\ValidationException;use Antares\Validation\Validator;
$hydrator = new Hydrator(new Validator());
try { $dto = $hydrator->hydrate(CreateUserRequest::class, $rawData);} catch (HydrationException $e) { $e->getMessage(); // "Missing required parameter: email"} catch (ValidationException $e) { $e->getErrors(); // ['email' => ['The value must be a valid email address.']]}You can also validate any object directly, without hydrating it: (new Validator())->validate($object). The Validator reads the rules from the class’s constructor parameters.
In the framework, the Dispatcher does all of this automatically for any controller parameter typed as a #[Dto] class.