forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAnyOf.php
More file actions
51 lines (42 loc) · 1.6 KB
/
Copy pathAnyOf.php
File metadata and controls
51 lines (42 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-FileContributor: Fabio Ribeiro <faabiosr@gmail.com>
* SPDX-FileContributor: Graham Campbell <graham@mineuk.com>
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
* SPDX-FileContributor: Nick Lombard <github@jigsoft.co.za>
*/
declare(strict_types=1);
namespace Respect\Validation\Validators;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Validator;
use function array_map;
use function array_reduce;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must pass at least one of the rules',
'{{subject}} must pass at least one of the rules',
)]
final readonly class AnyOf implements Validator
{
/** @var non-empty-array<Validator> */
private readonly array $validators;
public function __construct(Validator $validator1, Validator $validator2, Validator ...$validators)
{
$this->validators = [$validator1, $validator2, ...$validators];
}
public function evaluate(mixed $input): Result
{
$children = array_map(static fn(Validator $validator) => $validator->evaluate($input), $this->validators);
$valid = array_reduce(
$children,
static fn(bool $carry, Result $result) => $carry || $result->hasPassed,
false,
);
return Result::of($valid, $input, $this)->withChildren(...$children);
}
}