SubsetHandler::validate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 20
rs 9.9332
ccs 12
cts 12
cp 1
crap 4
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\ValidationContext;
12
13
/**
14
 * A handler for {@see Subset} rule. Validates that the set of values is a subset of another set.
15
 */
16 17
final class SubsetHandler implements RuleHandlerInterface
17
{
18 17
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
19 1
    {
20
        if (!$rule instanceof Subset) {
21
            throw new UnexpectedRuleException(Subset::class, $rule);
22 16
        }
23 16
24 4
        if (!is_iterable($value)) {
25 4
            return (new Result())->addError($rule->getIncorrectInputMessage(), [
26 4
                'attribute' => $context->getTranslatedAttribute(),
27
                'type' => get_debug_type($value),
28
            ]);
29
        }
30 12
31 6
        if (!ArrayHelper::isSubset($value, $rule->getValues(), $rule->isStrict())) {
32 6
            return (new Result())->addError($rule->getMessage(), [
33 1
                'attribute' => $context->getTranslatedAttribute(),
34
            ]);
35
        }
36 6
37
        return new Result();
38 6
    }
39
}
40