Total Complexity | 6 |
Total Lines | 63 |
Duplicated Lines | 0 % |
Coverage | 78.95% |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
15 | class AtLeast extends Rule |
||
16 | { |
||
17 | use HasValidationMessage; |
||
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 | 4 | /** |
|
36 | * @param array $attributes The list of required attributes that will be checked. |
||
37 | 4 | */ |
|
38 | public function __construct(array $attributes) |
||
39 | { |
||
40 | 4 | $this->attributes = $attributes; |
|
41 | } |
||
42 | 4 | ||
43 | protected function validateValue($value, DataSetInterface $dataSet = null): Result |
||
44 | 4 | { |
|
45 | 4 | $filledCount = 0; |
|
46 | 3 | ||
47 | foreach ($this->attributes as $attribute) { |
||
48 | if (!$this->isEmpty($value->{$attribute})) { |
||
49 | $filledCount++; |
||
50 | 4 | } |
|
51 | } |
||
52 | 4 | ||
53 | 2 | $result = new Result(); |
|
54 | 2 | ||
55 | 2 | if ($filledCount < $this->min) { |
|
56 | $result->addError( |
||
57 | 2 | $this->translateMessage( |
|
58 | $this->message, |
||
59 | [ |
||
60 | 'min' => $this->min, |
||
61 | ] |
||
62 | ) |
||
63 | 4 | ); |
|
64 | } |
||
65 | |||
66 | 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 | public function min(int $value): self |
||
78 | } |
||
79 | } |
||
80 |