Completed
Push — master ( 50e551...f183e1 )
by Jitendra
11s
created

Extension::resolveDependency()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace PhalconExt\Di;
4
5
/**
6
 * An extension to phalcon di.
7
 *
8
 * @author  Jitendra Adhikari <[email protected]>
9
 * @license MIT
10
 *
11
 * @link    https://github.com/adhocore/phalcon-ext
12
 */
13
trait Extension
14
{
15
    /** @var array Names of services currently resolving */
16
    protected $resolving = [];
17
18
    /** @var array Original services backup */
19
    protected $original  = [];
20
21
    /** @var array The aliases of services */
22
    protected $aliases   = [];
23
24
    // Implemented by \Phalcon\Di.
25
    abstract public function set($service, $definition, $shared = false);
26
27
    abstract public function get($service, $parameters = null);
28
29
    abstract public function has($service);
30
31
    abstract public function remove($service);
32
33
    /**
34
     * Resolve all the dependencies for a class FQCN and instantiate it.
35
     *
36
     * @param string $class      FQCN
37
     * @param array  $parameters Parameters
38
     *
39
     * @return object
40
     */
41
    public function resolve(string $class, array $parameters = [])
42
    {
43
        if ($this->has($class)) {
44
            return $this->get($class, $parameters);
45
        }
46
47
        if ($this->aliases[$class] ?? null) {
48
            return $this->get($this->aliases[$class]);
49
        }
50
51
        if ($this->resolving[$class] ?? null) {
52
            throw new \RuntimeException('Cyclic dependency for class: ' . $class);
53
        }
54
55
        $this->resolving[$class] = true;
56
        $this->set($class, $resolved = $this->instantiate($class, $parameters), true);
57
        unset($this->resolving[$class]);
58
59
        return $resolved;
60
    }
61
62
    /**
63
     * Instantiate class FQCN by constructor injecting the dependencies from the DI.
64
     *
65
     * @param string $class      FQCN
66
     * @param array  $parameters Parameters
67
     *
68
     * @return object
69
     */
70
    protected function instantiate(string $class, array $parameters = [])
71
    {
72
        $reflector = new \ReflectionClass($class);
73
74
        if (!$reflector->isInstantiable()) {
75
            throw new \RuntimeException('Cannot instantiate class: ' . $class);
76
        }
77
78
        if ([] === $dependencies = $reflector->getConstructor()->getParameters()) {
79
            return $reflector->newInstance();
80
        }
81
82
        return $reflector->newInstanceArgs(
83
            $this->resolveDependencies($dependencies, $parameters)
84
        );
85
    }
86
87
    /**
88
     * Resolve dependencies of a class.
89
     *
90
     * @param array $dependencies
91
     * @param array $parameters
92
     *
93
     * @return mixed
94
     */
95
    protected function resolveDependencies(array $dependencies, array $parameters)
96
    {
97
        $resolved = [];
98
99
        foreach ($dependencies as $dependency) {
100
            $name = $dependency->name;
101
102
            // Already available in parameters.
103
            if (isset($parameters[$name])) {
104
                $resolved[] = $parameters[$name];
105
            }
106
            // Already registered in DI.
107
            elseif ($this->has($name)) {
108
                $resolved[] = $this->get($name);
109
            } else {
110
                $resolved[] = $this->resolveDependency($dependency);
111
            }
112
        }
113
114
        return $resolved;
115
    }
116
117
    /**
118
     * Resolve a dependency.
119
     *
120
     * @param \ReflectionParameter $dependency
121
     *
122
     * @return mixed
123
     */
124
    protected function resolveDependency(\ReflectionParameter $dependency)
125
    {
126
        // Is a class and needs to be resolved.
127
        if ($subClass = $dependency->getClass()) {
128
            return $this->resolve($subClass->name);
129
        }
130
        // Nullable
131
        elseif ($dependency->allowsNull()) {
132
            return null;
133
        }
134
        // Use default value.
135
        elseif ($dependency->isOptional()) {
136
            return $dependency->getDefaultValue();
137
        }
138
139
        throw new \RuntimeException('Cannot resolve dependency $' . $name);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $name seems to be never defined.
Loading history...
140
    }
141
142
    /**
143
     * Replace services with another one. Great for test mocks.
144
     *
145
     * @param array $services
146
     *
147
     * @return self
148
     */
149
    public function replace(array $services): self
150
    {
151
        foreach ($services as $name => $definition) {
152
            if ($this->has($name)) {
153
                $this->original[$name] = $this->get($name);
154
                $this->remove($name);
155
            }
156
157
            $this->set($name, $definition);
158
        }
159
160
        return $this;
161
    }
162
163
    /**
164
     * Restore given service or all.
165
     *
166
     * @param array|null $name
167
     *
168
     * @return self
169
     */
170
    public function restore(array $names = null): self
171
    {
172
        foreach ($names ?? \array_keys($this->original) as $name) {
173
            if ($this->has($name)) {
174
                $this->remove($name);
175
                $this->set($name, $this->original[$name], true);
176
            }
177
178
            unset($this->original[$name]);
179
        }
180
181
        return $this;
182
    }
183
184
    /**
185
     * Register aliases for services.
186
     *
187
     * @param array $aliases
188
     *
189
     * @return self
190
     */
191
    public function registerAliases(array $aliases = []): self
192
    {
193
        $this->aliases += $aliases;
194
195
        foreach ($this->_services as $name => $service) {
196
            $def   = $service->getDefinition();
197
            $isStr = \is_string($def);
198
199
            if ($isStr || (\is_object($def) && !$def instanceof \Closure)) {
200
                $alias                 = $isStr ? $def : \get_class($def);
201
                $this->aliases[$alias] = $name;
202
            }
203
        }
204
205
        return $this;
206
    }
207
}
208