forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNoneOf.php
More file actions
70 lines (59 loc) · 2 KB
/
Copy pathNoneOf.php
File metadata and controls
70 lines (59 loc) · 2 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?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 count;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must pass the rules',
'{{subject}} must pass the rules',
self::TEMPLATE_SOME,
)]
#[Template(
'{{subject}} must pass all the rules',
'{{subject}} must pass all the rules',
self::TEMPLATE_ALL,
)]
final readonly class NoneOf implements Validator
{
public const string TEMPLATE_ALL = '__all__';
public const string TEMPLATE_SOME = '__some__';
/** @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
{
$failedCount = 0;
$children = [];
foreach ($this->validators as $validator) {
$child = $validator->evaluate($input)->withToggledModeAndValidation();
$children[] = $child;
if ($child->hasPassed) {
continue;
}
$failedCount++;
}
return Result::of(
$failedCount === 0,
$input,
$this,
[],
count($children) === $failedCount ? self::TEMPLATE_ALL : self::TEMPLATE_SOME,
)->withChildren(...$children);
}
}