Completed
Push — master ( f20507...fbd194 )
by Alessandro
01:50
created

Validator::isarray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Validoo;
4
5
/**
6
 * Validator Class
7
 * @author Alessandro Manno <[email protected]>
8
 * @author Chiara Ferrazza <[email protected]>
9
 * @copyright (c) 2016, Facile.it
10
 * @license https://github.com/facile-it/validoo/blob/master/LICENSE MIT Licence
11
 * @link https://github.com/facile-it/validoo
12
 */
13
14
/**
15
 * TODO: Exception handling for rules with parameters
16
 * TODO: unit tests for numeric, float, alpha_numeric, max_length, min_length, exact_length
17
 * TODO: add protection filters for several input vulnerabilities.
18
 */
19
class Validator
20
{
21
22
    /** @var array */
23
    private $errors = [];
24
    /** @var array */
25
    private $namings = [];
26
    /** @var array */
27
    private $customErrorsWithInputName = [];
28
    /** @var array */
29
    private $customErrors = [];
30
31
    /**
32
     * Constructor is not allowed because Validoo uses its own
33
     * static method to instantiate the validation
34
     * @param $errors
35
     * @param $namings
36
     */
37 48
    private function __construct($errors, $namings)
38
    {
39 48
        $this->errors = $errors;
40 48
        $this->namings = $namings;
41 48
    }
42
43
    /**
44
     * @param $inputs
45
     * @param array $rules
46
     * @param array|null $naming
47
     * @return Validator
48
     * @throws ValidooException
49
     */
50 48
    public static function validate($inputs, array $rules, array $naming = null): self
51
    {
52 48
        $errors = null;
53 48
        foreach ($rules as $input => $input_rules) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
54
55 48
            if (is_string($input_rules))
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
56 2
                $input_rules = explode("|", $input_rules);
57
58 48
            if (!is_array($input_rules))
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
59
                throw new ValidooException(ValidooException::ARRAY_EXPECTED, $input);
60
61 48
            if (in_array("onlyifset", $input_rules) && !isset($inputs[$input]))
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
62 1
                continue;
63
64 48
            foreach ($input_rules as $rule => $closure) {
65 48
                if (!isset($inputs[$input])) {
66 7
                    $input_value = null;
67
                } else {
68 41
                    $input_value = $inputs[$input];
69
                }
70 48
                if (is_numeric($rule)) {
71 46
                    $rule = $closure;
72
                }
73 48
                if ('onlyifset' == $rule)
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
74 1
                    continue;
75
76 48
                $rule_and_params = self::getParams($rule);
77 48
                $params = $real_params = $rule_and_params['params'];
78 48
                $rule = $rule_and_params['rule'];
79 48
                $params = self::getParamValues($params, $inputs);
80 48
                array_unshift($params, $input_value);
81
82 48
                if (false == self::doValidation($closure, $params, $rule)) {
83 27
                    $errors[$input][$rule]['result'] = false;
84 48
                    $errors[$input][$rule]['params'] = $real_params;
85
                }
86
            }
87
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
88
        }
89 48
        return new self($errors, $naming);
90
    }
91
92
    /**
93
     * @param $closure
94
     * @param $params
95
     * @param $rule
96
     * @return mixed
97
     * @throws ValidooException
98
     */
99 48
    private static function doValidation($closure, $params, $rule)
100
    {
101 48
        if (@get_class($closure) === 'Closure') {
102 2
            $refl_func = new \ReflectionFunction($closure);
103 2
            $validation = $refl_func->invokeArgs($params);
104 46
        } else if (@method_exists(get_called_class(), $rule)) {
105 46
            $refl = new \ReflectionMethod(get_called_class(), $rule);
106 46
            if ($refl->isStatic()) {
107 46
                $refl->setAccessible(true);
108 46
                $validation = $refl->invokeArgs(null, $params);
109
            } else {
110 46
                throw new ValidooException(ValidooException::STATIC_METHOD, $rule);
111
            }
112
        } else {
113
            throw new ValidooException(ValidooException::UNKNOWN_RULE, $rule);
114
        }
115 48
        return $validation;
116
    }
117
118
    /**
119
     * Gets the parameter names of a rule
120
     * @param $rule
121
     * @return mixed
122
     */
123 48
    private static function getParams($rule)
124
    {
125 48
        if (preg_match("#^([\w]+)\((.+?)\)$#", $rule, $matches)) {
126
            return [
127 6
                'rule' => $matches[1],
128 6
                'params' => explode(',', $matches[2])
129
            ];
130
        }
131
        return [
132 42
            'rule' => $rule,
133
            'params' => []
134
        ];
135
    }
136
137
    /**
138
     * Handle parameter with input name
139
     * eg: equals(:name)
140
     * @param mixed $params
141
     * @param $inputs
142
     * @return mixed
143
     */
144 48
    private static function getParamValues($params, $inputs)
