Passed
Pull Request — master (#27)
by Jitendra
01:46
created

Validation::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
    /** @var Rules */
50
    protected $rulesHelper;
51
52
    public function initialize()
53
    {
54
        $this->rulesHelper = new Rules($this);
55
    }
56
57
    /**
58
     * Register a custom validation rule.
59
     *
60
     * @param string             $ruleName
61
     * @param callable|Validator $handler
62
     * @param string             $message  Message to use when validation fails
63
     *
64
     * @return self
65
     */
66
    public function register(string $ruleName, $handler, string $message = ''): self
67
    {
68
        if (isset($this->validators[$ruleName])) {
69
            return $this;
70
        }
71
72
        if ($message) {
73
            $this->_defaultMessages += [$ruleName => $message];
74
        }
75
76
        $this->validators[$ruleName] = $this->getHandler($ruleName, $handler);
77
78
        return $this;
79
    }
80
81
    /**
82
     * Get validation handler description].
83
     *
84
     * @param string $ruleName
85
     * @param mixed  $handler
86
     *
87
     * @return string
88
     */
89
    protected function getHandler(string $ruleName, $handler)
90
    {
91
        if ($handler instanceof \Closure) {
92
            $handler = \Closure::bind($handler, $this);
93
        }
94
95
        if (\is_callable($handler)) {
96
            $this->callbacks[$ruleName] = $handler;
97
            $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...
98
        }
99
100
        if (!\is_subclass_of($handler, Validator::class)) {
101
            throw new \InvalidArgumentException('Unsupported validation rule: ' . $ruleName);
102
        }
103
104
        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...
105
    }
106
107
    /**
108
     * Registers multiple custom validation rules at once!
109
     *
110
     * @param array $ruleHandlers ['rule1' => <handler>, ...]
111
     * @param array $messages     ['rule1' => 'message', ...]
112
     *
113
     * @return self
114
     */
115
    public function registerRules(array $ruleHandlers, array $messages = []): self
116
    {
117
        foreach ($ruleHandlers as $ruleName => $handler) {
118
            $this->register($ruleName, $handler, $messages[$ruleName] ?? '');
119
        }
120
121
        return $this;
122
    }
123
124
    /**
125
     * Check if the validation passes.
126
     *
127
     * @return bool
128
     */
129
    public function pass(): bool
130
    {
131
        return \count($this->_messages) === 0;
132
    }
133
134
    /**
135
     * Check if the validation fails.
136
     *
137
     * @return bool
138
     */
139
    public function fail(): bool
140
    {
141
        return !$this->pass();
142
    }
143
144
    /**
145
     * Get the error messages.
146
     *
147
     * @return array
148
     */
149
    public function getErrorMessages(): array
150
    {
151
        $messages = [];
152
153
        foreach ($this->_messages as $message) {
154
            $messages[] = [
155
                'code'    => $message->getCode(),
156
                'message' => $message->getMessage(),
157
                'field'   => $message->getField(),
158
            ];
159
        }
160
161
        return $messages;
162
    }
163
164
    /**
165
     * self validation with given ruleSet against given arbitrary dataSet.
166
     *
167
     * @param array        $ruleSet
168
     * @param array|object $dataSet
169
     *
170
     * @return self
171
     */
172
    public function run(array $ruleSet, $dataSet): self
173
    {
174
        $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...
175
176
        // See if it is arrayable!
177
        if (\is_object($dataSet)) {
178
            $dataSet = $this->prepareDate($dataSet);
179
        }
180
181
        // OK, must be entity!
182
        if (\is_object($dataSet)) {
183
            $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...
184
        } else {
185
            $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...
186
        }
187
188
        $this->addRules($ruleSet)->validate();
189
190
        return $this;
191
    }
192
193
    /**
194
     * Prepare data &/or entity.
195
     *
196
     * @param array|object $dataSet
197
     *
198
     * @return array|object
199
     */
200
    protected function prepareDate($dataSet)
201
    {
202
        if ($dataSet instanceof \stdClass) {
203
            return (array) $dataSet;
204
        }
205
206
        if (\method_exists($dataSet, 'toArray')) {
207
            return $dataSet->toArray();
208
        }
209
210
        if (\method_exists($dataSet, 'getData')) {
211
            return $dataSet->getData();
212
        }
213
214
        return $dataSet;
215
    }
216
217
    /**
218
     * Run the validation rules on data set.
219
     *
220
     * @param array $ruleSet
221
     *
222
     * @return self
223
     */
224
    protected function addRules(array $ruleSet): self
225
    {
226
        foreach ($ruleSet as $attribute => $rules) {
227
            $rules = $this->rulesHelper->normalizeRules($rules);
228
229
            // Only validate if attribute exists in dataSet when so configured.
230
            if (isset($rules['if_exist']) && null === $this->getValue($attribute)) {
231
                continue;
232
            }
233
234
            unset($rules['if_exist']);
235
            $this->attributeRules($attribute, $rules);
236
        }
237
238
        return $this;
239
    }
240
241
    /**
242
     * Add all the rules for given attribute to validators list.
243
     *
244
     * @param string $attribute
245
     * @param array  $rules
246
     *
247
     * @return void
248
     */
249
    protected function attributeRules(string $attribute, array $rules)
250
    {
251
        foreach ($rules as $rule => $options) {
252
            if (!isset($this->validators[$rule])) {
253
                throw new \InvalidArgumentException('Unknown validation rule: ' . $rule);
254
            }
255
256
            $validator = $this->validators[$rule];
257
            $options   = (array) $options + [
258
                'callback' => $this->callbacks[$rule] ?? null,
259
                'message'  => $this->_defaultMessages[$rule] ?? null,
260
                '__field'  => $attribute,
261
            ];
262
263
            $this->add($attribute, new $validator($options));
264
        }
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    protected function preChecking($field, ValidatorInterface $validator): bool
271
    {
272
        $this->validator = $validator;
273
274
        return parent::preChecking($field, $validator);
275
    }
276
277
    /**
278
     * Get current value being validated.
279
     *
280
     * @return mixed
281
     */
282
    public function getCurrentValue()
283
    {
284
        return $this->getValue($this->validator->getOption('__field'));
285
    }
286
287
    /**
288
     * Delegate calls to current validator.
289
     *
290
     * @param string $method
291
     * @param mixed  $args
292
     *
293
     * @return mixed
294
     */
295
    public function __call($method, $args)
296
    {
297
        return $this->validator->$method(...$args);
298
    }
299
}
300