|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Validator\HasValidationErrorMessage; |
|
8
|
|
|
use Yiisoft\Validator\Rule; |
|
9
|
|
|
use Yiisoft\Validator\Result; |
|
10
|
|
|
use Yiisoft\Validator\DataSetInterface; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* AtLeastValidator checks if at least $min of many attributes are filled. |
|
14
|
|
|
*/ |
|
15
|
|
|
class AtLeast extends Rule |
|
16
|
|
|
{ |
|
17
|
|
|
use HasValidationErrorMessage; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* The minimum required quantity of filled attributes to pass the validation. |
|
21
|
|
|
* Defaults to 1. |
|
22
|
|
|
*/ |
|
23
|
|
|
private int $min = 1; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* The list of required attributes that will be checked. |
|
27
|
|
|
*/ |
|
28
|
|
|
private array $attributes; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Message to display in case of error. |
|
32
|
|
|
*/ |
|
33
|
|
|
private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.'; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param array $attributes The list of required attributes that will be checked. |
|
37
|
|
|
*/ |
|
38
|
5 |
|
public function __construct(array $attributes) |
|
39
|
|
|
{ |
|
40
|
5 |
|
$this->attributes = $attributes; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
4 |
|
protected function validateValue($value, DataSetInterface $dataSet = null): Result |
|
44
|
|
|
{ |
|
45
|
4 |
|
$filledCount = 0; |
|
46
|
|
|
|
|
47
|
4 |
|
foreach ($this->attributes as $attribute) { |
|
48
|
4 |
|
if (!$this->isEmpty($value->{$attribute})) { |
|
49
|
3 |
|
$filledCount++; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
4 |
|
$result = new Result(); |
|
54
|
|
|
|
|
55
|
4 |
|
if ($filledCount < $this->min) { |
|
56
|
2 |
|
$result->addError( |
|
57
|
2 |
|
$this->translateMessage( |
|
58
|
2 |
|
$this->message, |
|
59
|
|
|
[ |
|
60
|
2 |
|
'min' => $this->min, |
|
61
|
|
|
] |
|
62
|
|
|
) |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
4 |
|
return $result; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @param int $value The minimum required quantity of filled attributes to pass the validation. |
|
71
|
|
|
* @return self |
|
72
|
|
|
*/ |
|
73
|
1 |
|
public function min(int $value): self |
|
74
|
|
|
{ |
|
75
|
1 |
|
$new = clone $this; |
|
76
|
1 |
|
$new->min = $value; |
|
77
|
1 |
|
return $new; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
1 |
|
public function getName(): string |
|
81
|
|
|
{ |
|
82
|
1 |
|
return 'atLeast'; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
2 |
|
public function getOptions(): array |
|
86
|
|
|
{ |
|
87
|
2 |
|
return array_merge( |
|
88
|
2 |
|
['min' => $this->min], |
|
89
|
2 |
|
['message' => $this->translateMessage($this->message, ['min' => $this->min])], |
|
90
|
2 |
|
parent::getOptions() |
|
91
|
|
|
); |
|
92
|
|
|
} |
|
93
|
|
|
} |
|
94
|
|
|
|