Instantiator::make()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Kontrolio\Rules;
4
5
use ReflectionClass;
6
use ReflectionException;
7
use UnexpectedValueException;
8
9
final class Instantiator
10
{
11
    /**
12
     * Returns new instance of a rule by the given class name.
13
     *
14
     * @param string $class
15
     *
16
     * @return object|RuleInterface
17
     * @throws UnexpectedValueException
18
     * @throws ReflectionException
19
     */
20
    public function make($class)
21
    {
22
        return $this->reflect($class)->newInstanceWithoutConstructor();
23
    }
24
25
    /**
26
     * Returns new instance of a rule by the given class name and arguments.
27
     *
28
     * @param string $class
29
     * @param array $arguments
30
     *
31
     * @return object|RuleInterface
32
     * @throws UnexpectedValueException
33
     * @throws ReflectionException
34
     */
35
    public function makeWithArgs($class, array $arguments = [])
36
    {
37
        return $this->reflect($class)->newInstanceArgs($arguments);
38
    }
39
40
    /**
41
     * Creates reflection object for the given class name.
42
     *
43
     * @param string $class
44
     *
45
     * @return ReflectionClass
46
     * @throws ReflectionException
47
     */
48
    private function reflect($class)
49
    {
50
        $obj = (new ReflectionClass($class));
51
52
        if (!$obj->isInstantiable()) {
53
            throw new UnexpectedValueException('Rule class must be instantiable.');
54
        }
55
56
        if (!$obj->implementsInterface(RuleInterface::class)) {
57
            throw new UnexpectedValueException(sprintf('Rule must implement %s.', RuleInterface::class));
58
        }
59
60
        return $obj;
61
    }
62
}
63