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