1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace iamsaint\yml\helpers; |
4
|
|
|
|
5
|
|
|
use iamsaint\yml\exceptions\IncorrectRuleException; |
6
|
|
|
use iamsaint\yml\interfaces\Validator; |
7
|
|
|
use function is_array; |
8
|
|
|
use function is_string; |
9
|
|
|
use function count; |
10
|
|
|
use function class_exists; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class RuleHelper |
14
|
|
|
* @package iamsaint\yml\helpers |
15
|
|
|
*/ |
16
|
|
|
class RuleHelper |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param $rule |
21
|
|
|
* @throws IncorrectRuleException |
22
|
|
|
*/ |
23
|
|
|
private static function validateArray($rule): void |
24
|
|
|
{ |
25
|
|
|
if (!is_array($rule)) { |
26
|
|
|
throw new IncorrectRuleException('Rule must be array'); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param $rule |
32
|
|
|
* @throws IncorrectRuleException |
33
|
|
|
*/ |
34
|
|
|
private static function validateString($rule): void |
35
|
|
|
{ |
36
|
|
|
if (!is_string($rule[1])) { |
37
|
|
|
throw new IncorrectRuleException('Rule name must be a string'); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param $rule |
43
|
|
|
* @throws IncorrectRuleException |
44
|
|
|
*/ |
45
|
|
|
private static function validateDefined($rule):void |
46
|
|
|
{ |
47
|
|
|
if (count($rule) < 2) { |
48
|
|
|
throw new IncorrectRuleException('Rule is not defined'); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param $rule |
54
|
|
|
* @return string |
55
|
|
|
* @throws IncorrectRuleException |
56
|
|
|
*/ |
57
|
|
|
private static function getRuleClass($rule): string |
58
|
|
|
{ |
59
|
|
|
$class = '\\iamsaint\\yml\\validators\\'.$rule[1]; |
60
|
|
|
|
61
|
|
|
if (!class_exists($class)) { |
62
|
|
|
throw new IncorrectRuleException('Validator not found'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $class; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param $rule |
70
|
|
|
* @return bool |
71
|
|
|
* @throws IncorrectRuleException |
72
|
|
|
*/ |
73
|
|
|
private static function isValidRule($rule):bool |
74
|
|
|
{ |
75
|
|
|
self::validateArray($rule); |
76
|
|
|
self::validateDefined($rule); |
77
|
|
|
self::validateString($rule); |
78
|
|
|
|
79
|
|
|
return false; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param $object |
84
|
|
|
* @param $rule |
85
|
|
|
* @throws IncorrectRuleException |
86
|
|
|
*/ |
87
|
|
|
public static function validate($object, $rule): void |
88
|
|
|
{ |
89
|
|
|
if (self::isValidRule($rule)) { |
90
|
|
|
$ruleClass = self::getRuleClass($rule); |
91
|
|
|
|
92
|
|
|
$attributes = is_array($rule[0]) ? $rule[0] : [$rule[0]]; |
93
|
|
|
|
94
|
|
|
$validator = new $ruleClass(); |
95
|
|
|
|
96
|
|
|
if ($validator instanceof Validator) { |
97
|
|
|
$validator->validate($object, $attributes, $rule[2] ?: []); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|