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\Formatter; |
11
|
|
|
use Yiisoft\Validator\FormatterInterface; |
12
|
|
|
use Yiisoft\Validator\Result; |
13
|
|
|
use Yiisoft\Validator\ValidationContext; |
14
|
|
|
|
15
|
|
|
final class SubsetHandler implements RuleHandlerInterface |
16
|
|
|
{ |
17
|
|
|
private FormatterInterface $formatter; |
18
|
|
|
|
19
|
10 |
|
public function __construct(?FormatterInterface $formatter = null) |
20
|
|
|
{ |
21
|
10 |
|
$this->formatter = $formatter ?? new Formatter(); |
22
|
|
|
} |
23
|
|
|
|
24
|
10 |
|
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result |
25
|
|
|
{ |
26
|
10 |
|
if (!$rule instanceof Subset) { |
27
|
1 |
|
throw new UnexpectedRuleException(Subset::class, $rule); |
28
|
|
|
} |
29
|
|
|
|
30
|
9 |
|
$result = new Result(); |
31
|
|
|
|
32
|
9 |
|
if (!is_iterable($value)) { |
33
|
|
|
$formattedMessage = $this->formatter->format( |
34
|
|
|
$rule->getIterableMessage(), |
35
|
|
|
['attribute' => $context?->getAttribute(), 'value' => $value] |
36
|
|
|
); |
37
|
|
|
$result->addError($formattedMessage); |
38
|
|
|
return $result; |
39
|
|
|
} |
40
|
|
|
|
41
|
9 |
|
if (!ArrayHelper::isSubset($value, $rule->getValues(), $rule->isStrict())) { |
42
|
3 |
|
$values = $rule->getValues() instanceof Traversable |
43
|
|
|
? iterator_to_array($rule->getValues()) |
44
|
3 |
|
: $rule->getValues(); |
45
|
3 |
|
$valuesString = '"' . implode('", "', $values) . '"'; |
46
|
|
|
|
47
|
3 |
|
$formattedMessage = $this->formatter->format( |
48
|
3 |
|
$rule->getSubsetMessage(), |
49
|
3 |
|
['attribute' => $context?->getAttribute(), 'value' => $value, 'values' => $valuesString] |
50
|
|
|
); |
51
|
3 |
|
$result->addError($formattedMessage); |
52
|
|
|
} |
53
|
|
|
|
54
|
9 |
|
return $result; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|