PHP code example of fatjon-lleshi / antares-validation

1. Go to this page and download the library: Download fatjon-lleshi/antares-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fatjon-lleshi / antares-validation example snippets


use Antares\Validation\Attributes\Dto;
use Antares\Validation\Attributes\NotBlank;
use Antares\Validation\Attributes\Email;
use Antares\Validation\Attributes\Min;

#[Dto]
readonly class CreateUserRequest
{
    public function __construct(
        #[NotBlank]
        public string $name,

        #[NotBlank, Email]
        public string $email,

        #[Min(18)]
        public int $age,
    ) {}
}

use Antares\Hydration\Hydrator;

$hydrator = new Hydrator();

$data = json_decode((string) $request->getBody(), true);

$dto = $hydrator->hydrate(CreateUserRequest::class, $data);

use Antares\Validation\Attributes\Strict;

#[Dto, Strict]
readonly class CreateUserRequest
{
    public function __construct(
        public string $name,
        public int $age,
    ) {}
}

#[Dto]
readonly class AddressRequest
{
    public function __construct(
        #[NotBlank]
        public string $city,
        #[NotBlank]
        public string $country,
    ) {}
}

#[Dto]
readonly class CreateUserRequest
{
    public function __construct(
        #[NotBlank]
        public string $name,
        public AddressRequest $address,
    ) {}
}

use Antares\Validation\Validator;
use Antares\Validation\Exceptions\ValidationException;

$validator = new Validator();

try {
    $validator->validate($dto);
} catch (ValidationException $e) {
    $errors = $e->getErrors();
}

use Antares\Validation\Attributes\ValidationAttribute;
use Attribute;

#[Attribute(Attribute::TARGET_PARAMETER)]
final class Slug implements ValidationAttribute
{
    public function validate(mixed $value): ?string
    {
        if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', (string) $value)) {
            return 'Must be a valid slug.';
        }

        return null;
    }
}

use Antares\Hydration\Exceptions\HydrationException;
use Antares\Validation\Exceptions\ValidationException;

try {
    $dto = $hydrator->hydrate(CreateUserRequest::class, $data);
    $validator->validate($dto);
} catch (HydrationException $e) {
    // 400 Bad Request
} catch (ValidationException $e) {
    // 422 Unprocessable Entity
    $errors = $e->getErrors(); // ['email' => 'Must be a valid email address.']
}