|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Kontrolio\Rules; |
|
4
|
|
|
|
|
5
|
|
|
use ReflectionException; |
|
6
|
|
|
use UnexpectedValueException; |
|
7
|
|
|
|
|
8
|
|
|
final class Repository |
|
9
|
|
|
{ |
|
10
|
|
|
private $rules = []; |
|
11
|
|
|
private $instantiator; |
|
12
|
|
|
|
|
13
|
|
|
public function __construct(Instantiator $instantiator, array $rules = []) |
|
14
|
|
|
{ |
|
15
|
|
|
$this->instantiator = $instantiator; |
|
16
|
|
|
$this->add($rules); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function all() |
|
20
|
|
|
{ |
|
21
|
|
|
return $this->rules; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Creates a new rule instance by the given name and arguments. |
|
26
|
|
|
* |
|
27
|
|
|
* Example: |
|
28
|
|
|
* $rule = $rules->make('equal_to', ['foo']); |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $name |
|
31
|
|
|
* @param array $arguments |
|
32
|
|
|
* |
|
33
|
|
|
* @return RuleInterface|object |
|
34
|
|
|
* @throws ReflectionException |
|
35
|
|
|
*/ |
|
36
|
|
|
public function make($name, array $arguments) |
|
37
|
|
|
{ |
|
38
|
|
|
return $this->instantiator->makeWithArgs($this->get($name), $arguments); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function has($name) |
|
42
|
|
|
{ |
|
43
|
|
|
return array_key_exists($name, $this->rules); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Returns rule class name if it exists. |
|
48
|
|
|
* |
|
49
|
|
|
* @param string $name |
|
50
|
|
|
* |
|
51
|
|
|
* @return string |
|
52
|
|
|
* @throws UnexpectedValueException |
|
53
|
|
|
*/ |
|
54
|
|
|
public function get($name) |
|
55
|
|
|
{ |
|
56
|
|
|
if ($this->has($name)) { |
|
57
|
|
|
return $this->rules[$name]; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
throw new UnexpectedValueException( |
|
61
|
|
|
sprintf('Rule identified by `%s` could not be loaded.', $name) |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Appends the given rule class names to the repository. |
|
67
|
|
|
* |
|
68
|
|
|
* @param array $rules |
|
69
|
|
|
* |
|
70
|
|
|
* @return $this |
|
71
|
|
|
*/ |
|
72
|
|
|
public function add(array $rules) |
|
73
|
|
|
{ |
|
74
|
|
|
$mapped = array_combine($this->getRuleNames($rules), array_values($rules)); |
|
75
|
|
|
|
|
76
|
|
|
$this->rules = array_merge($this->rules, $mapped); |
|
77
|
|
|
|
|
78
|
|
|
return $this; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
private function getRuleNames(array $rules) |
|
82
|
|
|
{ |
|
83
|
|
|
return array_map(function ($key) use ($rules) { |
|
84
|
|
|
return is_int($key) ? $this->instantiator->make($rules[$key])->getName() : $key; |
|
85
|
|
|
}, array_keys($rules)); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|