AliasBinder   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
c 0
b 0
f 0
lcom 1
cbo 0
dl 0
loc 93
ccs 0
cts 45
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 8 2
A bind() 0 6 1
A getAliases() 0 4 1
A getAlias() 0 4 1
A hasAlias() 0 4 1
A makeClass() 0 15 2
A __call() 0 8 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