Passed
Push — master ( 3d4557...4c2a8d )
by Hannes
01:54
created

Instantiator::getNewObject()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 19
rs 9.6111
cc 5
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace hanneskod\readmetester\Utils;
6
7
use Psr\Container\ContainerInterface;
8
9
class Instantiator implements ContainerInterface
10
{
11
    /** @var array<string, object> */
12
    private array $cache = [];
13
14
     /**
15
      * Implements ContainerInterface
16
      *
17
      * @param string $id
18
      * @return object
19
      */
20
    public function get($id)
21
    {
22
        return $this->getSharedObject($id);
23
    }
24
25
    /**
26
     * Implements ContainerInterface
27
     *
28
     * @param string $id
29
     * @return boolean
30
     */
31
    public function has($id)
32
    {
33
        return isset($this->cache[$id]);
34
    }
35
36
    public function getNewObject(string $classname): object
37
    {
38
        if (!class_exists($classname)) {
39
            throw new \RuntimeException("Class '$classname' does not exist");
40
        }
41
42
        $reflector = new \ReflectionClass($classname);
43
44
        if (!$reflector->isInstantiable()) {
45
            throw new \RuntimeException("Unable to instantiate non-instantiable class '$classname'");
46
        }
47
48
        $constructor = $reflector->getConstructor();
49
50
        if ($constructor && $constructor->getNumberOfRequiredParameters()) {
51
            throw new \RuntimeException("Unable to instantiate '$classname' with no parameters");
52
        }
53
54
        return new $classname();
55
    }
56
57
    public function getSharedObject(string $classname): object
58
    {
59
        if (!isset($this->cache[$classname])) {
60
            $this->cache[$classname] = $this->getNewObject($classname);
61
        }
62
63
        return $this->cache[$classname];
64
    }
65
}
66