Completed
Push — master ( ad396b...f20507 )
by Alessandro
01:55
created

Validator::isdir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 11
    protected static function integer($input): bool
195
    {
196 11
        return is_int($input) || ($input == (string)(int)$input);
197
    }
198
199
    /**
200
     * @param $input
201
     * @return bool
202
     */
203
    protected static function float($input): bool
204
    {
205
        return is_float($input) || ($input == (string)(float)$input);
206
    }
207
208
    /**
209
     * @param $input
210
     * @return bool
211
     */
212 4
    protected static function alpha($input): bool
213
    {
214 4
        return (preg_match("#^[a-zA-ZÀ-ÿ]+$#", $input) == 1);
215
    }
216
217
    /**
218
     * @param $input
219
     * @return bool
220
     */
221
    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...
222
    {
223
        return (preg_match("#^[a-zA-ZÀ-ÿ0-9]+$#", $input) == 1);
224
    }
225
226
    /**
227
     * @param $input
228
     * @return bool
229
     */
230 4
    protected static function ip($input): bool
231
    {
232 4
        return filter_var($input, FILTER_VALIDATE_IP);
233
    }
234
235
    /**
236
     * @param $input
237
     * @return bool
238
     */
239 9
    protected static function url($input): bool
240
    {
241 9
        return filter_var($input, FILTER_VALIDATE_URL);
242
    }
243
244
    /**
245
     * @param $input
246
     * @param $length
247
     * @return bool
248
     */
249
    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...
250
    {
251
        return (strlen($input) <= $length);
252
    }
253
254
    /**
255
     * @param $input
256
     * @param $length
257
     * @return bool
258
     */
259
    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...
260
    {
261
        return (strlen($input) >= $length);
262
    }
263
264
    /**
265
     * @param $input
266
     * @param $length
267
     * @return bool
268
     */
269
    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...
270
    {
271
        return (strlen($input) == $length);
272
    }
273
274
    /**
275
     * @param $input
276
     * @param $param
277
     * @return bool
278
     */
279 4
    protected static function equals($input, $param): bool
280
    {
281 4
        return ($input == $param);
282
    }
283
284
    /**
285
     * @param $input
286
     * @return bool
287
     */
288
    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...
289
    {
290
        return preg_match('/^[A-Za-z0-9-_]+[.]{1}[A-Za-z]+$/', $input);
291
    }
292
293
    /**
294
     * @return bool
295
     */
296 46
    public function isSuccess()
297
    {
298 46
        return empty($this->errors);
299
    }
300
301
    /**
302
     * @param array $errors_array
303
     */
304 1
    public function customErrors(array $errors_array)
305
    {
306 1
        foreach ($errors_array as $key => $value) {
307
            // handle input.rule eg (name.required)
308 1
            if (preg_match("#^(.+?)\.(.+?)$#", $key, $matches)) {
309
                // $this->customErrorsWithInputName[name][required] = error message
310
                $this->customErrorsWithInputName[(string)$matches[1]][(string)$matches[2]] = $value;
311
            } else {
312 1
                $this->customErrors[(string)$key] = $value;
313
            }
314
        }
315 1
    }
316
317
    /**
318
     * @param string|null $lang
319
     * @return array
320
     * @throws ValidooException
321
     */
322 3
    public function getErrors(string $lang = null): array
