/
AtLeast.php
91 lines (76 loc) · 2.16 KB
/
AtLeast.php
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
namespace Yiisoft\Validator\Rule;
use Yiisoft\Validator\HasValidationErrorMessage;
use Yiisoft\Validator\Result;
use Yiisoft\Validator\Rule;
use Yiisoft\Validator\ValidationContext;
/**
* AtLeastValidator checks if at least $min of many attributes are filled.
*/
final class AtLeast extends Rule
{
use HasValidationErrorMessage;
/**
* The minimum required quantity of filled attributes to pass the validation.
* Defaults to 1.
*/
private int $min = 1;
/**
* The list of required attributes that will be checked.
*/
private array $attributes;
/**
* Message to display in case of error.
*/
private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.';
/**
* @param array $attributes The list of required attributes that will be checked.
*/
public static function rule(array $attributes): self
{
$rule = new self();
$rule->attributes = $attributes;
return $rule;
}
protected function validateValue($value, ValidationContext $context = null): Result
{
$filledCount = 0;
foreach ($this->attributes as $attribute) {
if (!$this->isEmpty($value->{$attribute})) {
$filledCount++;
}
}
$result = new Result();
if ($filledCount < $this->min) {
$result->addError(
$this->formatMessage(
$this->message,
[
'min' => $this->min,
]
)
);
}
return $result;
}
/**
* @param int $value The minimum required quantity of filled attributes to pass the validation.
*
* @return self
*/
public function min(int $value): self
{
$new = clone $this;
$new->min = $value;
return $new;
}
public function getOptions(): array
{
return array_merge(
parent::getOptions(),
['min' => $this->min],
['message' => $this->formatMessage($this->message, ['min' => $this->min])],
);
}
}