Completed
Push — master ( e66c58...0a0a0f )
by Daniel
9s
created

Registry::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid;
6
7
class Registry
8
{
9
    private $context;
10
    private $class;
11
    private $instances = [];
12
    private $aliases = [];
13
14
    public function __construct(string $class, string $context)
15
    {
16
        $this->class = $class;
17
        $this->context = $context;
18
    }
19
20
    public function register($instance, $alias = null)
21
    {
22
        if (!is_object($instance)) {
23
            throw new \InvalidArgumentException(sprintf(
24
                'Expected an object, but got an "%s".',
25
                gettype($instance)
26
            ));
27
        }
28
29
        if (false === $instance instanceof $this->class) {
30
            throw new \InvalidArgumentException(sprintf(
31
                'Expected an instance of "%s", but got "%s"',
32
                $this->class, get_class($instance)
33
            ));
34
        }
35
36
        $classFqn = get_class($instance);
37
38
        if (isset($this->instances[$classFqn])) {
39
            throw new \InvalidArgumentException(sprintf(
40
                '%s "%s" has already been registered',
41
                $this->context, $classFqn
42
            ));
43
        }
44
45
        $this->instances[$classFqn] = $instance;
46
47
        if (null !== $alias) {
48
            if (isset($this->aliases[$alias])) {
49
                throw new \InvalidArgumentException(sprintf(
50
                    'Alias "%s" has already been set to "%s"',
51
                    $alias, $this->aliases[$alias]
52
                ));
53
            }
54
55
            $this->aliases[$alias] = $classFqn;
56
        }
57
    }
58
59
    public function get(string $classFqn)
60
    {
61
        if (isset($this->aliases[$classFqn])) {
62
            $classFqn = $this->aliases[$classFqn];
63
        }
64
65
        if (!isset($this->instances[$classFqn])) {
66
            throw new \InvalidArgumentException(sprintf(
67
                '%s with name "%s" was not found. Known %s types: "%s", aliases: "%s"',
68
                $this->context,
69
                $classFqn,
70
                $this->context,
71
                implode('", "', array_keys($this->instances)),
72
                implode('", "', array_keys($this->aliases))
73
            ));
74
        }
75
76
        return $this->instances[$classFqn];
77
    }
78
79
    public function has(string $classFqn)
80
    {
81
        return isset($this->instances[$classFqn]) || isset($this->aliases[$classFqn]);
82
    }
83
}
84