323
    {
324 3
        if (null === $lang) {
325 3
            $lang = $this->getDefaultLang();
326
        }
327
328 3
        $error_results = [];
329 3
        $default_error_texts = $this->getDefaultErrorTexts($lang);
330
331 3
        foreach ($this->errors as $input_name => $results) {
332 3
            foreach ($results as $rule => $result) {
333 3
                $named_input = $this->handleNaming($input_name);
334
                /**
335
                 * if parameters are input name they should be named as well
336
                 */
337 3
                $result['params'] = $this->handleParameterNaming($result['params']);
338
                // if there is a custom message with input name, apply it
339 3
                if (isset($this->customErrorsWithInputName[(string)$input_name][(string)$rule])) {
340
                    $error_message = $this->customErrorsWithInputName[(string)$input_name][(string)$rule];
341
                } // if there is a custom message for the rule, apply it
342 3
                else if (isset($this->customErrors[(string)$rule])) {
343 1
                    $error_message = $this->customErrors[(string)$rule];
344
                } // if there is a custom validator try to fetch from its error file
345 2
                else if (isset($custom_error_texts[(string)$rule])) {
346
                    $error_message = $custom_error_texts[(string)$rule];
347
                } // if none try to fetch from default error file
348 2
                else if (isset($default_error_texts[(string)$rule])) {
349 2
                    $error_message = $default_error_texts[(string)$rule];
350
                } else {
351
                    throw new ValidooException(ValidooException::NO_ERROR_TEXT, $rule);
352
                }
353
                /**
354
                 * handle :params(..)
355
                 */
356 3
                if (preg_match_all("#:params\((.+?)\)#", $error_message, $param_indexes)) {
357 1
                    foreach ($param_indexes[1] as $param_index) {
358 1
                        $error_message = str_replace(':params(' . $param_index . ')', $result['params'][$param_index], $error_message);
359
                    }
360
                }
361 3
                $error_results[] = str_replace(':attribute', $named_input, $error_message);
362
            }
363
        }
364
365 3
        return $error_results;
366
    }
367
368
    /**
369
     * @return string
370
     */
371 3
    protected function getDefaultLang(): string
372
    {
373 3
        return 'en';
374
    }
375
376
    /*
377
     * TODO: need improvements for tel and urn urls.
378
     * check out url.test.php for the test result
379
     * urn syntax: http://www.faqs.org/rfcs/rfc2141.html
380
     *
381
     */
382
383
    /**
384
     * @param string|null $lang
385
     * @return array|mixed
386
     */
387 3
    protected function getDefaultErrorTexts(string $lang = null)
388
    {
389
        /* handle default error text file */
390 3
        $default_error_texts = [];
391 3
        if (file_exists(__DIR__ . '/errors/' . $lang . '.php')) {
392
            /** @noinspection PhpIncludeInspection */
393 3
            $default_error_texts = include __DIR__ . '/errors/' . $lang . '.php';
394
        }
395 3
        if (file_exists(__DIR__ . '/errors/' . $lang . '.json')) {
396
            $default_error_texts = json_decode(file_get_contents(__DIR__ . '/errors/' . $lang . '.json'), true);
397
        }
398
399
400 3
        return $default_error_texts;
401
    }
402
403
    /**
404
     * @param string $input_name
405
     * @return mixed|string
406
     */
407 3
    protected function handleNaming(string $input_name)
408
    {
409 3
        if (isset($this->namings[$input_name])) {
410
            $named_input = $this->namings[$input_name];
411
        } else {
412 3
            $named_input = $input_name;
413
        }
414
415 3
        return $named_input;
416
    }
417
418
    /**
419
     * @param array $params
420
     * @return array
421
     */
422 3
    protected function handleParameterNaming(array $params)
423
    {
424 3
        foreach ($params as $key => $param) {
425 1
            if (preg_match("#^:([\w]+)$#", $param, $param_type)) {
426 1
                if (isset($this->namings[(string)$param_type[1]])) {
427 1
                    $params[$key] = $this->namings[(string)$param_type[1]];
428
                } else {
429 1
                    $params[$key] = $param_type[1];
430
                }
431
            }
432
        }
433
434 3
        return $params;
435
    }
436
437
    /**
438
     * @param string $input_name
439
     * @param string|null $rule_name
440
     * @return bool
441
     */
442
    public function has(string $input_name, string $rule_name = null): bool
443
    {
444
        if (null !== $rule_name) {
445
            return isset($this->errors[$input_name][$rule_name]);
446
        }
447
448
        return isset($this->errors[$input_name]);
449
    }
450
451
    /**
452
     * @return array
453
     */
454
    final public function getResults(): array
455
    {
456
        return $this->errors;
457
    }
458
}
459