innmind / validation
1.4.0
2024-03-24 09:51 UTC
Requires
- php: ~8.2
- innmind/immutable: ~5.3
- innmind/time-continuum: ~3.4
Requires (Dev)
- innmind/black-box: ~5.5
- innmind/coding-standard: ~2.0
- vimeo/psalm: ~5.0
README
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'] // ]