Passed
Pull Request — master (#222)
by Dmitriy
12:29
created

SubsetHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
wmc 5
eloc 12
dl 0
loc 23
ccs 10
cts 12
cp 0.8333
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 21 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use Yiisoft\Validator\Exception\UnexpectedRuleException;
13
14
final class SubsetHandler implements RuleHandlerInterface
15
{
16 10
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
17
    {
18 10
        if (!$rule instanceof Subset) {
19 1
            throw new UnexpectedRuleException(Subset::class, $rule);
20
        }
21
22 9
        $result = new Result();
23
24 9
        if (!is_iterable($value)) {
25
            $result->addError($rule->iterableMessage);
26
            return $result;
27
        }
28
29 9
        if (!ArrayHelper::isSubset($value, $rule->values, $rule->strict)) {
30 3
            $values = is_array($rule->values) ? $rule->values : iterator_to_array($rule->values);
31 3
            $valuesString = '"' . implode('", "', $values) . '"';
32
33 3
            $result->addError($rule->subsetMessage, ['values' => $valuesString]);
34
        }
35
36 9
        return $result;
37
    }
38
}
39