Completed
Push — master ( 112b7a...450ccc )
by Travis
06:11
created

InListGuard::nonStrict()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
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
        // If the input is an array or an ArrayObject then it's cheap to cast it and use in_array().
49 17
        if (\is_array($this->list) || $this->list instanceof ArrayObject) {
50 12
            if (\in_array($input, (array)$this->list, $this->strict)) {
51 6
                $value = $input;
52 6
                return true;
53
            }
54
55 6
            return false;
56
        }
57
58 5
        $validate = $this->strict
59
            ? function ($value) use ($input): bool {
60 3
                return $value === $input;
61 3
            }
62
            : function ($value) use ($input): bool {
63
                /** @noinspection TypeUnsafeComparisonInspection */
64 2
                return $value == $input;
65 5
            };
66
67
        // Since the type hint is 'iterable' (aka Traversable) iterate over the object.
68 5
        foreach ($this->list as $item) {
69 5
            if ($validate($item)) {
70 2
                $value = $input;
71 5
                return true;
72
            }
73
        }
74
75 3
        return false;
76
    }
77
}
78