Completed
Push — master ( b99a49...895f8e )
by Jitendra
07:41 queued 03:12
created

Validation::attributeRules()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
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 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...
8
9
/**
10
 * Phalcon Validation with batteries.
11
 *
12
 * @author  Jitendra Adhikari <[email protected]>
13
 * @license MIT
14
 *
15
 * @link    https://github.com/adhocore/phalcon-ext
16
 */
17
class Validation extends BaseValidation
18
{
19
    /** @var array The alias of available validators */
20
    protected $validators = [
21
        '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...
22
        '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...
23
        '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...
24
        '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...
25
        '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...
26
        '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...
27
        '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...
28
        '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...
29
        '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...
30
        '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...
31
        '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...
32
        '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...
33
        '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...
34
        '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...
35
        '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...
36
        '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...
37
        '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...
38
        '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...
39
        'exist'        => Existence::class,
40
    ];
41
42
    /** @var array The custom validation callbacks */
43
    protected $callbacks = [];
44
45
    /**
46
     * Register a custom validation rule.
47
     *
48
     * @param string             $ruleName
49
     * @param callable|Validator $handler
50
     * @param string             $message  Message to use when validation fails
51
     *
52
     * @return Validation $this
53
     */
54
    public function register(string $ruleName, $handler, string $message = ''): self
55
    {
56
        if (isset($this->validators[$ruleName])) {
57
            return $this;
58
        }
59
60
        if ($message) {
61
            $this->_defaultMessages += [$ruleName => $message];
62
        }
63
64
        if (\is_callable($handler)) {
65
            $this->callbacks[$ruleName] = $handler;
66
            $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...
67
        }
68
69
        if (!\is_subclass_of($handler, Validator::class)) {
70
            throw new \InvalidArgumentException('Unsupported validation rule: ' . $ruleName);
71
        }
72
73
        $this->validators[$ruleName] = $handler;
74
75
        return $this;
76
    }
77
78
    /**
79
     * Registers multiple custom validation rules at once!
80
     *
81
     * @param array $ruleHandlers ['rule1' => <handler>, ...]
82
     * @param array $messages     ['rule1' => 'message', ...]
83
     *
84
     * @return Validation $this
85
     */
86
    public function registerRules(array $ruleHandlers, array $messages = []): self
87
    {
88
        foreach ($ruleHandlers as $ruleName => $handler) {
89
            $this->register($ruleName, $handler, $messages[$ruleName] ?? '');
90
        }
91
92
        return $this;
93
    }
94
95
    /**
96
     * Check if the validation passes.
97
     *
98
     * @return bool
99
     */
100
    public function pass(): bool
101
    {
102
        return \count($this->_messages) === 0;
103
    }
104
105
    /**
106
     * Check if the validation fails.
107
     *
108
     * @return bool
109
     */
110
    public function fail(): bool
111
    {
112
        return !$this->pass();
113
    }
114
115
    /**
116
     * Get the error messages.
117
     *
118
     * @return array
119
     */
120
    public function getErrorMessages(): array
121
    {
122
        $messages = [];
123
124
        foreach ($this->_messages as $message) {
125
            $messages[] = [
126
                'code'    => $message->getCode(),
127
                'message' => $message->getMessage(),
128
                'field'   => $message->getField(),
129
            ];
130
        }
131
132
        return $messages;
133
    }
134
135
    /**
136
     * Runs a validation with given ruleSet against given arbitrary dataSet.
137
     *
138
     * @param array $ruleSet
139
     * @param array $dataSet
140
     *
141
     * @return Validation $this
142
     */
143
    public function run(array $ruleSet, array $dataSet): Validation
144
    {
145
        $this->addRules($ruleSet, $dataSet, true)->validate($dataSet);
146
147
        return $this;
148
    }
149
150
    /**
151
     * Run the validation rules on data set.
152
     *
153
     * @param array $ruleSet
154
     * @param array $dataSet
155
     * @param bool  $reset   Whether to reset currently registered validators.
156
     *
157
     * @return Validation
158
     */
159
    public function addRules(array $ruleSet, array $dataSet = [], bool $reset = false): Validation
160
    {
161
        if ($reset) {
162
            $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...
163
        }
164
165
        foreach ($ruleSet as $attribute => $rules) {
166
            if (\is_string($rules)) {
167
                $rules = $this->parseRules($rules);
168
            }
169
170
            if (!\is_array($rules)) {
171
                throw new \UnexpectedValueException('The rules should be an array or string');
172
            }
173
174
            // Only validate if attribute exists in dataSet when so configured.
175
            if (isset($rules['if_exist']) && !\array_key_exists($attribute, $dataSet)) {
176
                continue;
177
            }
178
179
            unset($rules['if_exist']);
180
            $this->attributeRules($attribute, $rules);
181
        }
182
183
        return $this;
184
    }
185
186
    /**
187
     * Parse string representation of the rules and make it array.
188
     *
189
     * Rule Format: `rule1:key1:value11,value12;key2:value22|rule2:key21:value21|rule3`
190
     *
191
     * @param string $rules Example: 'required|length:min:1;max:2;|in:domain:1,12,30'
192
     *
193
     * @return array
194
     */
195
    protected function parseRules(string $rules): array
196
    {
197
        $parsed = [];
198
199
        foreach (\explode('|', $rules) as $rule) {
200
            if (false === \strpos($rule, ':')) {
201
                $parsed[$rule] = [];
202
                continue;
203
            }
204
205
            list($name, $options) = \explode(':', $rule, 2);
206
            foreach (\explode(';', $options) as $parts) {
207
                list($key, $value) = \explode(':', $parts) + ['', ''];
208
                if (\strpos($value, ',')) {
209
                    $value = \explode(',', $value);
210
                }
211
212
                $parsed[$name][$key] = $value;
213
            }
214
        }
215
216
        return $parsed;
217
    }
218
219
    /**
220
     * Add all the rules for given attribute to validators list.
221
     *
222
     * @param string $attribute
223
     * @param array  $rules
224
     *
225
     * @return void
226
     */
227
    protected function attributeRules(string $attribute, array $rules)
228
    {
229
        foreach ($rules as $rule => $options) {
230
            if (!isset($this->validators[$rule])) {
231
                throw new \InvalidArgumentException('Unknown validation rule: ' . $rule);
232
            }
233
234
            $validator = $this->validators[$rule];
235
            $options   = (array) $options + [
236
                'callback' => $this->callbacks[$rule] ?? null,
237
                'message'  => $this->_defaultMessages[$rule] ?? null,
238
            ];
239
240
            $this->add($attribute, new $validator($options));
241
        }
242
    }
243
}
244