1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaravelPropertyBag\Settings\Rules; |
4
|
|
|
|
5
|
|
|
use LaravelPropertyBag\Helpers\NameResolver; |
6
|
|
|
use LaravelPropertyBag\Exceptions\InvalidSettingsRule; |
7
|
|
|
|
8
|
|
|
class RuleValidator |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Validate the value given for the rule. |
12
|
|
|
* |
13
|
|
|
* @param string $rule |
14
|
|
|
* @param mixed $value |
15
|
|
|
* |
16
|
|
|
* @throws InvalidSettingsRule |
17
|
|
|
* |
18
|
|
|
* @return bool |
19
|
|
|
*/ |
20
|
|
|
public function validate($rule, $value) |
21
|
|
|
{ |
22
|
|
|
$arguments = $this->buildArgumentArray($rule, $value); |
23
|
|
|
|
24
|
|
|
$method = $this->makeRuleMethod($rule); |
25
|
|
|
|
26
|
|
|
if ($this->userDefinedExists($method)) { |
27
|
|
|
$class = NameResolver::makeRulesFileName(); |
28
|
|
|
|
29
|
|
|
return call_user_func_array([$class, $method], $arguments); |
30
|
|
|
} elseif (method_exists(Rules::class, $method)) { |
31
|
|
|
return call_user_func_array([Rules::class, $method], $arguments); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
throw InvalidSettingsRule::ruleNotFound($rule, $method); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* String is a rule. |
39
|
|
|
* |
40
|
|
|
* @param string $string |
41
|
|
|
* |
42
|
|
|
* @return bool|string |
43
|
|
|
*/ |
44
|
|
|
public function isRule($string) |
45
|
|
|
{ |
46
|
|
|
if ($isRule = preg_match('/:(.*?):/', $string, $match)) { |
47
|
|
|
return $match[1]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return (bool) $isRule; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Make method name used to validate rule. |
55
|
|
|
* |
56
|
|
|
* @param string $rule |
57
|
|
|
* |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
|
|
protected function makeRuleMethod($rule) |
61
|
|
|
{ |
62
|
|
|
if (strpos($rule, '=') !== false) { |
63
|
|
|
$rule = explode('=', $rule)[0]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return 'rule'.ucfirst($rule); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* User defined rule method exists. |
71
|
|
|
* |
72
|
|
|
* @param string $method |
73
|
|
|
* |
74
|
|
|
* @return bool |
75
|
|
|
*/ |
76
|
|
|
protected function userDefinedExists($method) |
77
|
|
|
{ |
78
|
|
|
$userDefined = NameResolver::makeRulesFileName(); |
79
|
|
|
|
80
|
|
|
return class_exists($userDefined) && |
81
|
|
|
method_exists($userDefined, $method); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* Build argument array from rule and value. |
86
|
|
|
* |
87
|
|
|
* @param string $rule |
88
|
|
|
* @param mixed $value |
89
|
|
|
* |
90
|
|
|
* @return array |
91
|
|
|
*/ |
92
|
|
|
protected function buildArgumentArray($rule, $value) |
93
|
|
|
{ |
94
|
|
|
$argumentString = explode('=', $rule); |
95
|
|
|
|
96
|
|
|
$arguments = [$value]; |
97
|
|
|
|
98
|
|
|
if (isset($argumentString[1])) { |
99
|
|
|
return array_merge($arguments, explode(',', $argumentString[1])); |
100
|
|
|
} |
101
|
|
|
|
102
|
|
|
return $arguments; |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
|