1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Rule\Callback; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Rules represents multiple rules for a single value |
11
|
|
|
*/ |
12
|
|
|
final class Rules |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var RuleInterface[] |
16
|
|
|
*/ |
17
|
|
|
private array $rules = []; |
18
|
|
|
|
19
|
20 |
|
public function __construct(iterable $rules = []) |
20
|
|
|
{ |
21
|
20 |
|
foreach ($rules as $rule) { |
22
|
14 |
|
$this->add($rule); |
23
|
|
|
} |
24
|
20 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param callable|RuleInterface $rule |
28
|
|
|
*/ |
29
|
20 |
|
public function add($rule): void |
30
|
|
|
{ |
31
|
20 |
|
$this->rules[] = $this->normalizeRule($rule); |
32
|
20 |
|
} |
33
|
|
|
|
34
|
13 |
|
public function validate($value, DataSetInterface $dataSet = null, bool $previousRulesErrored = false): Result |
35
|
|
|
{ |
36
|
13 |
|
$compoundResult = new Result(); |
37
|
13 |
|
foreach ($this->rules as $rule) { |
38
|
13 |
|
$ruleResult = $rule->validate($value, $dataSet, $previousRulesErrored); |
39
|
13 |
|
if ($ruleResult->isValid() === false) { |
40
|
13 |
|
$previousRulesErrored = true; |
41
|
13 |
|
foreach ($ruleResult->getErrors() as $message) { |
42
|
13 |
|
$compoundResult->addError($message); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
} |
46
|
13 |
|
return $compoundResult; |
47
|
|
|
} |
48
|
|
|
|
49
|
20 |
|
private function normalizeRule($rule): RuleInterface |
50
|
|
|
{ |
51
|
20 |
|
if (is_callable($rule)) { |
52
|
3 |
|
$rule = new Callback($rule); |
53
|
|
|
} |
54
|
|
|
|
55
|
20 |
|
if (!$rule instanceof RuleInterface) { |
56
|
|
|
throw new \InvalidArgumentException(sprintf( |
57
|
|
|
'Rule should be either instance of %s or a callable', |
58
|
|
|
RuleInterface::class |
59
|
|
|
)); |
60
|
|
|
} |
61
|
|
|
|
62
|
20 |
|
return $rule; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Return rules as array. |
67
|
|
|
* |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
6 |
|
public function asArray(): array |
71
|
|
|
{ |
72
|
6 |
|
$arrayOfRules = []; |
73
|
6 |
|
foreach ($this->rules as $rule) { |
74
|
6 |
|
if ($rule instanceof ParametrizedRuleInterface) { |
75
|
6 |
|
$arrayOfRules[] = array_merge([$rule->getName()], $rule->getOptions()); |
76
|
|
|
} |
77
|
|
|
} |
78
|
6 |
|
return $arrayOfRules; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|