Passed
Pull Request — master (#26)
by Jitendra
02:07
created

Extension::resolveSubClassOrNullable()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 4
nop 2
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
        $allowsNull = $dependency->allowsNull();
127
128
        // Is a class and needs to be resolved OR is nullable.
129
        if ($dependency->getClass() || $allowsNull) {
130
            return $this->resolveSubClassOrNullable($dependency->getClass(), $allowsNull);
131
        }
132
133
        // Use default value.
134
        if ($dependency->isOptional()) {
135
            return $dependency->getDefaultValue();
136
        }
137
138
        throw new \RuntimeException('Cannot resolve dependency: $' . $dependency->name);
139
    }
140
141
    /**
142
     * Resolve subClass or nullable
143
     *
144
     * @param mixed $subClass
145
     * @param bool  $allowsNull
146
     *
147
     * @return mixed
148
     */
149
    protected function resolveSubClassOrNullable($subClass = null, bool $allowsNull = false)
150
    {
151
        if (!$subClass && $allowsNull) {
152
            return null;
153
        }
154
155
        try {
156
            return $this->resolve($subClass->name);
157
        } catch (\Throwable $e) {
158
            if (!$allowsNull) {
159
                throw $e;
160
            }
161
        }
162
163
        return null;
164
    }
165
166
    /**
167
     * Replace services with another one. Great for test mocks.
168
     *
169
     * @param array $services
170
     *
171
     * @return self
172
     */
173
    public function replace(array $services): self
174
    {
175
        foreach ($services as $name => $definition) {
176
            if ($this->has($name)) {
177
                $this->original[$name] = $this->get($name);
178
                $this->remove($name);
179
            }
180
181
            $this->set($name, $definition);
182
        }
183
184
        return $this;
185
    }
186
187
    /**
188
     * Restore given service or all.
189
     *
190
     * @param array|null $name
191
     *
192
     * @return self
193
     */
194
    public function restore(array $names = null): self
195
    {
196
        foreach ($names ?? \array_keys($this->original) as $name) {
197
            if ($this->has($name)) {
198
                $this->remove($name);
199
                $this->set($name, $this->original[$name], true);
200
            }
201
202
            unset($this->original[$name]);
203
        }
204
205
        return $this;
206
    }
207
208
    /**
209
     * Register aliases for services.
210
     *
211
     * @param array $aliases
212
     *
213
     * @return self
214
     */
215
    public function registerAliases(array $aliases = []): self
216
    {
217
        $this->aliases += $aliases;
218
219
        foreach ($this->_services as $name => $service) {
220
            if ('' !== $alias = $this->inferAlias($service->getDefinition())) {
221
                $this->aliases[$alias] = $name;
222
            }
223
        }
224
225
        return $this;
226
    }
227
228
    /**
229
     * Infer alias of service definition.
230
     *
231
     * @param mixed $definition
232
     *
233
     * @return string
234
     */
235
    protected function inferAlias($definition): string
236
    {
237
        if (\is_object($definition) && !$definition instanceof \Closure) {
238
            return \get_class($definition);
239
        }
240
241
        return \is_string($definition) ? $definition : '';
242
    }
243
}
244