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\SerializableRuleInterface; |
11
|
|
|
use Yiisoft\Validator\BeforeValidationInterface; |
12
|
|
|
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait; |
13
|
|
|
use Yiisoft\Validator\Rule\Trait\RuleNameTrait; |
14
|
|
|
use Yiisoft\Validator\ValidationContext; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Checks if at least {@see AtLeast::$min} of many attributes are filled. |
18
|
|
|
*/ |
19
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
20
|
|
|
final class AtLeast implements SerializableRuleInterface, BeforeValidationInterface |
21
|
|
|
{ |
22
|
|
|
use BeforeValidationTrait; |
23
|
|
|
use RuleNameTrait; |
24
|
|
|
|
25
|
4 |
|
public function __construct( |
26
|
|
|
/** |
27
|
|
|
* The list of required attributes that will be checked. |
28
|
|
|
*/ |
29
|
|
|
private array $attributes, |
30
|
|
|
/** |
31
|
|
|
* The minimum required quantity of filled attributes to pass the validation. |
32
|
|
|
* Defaults to 1. |
33
|
|
|
*/ |
34
|
|
|
private int $min = 1, |
35
|
|
|
/** |
36
|
|
|
* Message to display in case of error. |
37
|
|
|
*/ |
38
|
|
|
private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.', |
39
|
|
|
private bool $skipOnEmpty = false, |
40
|
|
|
private bool $skipOnError = false, |
41
|
|
|
/** |
42
|
|
|
* @var Closure(mixed, ValidationContext):bool|null |
43
|
|
|
*/ |
44
|
|
|
private ?Closure $when = null, |
45
|
|
|
) { |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return array |
50
|
|
|
*/ |
51
|
5 |
|
public function getAttributes(): array |
52
|
|
|
{ |
53
|
5 |
|
return $this->attributes; |
54
|
|
|
} |
55
|
|
|
|
56
|
5 |
|
public function getMin(): int |
57
|
|
|
{ |
58
|
5 |
|
return $this->min; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
3 |
|
public function getMessage(): string |
65
|
|
|
{ |
66
|
3 |
|
return $this->message; |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
#[ArrayShape([ |
70
|
|
|
'attributes' => 'array', |
71
|
|
|
'min' => 'int', |
72
|
|
|
'message' => 'array', |
73
|
|
|
'skipOnEmpty' => 'bool', |
74
|
|
|
'skipOnError' => 'bool', |
75
|
|
|
])] |
76
|
|
|
public function getOptions(): array |
77
|
|
|
{ |
78
|
|
|
return [ |
79
|
2 |
|
'attributes' => $this->attributes, |
80
|
2 |
|
'min' => $this->min, |
81
|
|
|
'message' => [ |
82
|
2 |
|
'message' => $this->message, |
83
|
2 |
|
'parameters' => ['min' => $this->min], |
84
|
|
|
], |
85
|
2 |
|
'skipOnEmpty' => $this->skipOnEmpty, |
86
|
2 |
|
'skipOnError' => $this->skipOnError, |
87
|
|
|
]; |
88
|
|
|
} |
89
|
|
|
|
90
|
2 |
|
public function getHandlerClassName(): string |
91
|
|
|
{ |
92
|
2 |
|
return AtLeastHandler::class; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|