1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Attribute; |
8
|
|
|
use Closure; |
9
|
|
|
use JetBrains\PhpStorm\ArrayShape; |
10
|
|
|
use Yiisoft\Validator\BeforeValidationInterface; |
11
|
|
|
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait; |
12
|
|
|
use Yiisoft\Validator\Rule\Trait\RuleNameTrait; |
13
|
|
|
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait; |
14
|
|
|
use Yiisoft\Validator\RuleInterface; |
15
|
|
|
use Yiisoft\Validator\SerializableRuleInterface; |
16
|
|
|
use Yiisoft\Validator\SkipOnEmptyInterface; |
17
|
|
|
use Yiisoft\Validator\ValidationContext; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Allows to combine and validate multiple rules. |
21
|
|
|
*/ |
22
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
23
|
|
|
class Composite implements SerializableRuleInterface, BeforeValidationInterface, SkipOnEmptyInterface |
24
|
|
|
{ |
25
|
|
|
use BeforeValidationTrait; |
26
|
|
|
use RuleNameTrait; |
27
|
|
|
use SkipOnEmptyTrait; |
28
|
|
|
|
29
|
2 |
|
public function __construct( |
30
|
|
|
/** |
31
|
|
|
* @var iterable<RuleInterface> |
32
|
|
|
*/ |
33
|
|
|
private iterable $rules = [], |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var bool|callable|null |
37
|
|
|
*/ |
38
|
|
|
private $skipOnEmpty = null, |
39
|
|
|
private bool $skipOnError = false, |
40
|
|
|
/** |
41
|
|
|
* @var Closure(mixed, ValidationContext):bool|null |
42
|
|
|
*/ |
43
|
|
|
private ?Closure $when = null, |
44
|
|
|
) { |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
#[ArrayShape([ |
48
|
|
|
'skipOnEmpty' => 'bool', |
49
|
|
|
'skipOnError' => 'bool', |
50
|
|
|
'rules' => 'array', |
51
|
|
|
])] |
52
|
|
|
public function getOptions(): array |
53
|
|
|
{ |
54
|
1 |
|
$arrayOfRules = []; |
55
|
1 |
|
foreach ($this->getRules() as $rule) { |
56
|
1 |
|
if ($rule instanceof SerializableRuleInterface) { |
57
|
1 |
|
$arrayOfRules[] = array_merge([$rule->getName()], $rule->getOptions()); |
58
|
|
|
} else { |
59
|
|
|
$arrayOfRules[] = [$rule->getName()]; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return [ |
64
|
1 |
|
'skipOnEmpty' => $this->getSkipOnEmptyOption(), |
65
|
1 |
|
'skipOnError' => $this->skipOnError, |
66
|
|
|
'rules' => $arrayOfRules, |
67
|
|
|
]; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]> |
72
|
|
|
*/ |
73
|
3 |
|
public function getRules(): iterable |
74
|
|
|
{ |
75
|
3 |
|
return $this->rules; |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function getHandlerClassName(): string |
79
|
|
|
{ |
80
|
1 |
|
return CompositeHandler::class; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|