Completed
Pull Request — master (#431)
by Anton
04:27
created

ValidatorChain::__call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Validator;
12
13
use Bluz\Validator\Exception\ValidatorException;
14
use Bluz\Validator\Rule\RuleInterface;
15
16
/**
17
 * Chain of Validators
18
 *
19
 * Chain can consists one or more validation rules
20
 *
21
 * @package  Bluz\Validator
22
 * @author   Anton Shevchuk
23
 *
24
 * @method ValidatorChain alpha($additionalCharacters = '')
25
 * @method ValidatorChain alphaNumeric($additionalCharacters = '')
26
 * @method ValidatorChain array($callback)
27
 * @method ValidatorChain between($min, $max)
28
 * @method ValidatorChain betweenInclusive($min, $max)
29
 * @method ValidatorChain condition($condition)
30
 * @method ValidatorChain contains($containsValue)
31
 * @method ValidatorChain containsStrict($containsValue)
32
 * @method ValidatorChain countryCode()
33
 * @method ValidatorChain creditCard()
34
 * @method ValidatorChain date($format)
35
 * @method ValidatorChain domain($checkDns = false)
36
 * @method ValidatorChain email($checkDns = false)
37
 * @method ValidatorChain equals($compareTo)
38
 * @method ValidatorChain equalsStrict($compareTo)
39
 * @method ValidatorChain float()
40
 * @method ValidatorChain in($haystack)
41
 * @method ValidatorChain inStrict($haystack)
42
 * @method ValidatorChain integer()
43
 * @method ValidatorChain ip($options = null)
44
 * @method ValidatorChain json()
45
 * @method ValidatorChain latin($additionalCharacters = '')
46
 * @method ValidatorChain latinNumeric($additionalCharacters = '')
47
 * @method ValidatorChain length($min = null, $max = null)
48
 * @method ValidatorChain less($maxValue)
49
 * @method ValidatorChain lessOrEqual($maxValue)
50
 * @method ValidatorChain more($minValue)
51
 * @method ValidatorChain moreOrEqual($minValue)
52
 * @method ValidatorChain notEmpty()
53
 * @method ValidatorChain noWhitespace()
54
 * @method ValidatorChain numeric()
55
 * @method ValidatorChain required()
56
 * @method ValidatorChain regexp($expression)
57
 * @method ValidatorChain slug()
58
 * @method ValidatorChain string()
59
 */
60
class ValidatorChain
61
{
62
    /**
63
     * @var string description of rules chain
64
     */
65
    protected $description;
66
67
    /**
68
     * @var RuleInterface[] list of validation rules
69
     */
70
    protected $rules = [];
71
72
    /**
73
     * @var string Error message
74
     */
75
    protected $error;
76
77
    /**
78
     * Magic call for create new rule
79
     *
80
     * @param  string $ruleName
81
     * @param  array  $arguments
82
     *
83
     * @return ValidatorChain
84
     * @throws Exception\ComponentException
85
     */
86 8
    public function __call($ruleName, $arguments) : ValidatorChain
87
    {
88 8
        $this->addRule(Validator::rule($ruleName, $arguments));
89 8
        return $this;
90
    }
91
92
    /**
93
     * Add Rule to ValidatorChain
94
     *
95
     * @param RuleInterface $rule
96
     *
97
     * @return ValidatorChain
98
     */
99 14
    public function addRule($rule) : ValidatorChain
100
    {
101 14
        $this->rules[] = $rule;
102 14
        return $this;
103
    }
104
105
    /**
106
     * Add Callback Rule to ValidatorChain
107
     *
108
     * @param mixed       $callable
109
     * @param string|null $description
110
     *
111
     * @return ValidatorChain
112
     */
113 6
    public function callback($callable, $description = null) : ValidatorChain
114
    {
115 6
        $rule = Validator::rule('callback', [$callable]);
116 6
        if ($description) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $description of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
117 2
            $rule->setDescription($description);
118
        }
119 6
        $this->addRule($rule);
120 6
        return $this;
121
    }
122
123
    /**
124
     * Validate chain of rules
125
     *
126
     * @param mixed $input
127
     *
128
     * @return bool
129
     */
130 11
    public function validate($input) : bool
131
    {
132 11
        $this->error = null; // clean
133 11
        foreach ($this->rules as $rule) {
134 11
            if (!$rule->validate($input)) {
135 8
                $this->error = $rule->getDescription();
136 11
                return false;
137
            }
138
        }
139 4
        return true;
140
    }
141
142
    /**
143
     * Assert
144
     *
145
     * @param  mixed $input
146
     *
147
     * @throws ValidatorException
148
     */
149 3
    public function assert($input)
150
    {
151 3
        if (!$this->validate($input)) {
152 3
            throw new ValidatorException($this->getError());
153
        }
154
    }
155
156
    /**
157
     * Get required flag
158
     *
159
     * @return bool
160
     */
161
    public function isRequired() : bool
162
    {
163
        return array_key_exists('required', $this->rules);
164
    }
165
166
    /**
167
     * Get error message
168
     *
169
     * @return null|string
170
     */
171 7
    public function getError()
172
    {
173 7
        if ($this->description) {
174 3
            return $this->description;
175
        }
176 4
        return $this->error;
177
    }
178
179
    /**
180
     * Set error message for replace text from rule
181
     *
182
     * @param  string $message
183
     *
184
     * @return ValidatorChain
185
     */
186
    protected function setError($message) : ValidatorChain
187
    {
188
        $this->error = $message;
189
        return $this;
190
    }
191
192
    /**
193
     * Get validation description
194
     *
195
     * @return array
196
     */
197 4
    public function getDescription() : array
198
    {
199 4
        if ($this->description) {
200 2
            return [$this->description];
201
        }
202
203 3
        return array_map('strval', $this->rules);
204
    }
205
206
    /**
207
     * Set validation description
208
     *
209
     * @param  string $message
210
     *
211
     * @return ValidatorChain
212
     */
213 4
    public function setDescription($message) : ValidatorChain
214
    {
215 4
        $this->description = $message;
216 4
        return $this;
217
    }
218
219
    /**
220
     * @inheritdoc
221
     */
222 1
    public function __toString()
223
    {
224 1
        return implode("\n", $this->getDescription());
225
    }
226
}
227