145
    {
146 48
        foreach ($params as $key => $param) {
147 6
            if (preg_match("#^:([\w]+)$#", $param, $param_type)) {
148 6
                $params[$key] = @$inputs[(string)$param_type[1]];
149
            }
150
        }
151 48
        return $params;
152
    }
153
154
    /**
155
     * @param null $input
156
     * @return bool
157
     */
158 9
    protected static function required($input = null): bool
159
    {
160 9
        return (null !== $input && (trim($input) != ''));
161
    }
162
163
    /**
164
     * @param $input
165
     * @return bool
166
     */
167
    protected static function numeric($input): bool
168
    {
169
        return is_numeric($input);
170
    }
171
172
    /**
173
     * @param $input
174
     * @return bool
175
     */
176 4
    protected static function email($input): bool
177
    {
178 4
        return filter_var($input, FILTER_VALIDATE_EMAIL);
179
    }
180
181
    /**
182
     * @param $input
183
     * @return bool
184
     */
185 2
    protected static function isdir($input): bool
186
    {
187 2
        return is_dir($input);
188
    }
189
190
    /**
191
     * @param $input
192
     * @return bool
193
     */
194
    protected static function isarray($input): bool
195
    {
196
        return is_array($input);
197
    }
198
199
    /**
200
     * @param $input
201
     * @return bool
202
     */
203 11
    protected static function integer($input): bool
204
    {
205 11
        return is_int($input) || ($input == (string)(int)$input);
206
    }
207
208
    /**
209
     * @param $input
210
     * @return bool
211
     */
212
    protected static function float($input): bool
213
    {
214
        return is_float($input) || ($input == (string)(float)$input);
215
    }
216
217
    /**
218
     * @param $input
219
     * @return bool
220
     */
221 4
    protected static function alpha($input): bool
222
    {
223 4
        return (preg_match("#^[a-zA-ZÀ-ÿ]+$#", $input) == 1);
224
    }
225
226
    /**
227
     * @param $input
228
     * @return bool
229
     */
230
    protected static function alpha_numeric($input): bool
0 ignored issues
show
Coding Style introduced by
Method name "Validator::alpha_numeric" is not in camel caps format
Loading history...
231
    {
232
        return (preg_match("#^[a-zA-ZÀ-ÿ0-9]+$#", $input) == 1);
233
    }
234
235
    /**
236
     * @param $input
237
     * @return bool
238
     */
239 4
    protected static function ip($input): bool
240
    {
241 4
        return filter_var($input, FILTER_VALIDATE_IP);
242
    }
243
244
    /**
245
     * @param $input
246
     * @return bool
247
     */
248 9
    protected static function url($input): bool
249
    {
250 9
        return filter_var($input, FILTER_VALIDATE_URL);
251
    }
252
253
    /**
254
     * @param $input
255
     * @param $length
256
     * @return bool
257
     */
258
    protected static function max_length($input, $length): bool
0 ignored issues
show
Coding Style introduced by
Method name "Validator::max_length" is not in camel caps format
Loading history...
259
    {
260
        return (strlen($input) <= $length);
261
    }
262
263
    /**
264
     * @param $input
265
     * @param $length
266
     * @return bool
267
     */
268
    protected static function min_length($input, $length): bool
0 ignored issues
show
Coding Style introduced by
Method name "Validator::min_length" is not in camel caps format
Loading history...
269
    {
270
        return (strlen($input) >= $length);
271
    }
272
273
    /**
274
     * @param $input
275
     * @param $length
276
     * @return bool
277
     */
278
    protected static function exact_length($input, $length): bool
0 ignored issues
show
Coding Style introduced by
Method name "Validator::exact_length" is not in camel caps format
Loading history...
279
    {
280
        return (strlen($input) == $length);
281
    }
282
283
    /**
284
     * @param $input
285
     * @param $param
286
     * @return bool
287
     */
288 4
    protected static function equals($input, $param): bool
289
    {
290 4
        return ($input == $param);
291
    }
292
293
    /**
294
     * @param $input
295
     * @return bool
296
     */
297
    protected static function is_filename($input): bool
0 ignored issues
show
Coding Style introduced by
Method name "Validator::is_filename" is not in camel caps format
Loading history...
298
    {
299
        return preg_match('/^[A-Za-z0-9-_]+[.]{1}[A-Za-z]+$/', $input);
300
    }
301
302
    /**
303
     * @return bool
304
     */
305 46
    public function isSuccess()
306
    {
307 46
        return empty($this->errors);
308
    }
309
310
    /**
311
     * @param array $errors_array
312
     */
313 1
    public function customErrors(array $errors_array)
314
    {
315 1
        foreach ($errors_array as $key => $value) {
316
            // handle input.rule eg (name.required)
317 1
            if (preg_match("#^(.+?)\.(.+?)$#", $key, $matches)) {
318
                // $this->customErrorsWithInputName[name][required] = error message
319
                $this->customErrorsWithInputName[(string)$matches[1]][(string)$matches[2]] = $value;
320
            } else {
321 1
                $this->customErrors[(string)$key] = $value;
322
            }
323
        }
324 1
    }
