innmind/validation

1.7.0 2024-11-11 12:37 UTC

This package is auto-updated.

Last update: 2024-12-11 12:55:56 UTC


README

Build Status codecov Type Coverage

This package is a monadic approach to data validation to easily compose validations rules.

Installation

composer require innmind/validation

Usage

use Innmind\Validation\{
    Shape,
    Is,
    Each,
    Failure,
};
use Innmind\Immutable\Sequence;

$valid = [
    'id' => 42,
    'username' => 'jdoe',
    'addresses' => [
        'address 1',
        'address 2',
    ],
    'submit' => true,
];
$invalid = [
    'id' => '42',
    'addresses' => [
        'address 1',
        null,
    ],
    'submit' => true,
];

$validate = Shape::of('id', Is::int())
    ->with('username', Is::string())
    ->with(
        'addresses',
        Is::list(
            Is::string()->map(
                static fn(string $address) => new YourModel($address),
            )
        )
    );
$result = $validate($valid)->match(
    static fn(array $value) => $value,
    static fn() => throw new \RuntimeException('invalid data'),
);
// Here $result looks like:
// [
//      'id' => 42
//      'username' => 'jdoe',
//      'addresses' [
//          new YourModel('address 1'),
//          new YourModel('address 2'),
//      ],
// ]
$errors = $validate($invalid)->match(
    static fn() => null,
    static fn(Sequence $failures) => $failures
        ->map(static fn(Failure $failure) => [
            $failure->path()->toString(),
            $failure->message(),
        ])
        ->toList(),
);
// Here $errors looks like:
// [
//      ['id', 'Value is not of type int'],
//      ['$', 'The key username is mission'],
//      ['addresses', 'Value is not of type string']
// ]