SingleInput::success()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 8
nc 4
nop 0
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace InputGuard\Guards\Bases;
5
6
trait SingleInput
7
{
8
    /**
9
     * The input to be validated.
10
     *
11
     * @var mixed
12
     */
13
    private $input;
14
15
    /**
16
     * The value to be returned after validation is complete.
17
     *
18
     * @var mixed
19
     */
20
    private $value;
21
22
    /**
23
     * A flag that indicates the validated state the object is in.
24
     *
25
     * @var bool|null
26
     */
27
    private $validated;
28
29
    /**
30
     * A flag that if set to true indicates that a null as the input is acceptable.
31
     *
32
     * @var bool
33
     */
34
    private $allowNull = false;
35
36
    /**
37
     * A flag that if set to true indicates that an empty string as the input is acceptable.
38
     *
39
     * @var bool
40
     */
41
    private $allowEmptyString = false;
42
43
    /**
44
     * The validation algorithm that determines if the input was successfully validated.
45
     *
46
     * If PHP allowed the behavior the method would be private.
47
     *
48
     * @param mixed $input
49
     * @param mixed &$value
50
     *
51
     * @return bool
52
     */
53
    abstract protected function validation($input, &$value): bool;
54
55
    /**
56
     * A switch to update the object state to allow nulls as a valid value for the input.
57
     *
58
     * @return $this
59
     */
60 2
    public function allowNull(): self
61
    {
62 2
        $this->allowNull = true;
63
64 2
        return $this;
65
    }
66
67
    /**
68
     * A switch to update the object state to allow empty strings as a valid value for the input.
69
     *
70
     * @return $this
71
     */
72 2
    public function allowEmptyString(): self
73
    {
74 2
        $this->allowEmptyString = true;
75
76 2
        return $this;
77
    }
78
79
    /**
80
     * Execute to determine the success status of the input validation.
81
     *
82
     * @return bool
83
     */
84 125
    public function success(): bool
85
    {
86 125
        if ($this->validated === null) {
87 125
            if ($this->allowNull && $this->input === null) {
88 2
                $this->validated = true;
89 124
            } elseif ($this->allowEmptyString && $this->input === '') {
90 2
                $this->validated = true;
91
            } else {
92 123
                $this->validated = $this->validation($this->input, $this->value);
93
            }
94
        }
95
96 125
        return $this->validated;
97
    }
98
}
99