|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Dice\Extra; |
|
4
|
|
|
|
|
5
|
|
|
class RuleValidator |
|
6
|
|
|
{ |
|
7
|
|
|
private $dice; |
|
8
|
|
|
|
|
9
|
|
|
public function __construct(\Dice\Dice $dice) |
|
10
|
|
|
{ |
|
11
|
|
|
$this->dice = $dice; |
|
12
|
|
|
} |
|
13
|
|
|
|
|
14
|
|
|
public function addRule($name, array $rule) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->checkValidKeys($rule); |
|
17
|
|
|
$this->checkBoolean($rule, 'inherit'); |
|
18
|
|
|
$this->checkBoolean($rule, 'shared'); |
|
19
|
|
|
$this->checkNumericArray($rule, 'constructParams'); |
|
20
|
|
|
$this->checkNumericArray($rule, 'shareInstances'); |
|
21
|
|
|
$this->checkNumericArray($rule, 'call'); |
|
22
|
|
|
|
|
23
|
|
|
$this->dice->addRule($name, $rule); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function create($name, array $args = [], array $share = []) |
|
27
|
|
|
{ |
|
28
|
|
|
return $this->dice->create($name, $args, $share); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function checkAssocArray($rule, $key) |
|
32
|
|
|
{ |
|
33
|
|
|
if (!isset($rule[$key])) { |
|
34
|
|
|
return; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if (count(array_filter(array_keys($rule[$key]), 'is_string')) === 0) { |
|
38
|
|
|
throw new \InvalidArgumentException('Rule option ' . $key . ' must be a an associative array'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function checkBoolean($rule, $key) |
|
44
|
|
|
{ |
|
45
|
|
|
if (!isset($rule[$key])) { |
|
46
|
|
|
return; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
if (!is_bool($rule[$key])) { |
|
50
|
|
|
throw new \InvalidArgumentException('Rule option ' . $key . ' must be true or false'); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function checkNumericArray($rule, $key) |
|
55
|
|
|
{ |
|
56
|
|
|
if (!isset($rule[$key])) { |
|
57
|
|
|
return; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
if (count(array_filter(array_keys($rule[$key]), 'is_string')) > 0) { |
|
61
|
|
|
throw new \InvalidArgumentException('Rule option ' . $key |
|
62
|
|
|
. ' must be a sequential array, not an associative array'); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function checkValidKeys($rule) |
|
67
|
|
|
{ |
|
68
|
|
|
$validKeys = ['call', 'shared', 'substitutions', 'instanceOf', 'inherit', 'shareInstances', 'constructParams']; |
|
69
|
|
|
|
|
70
|
|
|
foreach ($rule as $name => $value) { |
|
71
|
|
|
if (!in_array($name, $validKeys)) { |
|
72
|
|
|
throw new \InvalidArgumentException('Invalid rule option: ' . $name); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|