Passed
Push — master ( 46a3b3...1cc59e )
by Travis
02:14
created

InListGuard::isCastable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace InputGuard\Guards;
5
6
use ArrayObject;
7
use InputGuard\Guards\Bases\SingleInput;
8
use InputGuard\Guards\Bases\Strict;
9
10
class InListGuard implements Guard
11
{
12
    use ErrorMessagesBase;
13
    use SingleInput;
14
    use Strict;
15
16
    /**
17
     * @var iterable
18
     */
19
    private $list;
20
21
    /**
22
     * InListVal constructor.
23
     *
24
     * @param mixed      $input
25
     * @param iterable   $list
26
     * @param mixed|null $defaultValue
27
     * @param bool       $defaultStrict
28
     *
29
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
30
     */
31 17
    public function __construct($input, iterable $list, $defaultValue = null, bool $defaultStrict = true)
32
    {
33 17
        $this->input  = $input;
34 17
        $this->list   = $list;
35 17
        $this->value  = $defaultValue;
36 17
        $this->strict = $defaultStrict;
37 17
    }
38
39 17
    public function value()
40
    {
41 17
        $this->success();
42
43 17
        return $this->value;
44
    }
45
46 17
    protected function validation($input, &$value): bool
47
    {
48 17
        if ($this->isCastable() ? $this->validateCastableList($input) : $this->validateTraversableList($input)) {
0 ignored issues
show
Coding Style introduced by
Inline IF statements are not allowed
Loading history...
49 8
            $value = $input;
50 8
            return true;
51
        }
52
53 9
        return false;
54
    }
55
56 17
    private function isCastable(): bool
57
    {
58 17
        return \is_array($this->list) || $this->list instanceof ArrayObject;
59
    }
60
61 12
    private function validateCastableList($input): bool
62
    {
63 12
        return \in_array($input, (array)$this->list, $this->strict);
64
    }
65
66 5
    private function validateTraversableList($input): bool
67
    {
68 5
        $validate = $this->strict
69
            ? static function ($value) use ($input): bool {
0 ignored issues
show
Coding Style introduced by
Inline IF statements are not allowed
Loading history...
70 3
                return $value === $input;
71 3
            }
72
            : static function ($value) use ($input): bool {
73
                /** @noinspection TypeUnsafeComparisonInspection */
74 2
                return $value == $input;
75 5
            };
76
77 5
        foreach ($this->list as $item) {
78 5
            if ($validate($item)) {
79 5
                return true;
80
            }
81
        }
82
83 3
        return false;
84
    }
85
}
86