Completed
Pull Request — master (#13)
by Jitendra
04:44 queued 02:55
created

Extension::resolveDependencies()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 10
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
            }
110
            else {
111
                $resolved[] = $this->resolveDependency($dependency);
112
            }
113
        }
114
115
        return $resolved;
116
    }
117
118
    /**
119
     * Resolve a dependency.
120
     *
121
     * @param \ReflectionParameter $dependency
122
     *
123
     * @return mixed
124
     */
125
    protected function resolveDependency(\ReflectionParameter $dependency)
126
    {
127
        // Is a class and needs to be resolved.
128
        if ($subClass = $dependency->getClass()) {
129
            return $this->resolve($subClass->name);
130
        }
131
        // Nullable
132
        elseif ($dependency->allowsNull()) {
133
            return null;
134
        }
135
        // Use default value.
136
        elseif ($dependency->isOptional()) {
137
            return $dependency->getDefaultValue();
138
        }
139
140
        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...
141
    }
142
143
144
    /**
145
     * Replace services with another one. Great for test mocks.
146
     *
147
     * @param array $services
148
     *
149
     * @return self
150
     */
151
    public function replace(array $services): self
152
    {
153
        foreach ($services as $name => $definition) {
154
            if ($this->has($name)) {
155
                $this->original[$name] = $this->get($name);
156
                $this->remove($name);
157
            }
158
159
            $this->set($name, $definition);
160
        }
161
162
        return $this;
163
    }
164
165
    /**
166
     * Restore given service or all.
167
     *
168
     * @param string|null $name
169
     *
170
     * @return self
171
     */
172
    public function restore(string $name = null): self
173
    {
174
        if ($name && empty($this->original[$name])) {
175
            return $this;
176
        }
177
178
        $names = $name ? [$name] : array_keys($this->original);
179
180
        foreach ($names as $name) {
181
            if (!$this->has($name)) {
182
                continue;
183
            }
184
185
            $this->remove($name);
186
            $this->set($name, $this->original[$name], true);
187
        }
188
189
        return $this;
190
    }
191
192
    /**
193
     * Register aliases for services.
194
     *
195
     * @param array $aliases
196
     *
197
     * @return self
198
     */
199
    public function registerAliases(array $aliases = []): self
200
    {
201
        $this->aliases += $aliases;
202
203
        foreach ($this->_services as $name => $service) {
204
            $def   = $service->getDefinition();
205
            $isStr = \is_string($def);
206
207
            if ($isStr || (\is_object($def) && !$def instanceof \Closure)) {
208
                $alias                 = $isStr ? $def : \get_class($def);
1 ignored issue
show
Bug introduced by
It seems like $def can also be of type string; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

208
                $alias                 = $isStr ? $def : \get_class(/** @scrutinizer ignore-type */ $def);
Loading history...
209
                $this->aliases[$alias] = $name;
210
            }
211
        }
212
213
        return $this;
214
    }
215
}
216