Skip to content
Antares

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.

Terminal window
composer require fatjon-lleshi/antares-validation

This package has no dependency on the Antares framework core and can be used in any PHP 8.2+ project.

  1. Mark a class with #[Dto] and add validation attributes to its constructor parameters.
  2. Pass raw data (a decoded JSON body, form fields, etc.) to $hydrator->hydrate().
  3. 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:

ProblemExceptionIn the frameworkErrors 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 sentHydrationException400 Bad RequestThe first problem found
The data fits, but breaks a validation rule (#[Email], #[MinLength], …)ValidationException422 Unprocessable EntityEvery 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.