AliasBinder::getAliases()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Sco\Admin\Traits;
4
5
use BadMethodCallException;
6
7
/**
8
 * Trait AliasBinder
9
 *
10
 * @package Sco\Admin\Traits
11
 */
12
trait AliasBinder
13
{
14
    /**
15
     * @var array
16
     */
17
    protected $aliases = [];
18
19
    /**
20
     * @param array $aliases
21
     * @return $this
22
     */
23
    public function register(array $aliases)
24
    {
25
        foreach ($aliases as $alias => $class) {
26
            $this->bind($alias, $class);
27
        }
28
29
        return $this;
30
    }
31
32
    /**
33
     * @param string $alias
34
     * @param $class
35
     * @return $this
36
     */
37
    public function bind(string $alias, $class)
38
    {
39
        $this->aliases[$alias] = $class;
40
41
        return $this;
42
    }
43
44
    /**
45
     * @return array
46
     */
47
    public function getAliases()
48
    {
49
        return $this->aliases;
50
    }
51
52
    /**
53
     * @param string $key
54
     * @return bool
55
     */
56
    public function getAlias(string $key)
57
    {
58
        return $this->aliases[$key] ?? false;
59
    }
60
61
    /**
62
     * Check if alias is registered.
63
     *
64
     * @param string $alias
65
     *
66
     * @return bool
67
     */
68
    public function hasAlias(string $alias)
69
    {
70
        return array_key_exists($alias, $this->aliases);
71
    }
72
73
    /**
74
     * @param string $alias
75
     * @param array $arguments
76
     * @return object
77
     * @throws \ErrorException
78
     * @throws \ReflectionException
79
     */
80
    protected function makeClass(string $alias, array $arguments)
81
    {
82
        $class = $this->getAlias($alias);
83
        $reflection = new \ReflectionClass($class);
84
        if ($reflection->isAbstract()) {
85
            throw new \ErrorException(
86
                sprintf(
87
                    'Cannot use %s, it is abstract class',
88
                    $class
89
                )
90
            );
91
        }
92
93
        return $reflection->newInstanceArgs($arguments);
94
    }
95
96
    public function __call($method, $parameters)
97
    {
98
        if (! $this->hasAlias($method)) {
99
            throw new BadMethodCallException("Not Found {$method}");
100
        }
101
102
        return $this->makeClass($method, $parameters);
103
    }
104
}
105