Passed
Pull Request — master (#222)
by Rustam
02:28
created

SubsetHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 72.72%

Importance

Changes 0
Metric Value
wmc 6
eloc 22
dl 0
loc 40
ccs 16
cts 22
cp 0.7272
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 31 5
A __construct() 0 3 1
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