1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Arrays\ArrayHelper; |
8
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
11
|
|
|
use Yiisoft\Validator\SkipOnEmptyCallback\SkipOnEmpty; |
12
|
|
|
use Yiisoft\Validator\ValidationContext; |
13
|
|
|
|
14
|
|
|
use function is_array; |
15
|
|
|
use function is_object; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Checks if at least {@see AtLeast::$min} of many attributes are filled. |
19
|
|
|
*/ |
20
|
|
|
final class AtLeastHandler implements RuleHandlerInterface |
21
|
|
|
{ |
22
|
15 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
23
|
|
|
{ |
24
|
15 |
|
if (!$rule instanceof AtLeast) { |
25
|
1 |
|
throw new UnexpectedRuleException(AtLeast::class, $rule); |
26
|
|
|
} |
27
|
|
|
|
28
|
14 |
|
$result = new Result(); |
29
|
|
|
|
30
|
14 |
|
if (!is_array($value) && !is_object($value)) { |
31
|
1 |
|
return $result->addError($rule->getIncorrectInputMessage(), [ |
32
|
1 |
|
'attribute' => $context->getAttribute(), |
33
|
1 |
|
'type' => get_debug_type($value), |
34
|
|
|
]); |
35
|
|
|
} |
36
|
|
|
|
37
|
13 |
|
$filledCount = 0; |
38
|
13 |
|
foreach ($rule->getAttributes() as $attribute) { |
39
|
13 |
|
if (!(new SkipOnEmpty())(ArrayHelper::getValue($value, $attribute), $context->isAttributeMissing())) { |
40
|
10 |
|
$filledCount++; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
13 |
|
if ($filledCount < $rule->getMin()) { |
45
|
5 |
|
$result->addError($rule->getMessage(), [ |
46
|
5 |
|
'attribute' => $context->getAttribute(), |
47
|
5 |
|
'min' => $rule->getMin(), |
48
|
|
|
]); |
49
|
|
|
} |
50
|
|
|
|
51
|
13 |
|
return $result; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|