Instantiator::getSharedObject()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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