Passed
Pull Request — master (#199)
by Alexander
02:50
created

Subset::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\Rule;
12
use Yiisoft\Validator\ValidationContext;
13
14
#[Attribute(Attribute::TARGET_PROPERTY)]
15
final class Subset extends Rule
16
{
17 4
    public function __construct(
18
        private iterable $values,
19
        /**
20
         * @var bool whether the comparison is strict (both type and value must be the same)
21
         */
22
        private bool $strict = false,
23
        private string $iterableMessage = 'Value must be iterable.',
24
        private string $subsetMessage = 'Values must be ones of {values}.',
25
        ?FormatterInterface $formatter = null,
26
        bool $skipOnEmpty = false,
27
        bool $skipOnError = false,
28
        $when = null
29
    ) {
30 4
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
31
    }
32
33 3
    protected function validateValue($value, ?ValidationContext $context = null): Result
34
    {
35 3
        $result = new Result();
36
37 3
        if (!is_iterable($value)) {
38
            $result->addError($this->formatMessage($this->iterableMessage));
39
            return $result;
40
        }
41
42 3
        if (!ArrayHelper::isSubset($value, $this->values, $this->strict)) {
43 1
            $values = is_array($this->values) ? $this->values : iterator_to_array($this->values);
44 1
            $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

44
            $valuesString = '"' . implode('", "', /** @scrutinizer ignore-type */ $values) . '"';
Loading history...
45
46 1
            $result->addError($this->formatMessage($this->subsetMessage, ['values' => $valuesString]));
47
        }
48
49 3
        return $result;
50
    }
51
52
    public function getOptions(): array
53
    {
54
        return array_merge(parent::getOptions(), [
55
            'values' => $this->values,
56
            'strict' => $this->strict,
57
            'iterableMessage' => $this->formatMessage($this->iterableMessage),
58
            'subsetMessage' => $this->formatMessage($this->subsetMessage),
59
        ]);
60
    }
61
}
62