|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Traversable; |
|
8
|
|
|
use Yiisoft\Arrays\ArrayHelper; |
|
9
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
|
10
|
|
|
use Yiisoft\Validator\Result; |
|
11
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
|
12
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
13
|
|
|
|
|
14
|
|
|
final class SubsetHandler implements RuleHandlerInterface |
|
15
|
|
|
{ |
|
16
|
10 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
|
17
|
|
|
{ |
|
18
|
10 |
|
if (!$rule instanceof Subset) { |
|
19
|
1 |
|
throw new UnexpectedRuleException(Subset::class, $rule); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
9 |
|
$result = new Result(); |
|
23
|
9 |
|
if (!is_iterable($value)) { |
|
24
|
|
|
return $result->addError($rule->getIterableMessage(), [ |
|
25
|
|
|
'attribute' => $context->getAttribute(), |
|
26
|
|
|
'type' => get_debug_type($value), |
|
27
|
|
|
]); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
9 |
|
if (!ArrayHelper::isSubset($value, $rule->getValues(), $rule->isStrict())) { |
|
31
|
3 |
|
$values = $rule->getValues(); |
|
32
|
3 |
|
if ($values instanceof Traversable) { |
|
33
|
|
|
$values = iterator_to_array($values); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
3 |
|
$valuesString = '"' . implode('", "', $values) . '"'; |
|
|
|
|
|
|
37
|
|
|
|
|
38
|
3 |
|
$result->addError( |
|
39
|
3 |
|
$rule->getSubsetMessage(), |
|
40
|
|
|
[ |
|
41
|
3 |
|
'attribute' => $context->getAttribute(), |
|
42
|
|
|
'values' => $valuesString, |
|
43
|
|
|
], |
|
44
|
|
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
9 |
|
return $result; |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|