Passed
Pull Request — master (#293)
by
unknown
02:21
created

SubsetHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 71.43%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 20
c 1
b 0
f 0
dl 0
loc 37
ccs 15
cts 21
cp 0.7143
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 31 5
A __construct() 0 2 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\Translator\TranslatorInterface;
10
use Yiisoft\Validator\Exception\UnexpectedRuleException;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\RuleHandlerInterface;
13
use Yiisoft\Validator\ValidationContext;
14
15
final class SubsetHandler implements RuleHandlerInterface
16
{
17 11
    public function __construct(private TranslatorInterface $translator)
18
    {
19
    }
20
21 10
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
22
    {
23 10
        if (!$rule instanceof Subset) {
24 1
            throw new UnexpectedRuleException(Subset::class, $rule);
25
        }
26
27 9
        $result = new Result();
28
29 9
        if (!is_iterable($value)) {
30
            $formattedMessage = $this->translator->translate(
31
                $rule->getIterableMessage(),
32
                ['attribute' => $context->getAttribute(), 'value' => $value]
33
            );
34
            $result->addError($formattedMessage);
35
            return $result;
36
        }
37
38 9
        if (!ArrayHelper::isSubset($value, $rule->getValues(), $rule->isStrict())) {
39 3
            $values = $rule->getValues() instanceof Traversable
40
                ? iterator_to_array($rule->getValues())
41 3
                : $rule->getValues();
42 3
            $valuesString = '"' . implode('", "', $values) . '"';
0 ignored issues
show
Bug introduced by
It seems like $values can also be of type iterable; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

42
            $valuesString = '"' . implode('", "', /** @scrutinizer ignore-type */ $values) . '"';
Loading history...
43
44 3
            $formattedMessage = $this->translator->translate(
45 3
                $rule->getSubsetMessage(),
46 3
                ['attribute' => $context->getAttribute(), 'value' => $value, 'values' => $valuesString]
47
            );
48 3
            $result->addError($formattedMessage);
49
        }
50
51 9
        return $result;
52
    }
53
}
54