Completed
Push — master ( f183e1...4cf3c5 )
by Jitendra
14s queued 11s
created

Validation::addRules()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 2
1
<?php
2
3
namespace PhalconExt\Validation;
4
5
use Phalcon\Validation as BaseValidation;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Phalcon\Validation\Validator;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Phalcon\Validation\ValidatorInterface;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\ValidatorInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use PhalconExt\Validators;
0 ignored issues
show
Bug introduced by
The type PhalconExt\Validators was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
10
/**
11
 * Phalcon Validation with batteries.
12
 *
13
 * @author  Jitendra Adhikari <[email protected]>
14
 * @license MIT
15
 *
16
 * @link    https://github.com/adhocore/phalcon-ext
17
 */
18
class Validation extends BaseValidation
19
{
20
    /** @var array The alias of available validators */
21
    protected $validators = [
22
        'alnum'        => Validator\Alnum::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Alnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
        'alpha'        => Validator\Alpha::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Alpha was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
        'between'      => Validator\Between::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Between was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
25
        'confirmation' => Validator\Confirmation::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Confirmation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
        'creditcard'   => Validator\CreditCard::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\CreditCard was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
        'date'         => Validator\Date::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Date was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
        'digit'        => Validator\Digit::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Digit was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
        'email'        => Validator\Email::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Email was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
        'not_in'       => Validator\ExclusionIn::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\ExclusionIn was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
        'file'         => Validator\File::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
        'identical'    => Validator\Identical::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Identical was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
        'in'           => Validator\InclusionIn::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\InclusionIn was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
        'numeric'      => Validator\Numericality::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Numericality was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
        'required'     => Validator\PresenceOf::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
        'regex'        => Validator\Regex::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Regex was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
        'length'       => Validator\StringLength::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\StringLength was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
38
        'unique'       => Validator\Uniqueness::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Uniqueness was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
39
        'url'          => Validator\Url::class,
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Url was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40
        'exist'        => Existence::class,
41
    ];
42
43
    /** @var array The custom validation callbacks */
44
    protected $callbacks = [];
45
46
    /** @var ValidatorInterface The currently validating Validator. */
47
    protected $validator;
48
49
    /**
50
     * Register a custom validation rule.
51
     *
52
     * @param string             $ruleName
53
     * @param callable|Validator $handler
54
     * @param string             $message  Message to use when validation fails
55
     *
56
     * @return Validation $this
57
     */
58
    public function register(string $ruleName, $handler, string $message = ''): self
59
    {
60
        if (isset($this->validators[$ruleName])) {
61
            return $this;
62
        }
63
64
        if ($message) {
65
            $this->_defaultMessages += [$ruleName => $message];
66
        }
67
68
        $this->validators[$ruleName] = $this->getHandler($ruleName, $handler);
69
70
        return $this;
71
    }
72
73
    /**
74
     * Get validation handler description].
75
     *
76
     * @param string $ruleName
77
     * @param mixed  $handler
78
     *
79
     * @return string
80
     */
81
    protected function getHandler(string $ruleName, $handler)
82
    {
83
        if ($handler instanceof \Closure) {
84
            $handler = \Closure::bind($handler, $this);
85
        }
86
87
        if (\is_callable($handler)) {
88
            $this->callbacks[$ruleName] = $handler;
89
            $handler                    = Validator\Callback::class;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Callback was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
90
        }
91
92
        if (!\is_subclass_of($handler, Validator::class)) {
93
            throw new \InvalidArgumentException('Unsupported validation rule: ' . $ruleName);
94
        }
95
96
        return $handler;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $handler also could return the type Closure which is incompatible with the documented return type string.
Loading history...
97
    }
98
99
    /**
100
     * Registers multiple custom validation rules at once!
101
     *
102
     * @param array $ruleHandlers ['rule1' => <handler>, ...]
103
     * @param array $messages     ['rule1' => 'message', ...]
104
     *
105
     * @return Validation $this
106
     */
107
    public function registerRules(array $ruleHandlers, array $messages = []): self
108
    {
109
        foreach ($ruleHandlers as $ruleName => $handler) {
110
            $this->register($ruleName, $handler, $messages[$ruleName] ?? '');
111
        }
112
113
        return $this;
114
    }
115
116
    /**
117
     * Check if the validation passes.
118
     *
119
     * @return bool
120
     */
121
    public function pass(): bool
122
    {
123
        return \count($this->_messages) === 0;
124
    }
125
126
    /**
127
     * Check if the validation fails.
128
     *
129
     * @return bool
130
     */
131
    public function fail(): bool
132
    {
133
        return !$this->pass();
134
    }
135
136
    /**
137
     * Get the error messages.
138
     *
139
     * @return array
140
     */
141
    public function getErrorMessages(): array
142
    {
143
        $messages = [];
144
145
        foreach ($this->_messages as $message) {
146
            $messages[] = [
147
                'code'    => $message->getCode(),
148
                'message' => $message->getMessage(),
149
                'field'   => $message->getField(),
150
            ];
151
        }
152
153
        return $messages;
154
    }
155
156
    /**
157
     * Runs a validation with given ruleSet against given arbitrary dataSet.
158
     *
159
     * @param array $ruleSet
160
     * @param array $dataSet
161
     *
162
     * @return Validation $this
163
     */
164
    public function run(array $ruleSet, array $dataSet): Validation
165
    {
166
        $this->_messages = $this->_validators = [];
0 ignored issues
show
Bug Best Practice introduced by
The property _validators does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug Best Practice introduced by
The property _messages does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
167
168
        $this->addRules($ruleSet, $dataSet)->validate($dataSet);
169
170
        return $this;
171
    }
172
173
    /**
174
     * Run the validation rules on data set.
175
     *
176
     * @param array $ruleSet
177
     * @param array $dataSet
178
     *
179
     * @return Validation
180
     */
181
    public function addRules(array $ruleSet, array $dataSet = []): Validation
182
    {
183
        foreach ($ruleSet as $attribute => $rules) {
184
            $rules = $this->normalizeRules($rules);
185
186
            // Only validate if attribute exists in dataSet when so configured.
187
            if (isset($rules['if_exist']) && !\array_key_exists($attribute, $dataSet)) {
188
                continue;
189
            }
190
191
            unset($rules['if_exist']);
192
            $this->attributeRules($attribute, $rules);
193
        }
194
195
        return $this;
196
    }
197
198
    /**
199
     * Normalize rules if needed.
200
     *
201
     * @param mixed $rules
202
     *
203
     * @return array
204
     */
205
    protected function normalizeRules($rules): array
206
    {
207
        if (\is_string($rules)) {
208
            return $this->parseRules($rules);
209
        }
210
211
        if (!\is_array($rules)) {
212
            throw new \UnexpectedValueException('The rules should be an array or string');
213
        }
214
215
        return $rules;
216
    }
217
218
    /**
219
     * Parse string representation of the rules and make it array.
220
     *
221
     * Rule Format: `rule1:key1:value11,value12;key2:value22|rule2:key21:value21|rule3`
222
     *
223
     * @param string $rules Example: 'required|length:min:1;max:2;|in:domain:1,12,30'
224
     *
225
     * @return array
226
     */
227
    protected function parseRules(string $rules): array
228
    {
229
        $parsed = [];
230
231
        foreach (\explode('|', $rules) as $rule) {
232
            if (false === \strpos($rule, ':')) {
233
                $parsed[$rule] = [];
234
                continue;
235
            }
236
237
            list($name, $options) = \explode(':', $rule, 2);
238
            $parsed[$name]        = $this->parseOptions($options);
239
        }
240
241
        return $parsed;
242
    }
243
244
    /**
245
     * Parse rule options.
246
     *
247
     * @param string $options
248
     *
249
     * @return array
250
     */
251
    protected function parseOptions(string $options): array
252
    {
253
        $parsed = [];
254
255
        foreach (\explode(';', $options) as $parts) {
256
            list($key, $value) = \explode(':', $parts) + ['', ''];
257
            if (\strpos($value, ',')) {
258
                $value = \explode(',', $value);
259
            }
260
261
            $parsed[$key] = $value;
262
        }
263
264
        return $parsed;
265
    }
266
267
    /**
268
     * Add all the rules for given attribute to validators list.
269
     *
270
     * @param string $attribute
271
     * @param array  $rules
272
     *
273
     * @return void
274
     */
275
    protected function attributeRules(string $attribute, array $rules)
276
    {
277
        foreach ($rules as $rule => $options) {
278
            if (!isset($this->validators[$rule])) {
279
                throw new \InvalidArgumentException('Unknown validation rule: ' . $rule);
280
            }
281
282
            $validator = $this->validators[$rule];
283
            $options   = (array) $options + [
284
                'callback' => $this->callbacks[$rule] ?? null,
285
                'message'  => $this->_defaultMessages[$rule] ?? null,
286
                '__field'  => $attribute,
287
            ];
288
289
            $this->add($attribute, new $validator($options));
290
        }
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296
    protected function preChecking($field, ValidatorInterface $validator): bool
297
    {
298
        $this->validator = $validator;
299
300
        return parent::preChecking($field, $validator);
301
    }
302
303
    /**
304
     * Get current value being validated.
305
     *
306
     * @return mixed
307
     */
308
    public function getCurrentValue()
309
    {
310
        return $this->getValue($this->validator->getOption('__field'));
311
    }
312
313
    /**
314
     * Delegate calls to current validator.
315
     *
316
     * @param string $method
317
     * @param mixed  $args
318
     *
319
     * @return mixed
320
     */
321
    public function __call($method, $args)
322
    {
323
        return $this->validator->$method(...$args);
324
    }
325
}
326