325
326
    /**
327
     * @param string|null $lang
328
     * @return array
329
     * @throws ValidooException
330
     */
331 3
    public function getErrors(string $lang = null): array
332
    {
333 3
        if (null === $lang) {
334 3
            $lang = $this->getDefaultLang();
335
        }
336
337 3
        $error_results = [];
338 3
        $default_error_texts = $this->getDefaultErrorTexts($lang);
339
340 3
        foreach ($this->errors as $input_name => $results) {
341 3
            foreach ($results as $rule => $result) {
342 3
                $named_input = $this->handleNaming($input_name);
343
                /**
344
                 * if parameters are input name they should be named as well
345
                 */
346 3
                $result['params'] = $this->handleParameterNaming($result['params']);
347
                // if there is a custom message with input name, apply it
348 3
                if (isset($this->customErrorsWithInputName[(string)$input_name][(string)$rule])) {
349
                    $error_message = $this->customErrorsWithInputName[(string)$input_name][(string)$rule];
350
                } // if there is a custom message for the rule, apply it
351 3
                else if (isset($this->customErrors[(string)$rule])) {
352 1
                    $error_message = $this->customErrors[(string)$rule];
353
                } // if there is a custom validator try to fetch from its error file
354 2
                else if (isset($custom_error_texts[(string)$rule])) {
355
                    $error_message = $custom_error_texts[(string)$rule];
356
                } // if none try to fetch from default error file
357 2
                else if (isset($default_error_texts[(string)$rule])) {
358 2
                    $error_message = $default_error_texts[(string)$rule];
359
                } else {
360
                    throw new ValidooException(ValidooException::NO_ERROR_TEXT, $rule);
361
                }
362
                /**
363
                 * handle :params(..)
364
                 */
365 3
                if (preg_match_all("#:params\((.+?)\)#", $error_message, $param_indexes)) {
366 1
                    foreach ($param_indexes[1] as $param_index) {
367 1
                        $error_message = str_replace(':params(' . $param_index . ')', $result['params'][$param_index], $error_message);
368
                    }
369
                }
370 3
                $error_results[] = str_replace(':attribute', $named_input, $error_message);
371
            }
372
        }
373
374 3
        return $error_results;
375
    }
376
377
    /**
378
     * @return string
379
     */
380 3
    protected function getDefaultLang(): string
381
    {
382 3
        return 'en';
383
    }
384
385
    /*
386
     * TODO: need improvements for tel and urn urls.
387
     * check out url.test.php for the test result
388
     * urn syntax: http://www.faqs.org/rfcs/rfc2141.html
389
     *
390
     */
391
392
    /**
393
     * @param string|null $lang
394
     * @return array|mixed
395
     */
396 3
    protected function getDefaultErrorTexts(string $lang = null)
397
    {
398
        /* handle default error text file */
399 3
        $default_error_texts = [];
400 3
        if (file_exists(__DIR__ . '/errors/' . $lang . '.php')) {
401
            /** @noinspection PhpIncludeInspection */
402 3
            $default_error_texts = include __DIR__ . '/errors/' . $lang . '.php';
403
        }
404 3
        if (file_exists(__DIR__ . '/errors/' . $lang . '.json')) {
405
            $default_error_texts = json_decode(file_get_contents(__DIR__ . '/errors/' . $lang . '.json'), true);
406
        }
407
408
409 3
        return $default_error_texts;
410
    }
411
412
    /**
413
     * @param string $input_name
414
     * @return mixed|string
415
     */
416 3
    protected function handleNaming(string $input_name)
417
    {
418 3
        if (isset($this->namings[$input_name])) {
419
            $named_input = $this->namings[$input_name];
420
        } else {
421 3
            $named_input = $input_name;
422
        }
423
424 3
        return $named_input;
425
    }
426
427
    /**
428
     * @param array $params
429
     * @return array
430
     */
431 3
    protected function handleParameterNaming(array $params)
432
    {
433 3
        foreach ($params as $key => $param) {
434 1
            if (preg_match("#^:([\w]+)$#", $param, $param_type)) {
435 1
                if (isset($this->namings[(string)$param_type[1]])) {
436 1
                    $params[$key] = $this->namings[(string)$param_type[1]];
437
                } else {
438 1
                    $params[$key] = $param_type[1];
439
                }
440
            }
441
        }
442
443 3
        return $params;
444
    }
445
446
    /**
447
     * @param string $input_name
448
     * @param string|null $rule_name
449
     * @return bool
450
     */
451
    public function has(string $input_name, string $rule_name = null): bool
452
    {
453
        if (null !== $rule_name) {
454
            return isset($this->errors[$input_name][$rule_name]);
455
        }
456
457
        return isset($this->errors[$input_name]);
458
    }
459
460
    /**
461
     * @return array
462
     */
463
    final public function getResults(): array
464
    {
465
        return $this->errors;
466
    }
467
}
468