Validation::addRules()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 7
c 4
b 0
f 1
dl 0
loc 15
rs 10
cc 4
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the PHALCON-EXT package.
5
 *
6
 * (c) Jitendra Adhikari <[email protected]>
7
 *     <https://github.com/adhocore>
8
 *
9
 * Licensed under MIT license.
10
 */
11
12
namespace PhalconExt\Validation;
13
14
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...
15
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...
16
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...
17
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...
18
19
/**
20
 * Phalcon Validation with batteries.
21
 *
22
 * @author  Jitendra Adhikari <[email protected]>
23
 * @license MIT
24
 *
25
 * @link    https://github.com/adhocore/phalcon-ext
26
 */
27
class Validation extends BaseValidation
28
{
29
    /** @var array The alias of available validators */
30
    protected $validators = [
31
        '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...
32
        '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...
33
        '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...
34
        '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...
35
        '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...
36
        '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...
37
        '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...
38
        '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...
39
        '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...
40
        '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...
41
        '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...
42
        '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...
43
        '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...
44
        '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...
45
        '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...
46
        '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...
47
        '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...
48
        '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...
49
        'exist'        => Existence::class,
50
    ];
51
52
    /** @var array The custom validation callbacks */
53
    protected $callbacks = [];
54
55
    /** @var ValidatorInterface The currently validating Validator. */
56
    protected $validator;
57
58
    /** @var Rules */
59
    protected $rulesHelper;
60
61
    public function initialize()
62
    {
63
        $this->rulesHelper = new Rules($this);
64
    }
65
66
    /**
67
     * Register a custom validation rule.
68
     *
69
     * @param string             $ruleName
70
     * @param callable|Validator $handler
71
     * @param string             $message  Message to use when validation fails
72
     *
73
     * @return self
74
     */
75
    public function register(string $ruleName, $handler, string $message = ''): self
76
    {
77
        if (isset($this->validators[$ruleName])) {
78
            return $this;
79
        }
80
81
        if ($message) {
82
            $this->_defaultMessages += [$ruleName => $message];
83
        }
84
85
        $this->validators[$ruleName] = $this->getHandler($ruleName, $handler);
86
87
        return $this;
88
    }
89
90
    /**
91
     * Get validation handler description].
92
     *
93
     * @param string $ruleName
94
     * @param mixed  $handler
95
     *
96
     * @return string
97
     */
98
    protected function getHandler(string $ruleName, $handler)
99
    {
100
        if ($handler instanceof \Closure) {
101
            $handler = \Closure::bind($handler, $this);
102
        }
103
104
        if (\is_callable($handler)) {
105
            $this->callbacks[$ruleName] = $handler;
106
            $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...
107
        }
108
109
        if (!\is_subclass_of($handler, Validator::class)) {
110
            throw new \InvalidArgumentException('Unsupported validation rule: ' . $ruleName);
111
        }
112
113
        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...
114
    }
115
116
    /**
117
     * Registers multiple custom validation rules at once!
118
     *
119
     * @param array $ruleHandlers ['rule1' => <handler>, ...]
120
     * @param array $messages     ['rule1' => 'message', ...]
121
     *
122
     * @return self
123
     */
124
    public function registerRules(array $ruleHandlers, array $messages = []): self
125
    {
126
        foreach ($ruleHandlers as $ruleName => $handler) {
127
            $this->register($ruleName, $handler, $messages[$ruleName] ?? '');
128
        }
129
130
        return $this;
131
    }
132
133
    /**
134
     * Check if the validation passes.
135
     *
136
     * @return bool
137
     */
138
    public function pass(): bool
139
    {
140
        return \count($this->_messages) === 0;
141
    }
142
143
    /**
144
     * Check if the validation fails.
145
     *
146
     * @return bool
147
     */
148
    public function fail(): bool
149
    {
150
        return !$this->pass();
151
    }
152
153
    /**
154
     * Get the error messages.
155
     *
156
     * @return array
157
     */
158
    public function getErrorMessages(): array
159
    {
160
        $messages = [];
161
162
        foreach ($this->_messages as $message) {
163
            $messages[] = [
164
                'code'    => $message->getCode(),
165
                'message' => $message->getMessage(),
166
                'field'   => $message->getField(),
167
            ];
168
        }
169
170
        return $messages;
171
    }
172
173
    /**
174
     * self validation with given ruleSet against given arbitrary dataSet.
175
     *
176
     * @param array        $ruleSet
177
     * @param array|object $dataSet
178
     *
179
     * @return self
180
     */
181
    public function run(array $ruleSet, $dataSet): self
182
    {
183
        $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...
184
185
        // See if it is arrayable!
186
        if (\is_object($dataSet)) {
187
            $dataSet = $this->prepareDate($dataSet);
188
        }
189
190
        // OK, must be entity!
191
        if (\is_object($dataSet)) {
192
            $this->_entity = $dataSet;
0 ignored issues
show
Bug Best Practice introduced by
The property _entity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
193
        } else {
194
            $this->_data = $dataSet;
0 ignored issues
show
Bug Best Practice introduced by
The property _data does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
195
        }
196
197
        $this->addRules($ruleSet)->validate();
198
199
        return $this;
200
    }
201
202
    /**
203
     * Prepare data &/or entity.
204
     *
205
     * @param array|object $dataSet
206
     *
207
     * @return array|object
208
     */
209
    protected function prepareDate($dataSet)
210
    {
211
        if ($dataSet instanceof \stdClass) {
212
            return (array) $dataSet;
213
        }
214
215
        if (\method_exists($dataSet, 'toArray')) {
216
            return $dataSet->toArray();
217
        }
218
219
        if (\method_exists($dataSet, 'getData')) {
220
            return $dataSet->getData();
221
        }
222
223
        return $dataSet;
224
    }
225
226
    /**
227
     * Run the validation rules on data set.
228
     *
229
     * @param array $ruleSet
230
     *
231
     * @return self
232
     */
233
    protected function addRules(array $ruleSet): self
234
    {
235
        foreach ($ruleSet as $attribute => $rules) {
236
            $rules = $this->rulesHelper->normalizeRules($rules);
237
238
            // Only validate if attribute exists in dataSet when so configured.
239
            if (isset($rules['if_exist']) && null === $this->getValue($attribute)) {
240
                continue;
241
            }
242
243
            unset($rules['if_exist']);
244
            $this->attributeRules($attribute, $rules);
245
        }
246
247
        return $this;
248
    }
249
250
    /**
251
     * Add all the rules for given attribute to validators list.
252
     *
253
     * @param string $attribute
254
     * @param array  $rules
255
     *
256
     * @return void
257
     */
258
    protected function attributeRules(string $attribute, array $rules)
259
    {
260
        foreach ($rules as $rule => $options) {
261
            if (!isset($this->validators[$rule])) {
262
                throw new \InvalidArgumentException('Unknown validation rule: ' . $rule);
263
            }
264
265
            $validator = $this->validators[$rule];
266
            $options   = (array) $options + [
267
                'callback' => $this->callbacks[$rule] ?? null,
268
                'message'  => $this->_defaultMessages[$rule] ?? null,
269
                '__field'  => $attribute,
270
            ];
271
272
            $this->add($attribute, new $validator($options));
273
        }
274
    }
275
276
    /**
277
     * {@inheritdoc}
278
     */
279
    protected function preChecking($field, ValidatorInterface $validator): bool
280
    {
281
        $this->validator = $validator;
282
283
        return parent::preChecking($field, $validator);
284
    }
285
286
    /**
287
     * Get current value being validated.
288
     *
289
     * @return mixed
290
     */
291
    public function getCurrentValue()
292
    {
293
        return $this->getValue($this->validator->getOption('__field'));
294
    }
295
296
    /**
297
     * Delegate calls to current validator.
298
     *
299
     * @param string $method
300
     * @param mixed  $args
301
     *
302
     * @return mixed
303
     */
304
    public function __call($method, $args)
305
    {
306
        return $this->validator->$method(...$args);
307
    }
308
}
309