Completed
Push — master ( a97ce7...6f972b )
by Jan
03:17
created

Repository::getRuleNames()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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);
0 ignored issues
show
Bug introduced by
It seems like $mapped can also be of type false; however, parameter $array2 of array_merge() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
        $this->rules = array_merge($this->rules, /** @scrutinizer ignore-type */ $mapped);
Loading history...
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