1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Attribute; |
8
|
|
|
use Yiisoft\Validator\FormatterInterface; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\Rule; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Checks if at least {@see AtLeast::$min} of many object attributes are filled. |
15
|
|
|
*/ |
16
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY)] |
17
|
|
|
final class AtLeast extends Rule |
18
|
|
|
{ |
19
|
5 |
|
public function __construct( |
20
|
|
|
/** |
21
|
|
|
* @var string[] The list of required attributes that will be checked. |
22
|
|
|
*/ |
23
|
|
|
private array $attributes, |
24
|
|
|
/** |
25
|
|
|
* @var int The minimum required quantity of filled attributes to pass the validation. |
26
|
|
|
* Defaults to 1. |
27
|
|
|
*/ |
28
|
|
|
private int $min = 1, |
29
|
|
|
/** |
30
|
|
|
* @var string Message to display in case of error. |
31
|
|
|
*/ |
32
|
|
|
private string $message = 'The model is not valid. Must have at least "{min}" filled attributes.', |
33
|
|
|
?FormatterInterface $formatter = null, |
34
|
|
|
bool $skipOnEmpty = false, |
35
|
|
|
bool $skipOnError = false, |
36
|
|
|
$when = null |
37
|
|
|
) { |
38
|
5 |
|
parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when); |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
protected function validateValue($value, ?ValidationContext $context = null): Result |
42
|
|
|
{ |
43
|
4 |
|
$filledCount = 0; |
44
|
|
|
|
45
|
4 |
|
foreach ($this->attributes as $attribute) { |
46
|
4 |
|
if (!$this->isEmpty($value->{$attribute})) { |
47
|
3 |
|
$filledCount++; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
$result = new Result(); |
52
|
|
|
|
53
|
4 |
|
if ($filledCount < $this->min) { |
54
|
2 |
|
$message = $this->getFormattedMessage(); |
55
|
2 |
|
$result->addError($message); |
56
|
|
|
} |
57
|
|
|
|
58
|
4 |
|
return $result; |
59
|
|
|
} |
60
|
|
|
|
61
|
4 |
|
private function getFormattedMessage(): string |
62
|
|
|
{ |
63
|
4 |
|
return $this->formatMessage($this->message, ['min' => $this->min]); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
public function getOptions(): array |
67
|
|
|
{ |
68
|
2 |
|
return array_merge(parent::getOptions(), [ |
69
|
2 |
|
'attributes' => $this->attributes, |
70
|
2 |
|
'min' => $this->min, |
71
|
2 |
|
'message' => $this->getFormattedMessage(), |
72
|
|
|
]); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|