Completed
Push — master ( cd6aa3...db07f0 )
by Jitendra
13s
created

Validation::preChecking()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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->addRules($ruleSet, $dataSet, true)->validate($dataSet);
167
168
        return $this;
169
    }
170
171
    /**
172
     * Run the validation rules on data set.
173
     *
174
     * @param array $ruleSet
175
     * @param array $dataSet
176
     * @param bool  $reset   Whether to reset currently registered validators.
177
     *
178
     * @return Validation
179
     */
180
    public function addRules(array $ruleSet, array $dataSet = [], bool $reset = false): Validation
181
    {
182
        if ($reset) {
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
186
        foreach ($ruleSet as $attribute => $rules) {
187
            if (\is_string($rules)) {
188
                $rules = $this->parseRules($rules);
189
            }
190
191
            if (!\is_array($rules)) {
192
                throw new \UnexpectedValueException('The rules should be an array or string');
193
            }
194
195
            // Only validate if attribute exists in dataSet when so configured.
196
            if (isset($rules['if_exist']) && !\array_key_exists($attribute, $dataSet)) {
197
                continue;
198
            }
199
200
            unset($rules['if_exist']);
201
            $this->attributeRules($attribute, $rules);
202
        }
203
204
        return $this;
205
    }
206
207
    /**
208
     * Parse string representation of the rules and make it array.
209
     *
210
     * Rule Format: `rule1:key1:value11,value12;key2:value22|rule2:key21:value21|rule3`
211
     *
212
     * @param string $rules Example: 'required|length:min:1;max:2;|in:domain:1,12,30'
213
     *
214
     * @return array
215
     */
216
    protected function parseRules(string $rules): array
217
    {
218
        $parsed = [];
219
220
        foreach (\explode('|', $rules) as $rule) {
221
            if (false === \strpos($rule, ':')) {
222
                $parsed[$rule] = [];
223
                continue;
224
            }
225
226
            list($name, $options) = \explode(':', $rule, 2);
227
            foreach (\explode(';', $options) as $parts) {
228
                list($key, $value) = \explode(':', $parts) + ['', ''];
229
                if (\strpos($value, ',')) {
230
                    $value = \explode(',', $value);
231
                }
232
233
                $parsed[$name][$key] = $value;
234
            }
235
        }
236
237
        return $parsed;
238
    }
239
240
    /**
241
     * Add all the rules for given attribute to validators list.
242
     *
243
     * @param string $attribute
244
     * @param array  $rules
245
     *
246
     * @return void
247
     */
248
    protected function attributeRules(string $attribute, array $rules)
249
    {
250
        foreach ($rules as $rule => $options) {
251
            if (!isset($this->validators[$rule])) {
252
                throw new \InvalidArgumentException('Unknown validation rule: ' . $rule);
253
            }
254
255
            $validator = $this->validators[$rule];
256
            $options   = (array) $options + [
257
                'callback' => $this->callbacks[$rule] ?? null,
258
                'message'  => $this->_defaultMessages[$rule] ?? null,
259
                '__field'  => $attribute,
260
            ];
261
262
            $this->add($attribute, new $validator($options));
263
        }
264
    }
265
266
    /**
267
     * {@inheritdoc}
268
     */
269
    protected function preChecking($field, ValidatorInterface $validator): bool
270
    {
271
        $this->validator = $validator;
272
273
        return parent::preChecking($field, $validator);
274
    }
275
276
    /**
277
     * Get current value being validated.
278
     *
279
     * @return mixed
280
     */
281
    public function getCurrentValue()
282
    {
283
        return $this->getValue($this->validator->getOption('__field'));
284
    }
285
286
    /**
287
     * Delegate calls to current validator.
288
     *
289
     * @param string $method
290
     * @param mixed  $args
291
     *
292
     * @return mixed
293
     */
294
    public function __call($method, $args)
295
    {
296
        return $this->validator->$method(...$args);
297
    }
298
}
299