Test Failed
Push — main ( 8691b6...f23361 )
by Chema
03:47 queued 14s
created

Container::callableKey()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
nc 5
nop 1
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 5
rs 9.6111
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Container;
6
7
use Closure;
8
use Gacela\Container\Exception\ContainerException;
9
use InvalidArgumentException;
10
11
use SplObjectStorage;
12
13
use function count;
14
use function get_class;
15
use function is_array;
16
use function is_callable;
17
use function is_object;
18
use function is_string;
19
20
class Container implements ContainerInterface
21
{
22
    private ?DependencyResolver $dependencyResolver = null;
23
24
    /** @var array<class-string|string, list<mixed>> */
25
    private array $cachedDependencies = [];
26
27
    /** @var array<string,mixed> */
28
    private array $instances = [];
29
30
    private SplObjectStorage $factoryInstances;
31
32
    private SplObjectStorage $protectedInstances;
33
34
    /** @var array<string,bool> */
35
    private array $frozenInstances = [];
36
37
    private ?string $currentlyExtending = null;
38
39
    /**
40 42
     * @param  array<class-string, class-string|callable|object>  $bindings
41
     * @param  array<string, list<Closure>>  $instancesToExtend
42
     */
43
    public function __construct(
44 42
        private array $bindings = [],
45 42
        private array $instancesToExtend = [],
46
    ) {
47
        $this->factoryInstances = new SplObjectStorage();
48
        $this->protectedInstances = new SplObjectStorage();
49
    }
50
51 5
    /**
52
     * @param  class-string  $className
53 5
     */
54
    public static function create(string $className): mixed
55
    {
56 37
        return (new self())->get($className);
57
    }
58 37
59
    public function has(string $id): bool
60
    {
61 19
        return isset($this->instances[$id]);
62
    }
63 19
64 1
    public function set(string $id, mixed $instance): void
65
    {
66
        if (!empty($this->frozenInstances[$id])) {
67 19
            throw ContainerException::frozenInstanceOverride($id);
68
        }
69 19
70 3
        $this->instances[$id] = $instance;
71
72
        if ($this->currentlyExtending === $id) {
73 19
            return;
74
        }
75
76
        $this->extendService($id);
77
    }
78
79 33
    /**
80
     * @param  class-string|string  $id
81 33
     */
82 15
    public function get(string $id): mixed
83
    {
84
        if ($this->has($id)) {
85 18
            return $this->getInstance($id);
86
        }
87
88 5
        return $this->createInstance($id);
89
    }
90 5
91 5
    public function resolve(callable $callable): mixed
92 5
    {
93
        $callableKey = $this->callableKey($callable);
94 5
        $callable = Closure::fromCallable($callable);
95 5
96 5
        if (!isset($this->cachedDependencies[$callableKey])) {
97 5
            $this->cachedDependencies[$callableKey] = $this
98
                ->getDependencyResolver()
99
                ->resolveDependencies($callable);
100
        }
101 5
102
        /** @psalm-suppress MixedMethodCall */
103
        return $callable(...$this->cachedDependencies[$callableKey]);
104 1
    }
105
106 1
    public function factory(Closure $instance): Closure
107
    {
108 1
        $this->factoryInstances->attach($instance);
109
110
        return $instance;
111 1
    }
112
113 1
    public function remove(string $id): void
114 1
    {
115 1
        unset(
116 1
            $this->instances[$id],
117
            $this->frozenInstances[$id],
118
        );
119
    }
120
121
    /**
122 11
     * @psalm-suppress MixedAssignment
123
     */
124 11
    public function extend(string $id, Closure $instance): Closure
125 4
    {
126
        if (!$this->has($id)) {
127 4
            $this->extendLater($id, $instance);
128
129
            return $instance;
130 10
        }
131 4
132
        if (isset($this->frozenInstances[$id])) {
133
            throw ContainerException::frozenInstanceExtend($id);
134 8
        }
135 1
136
        if (is_object($this->instances[$id]) && isset($this->protectedInstances[$this->instances[$id]])) {
137
            throw ContainerException::instanceProtected($id);
138 7
        }
139 7
140 6
        $factory = $this->instances[$id];
141
        $extended = $this->generateExtendedInstance($instance, $factory);
142 6
        $this->set($id, $extended);
143
144
        return $extended;
145 2
    }
146
147 2
    public function protect(Closure $instance): Closure
148
    {
149 2
        $this->protectedInstances->attach($instance);
150
151
        return $instance;
152 15
    }
153
154 15
    private function getInstance(string $id): mixed
155
    {
156 15
        $this->frozenInstances[$id] = true;
157 14
158 15
        if (!is_object($this->instances[$id])
159
            || isset($this->protectedInstances[$this->instances[$id]])
160 8
            || !method_exists($this->instances[$id], '__invoke')
161
        ) {
162
            return $this->instances[$id];
163 12
        }
164 1
165
        if (isset($this->factoryInstances[$this->instances[$id]])) {
166
            return $this->instances[$id]($this);
167 11
        }
168
169
        $rawService = $this->instances[$id];
170 11
171
        /** @var mixed $resolvedService */
172 11
        $resolvedService = $rawService($this);
173
174 11
        $this->instances[$id] = $resolvedService;
175
176
        return $resolvedService;
177 18
    }
178
179 18
    private function createInstance(string $class): ?object
180 4
    {
181 4
        if (isset($this->bindings[$class])) {
182
            $binding = $this->bindings[$class];
183 2
            if (is_callable($binding)) {
184
                /** @var mixed $binding */
185 4
                $binding = $binding();
186 2
            }
187
            if (is_object($binding)) {
188
                return $binding;
189
            }
190 2
191 2
            /** @var class-string $binding */
192
            if (class_exists($binding)) {
193
                return $this->instantiateClass($binding);
194
            }
195 14
        }
196 10
197
        if (class_exists($class)) {
198
            return $this->instantiateClass($class);
199 4
        }
200
201
        return null;
202
    }
203
204
    /**
205 12
     * @param  class-string  $class
206
     */
207 12
    private function instantiateClass(string $class): ?object
208 12
    {
209 12
        if (class_exists($class)) {
210 12
            if (!isset($this->cachedDependencies[$class])) {
211 12
                $this->cachedDependencies[$class] = $this
212
                    ->getDependencyResolver()
213
                    ->resolveDependencies($class);
214
            }
215 12
216
            /** @psalm-suppress MixedMethodCall */
217
            return new $class(...$this->cachedDependencies[$class]);
218
        }
219
220
        return null;
221 4
    }
222
223 4
    private function extendLater(string $id, Closure $instance): void
224
    {
225
        $this->instancesToExtend[$id][] = $instance;
226 17
    }
227
228 17
    private function getDependencyResolver(): DependencyResolver
229 17
    {
230 17
        if ($this->dependencyResolver === null) {
231 17
            $this->dependencyResolver = new DependencyResolver(
232
                $this->bindings,
233
            );
234 17
        }
235
236
        return $this->dependencyResolver;
237
    }
238
239
    /**
240 7
     * Generates a unique string key for a given callable.
241
     *
242 7
     * @psalm-suppress MixedReturnTypeCoercion
243 5
     */
244 5
    private function callableKey(callable $callable): string
245
    {
246 5
        if (is_array($callable)) {
247 5
            [$classOrObject, $method] = $callable;
248
249
            $className = is_object($classOrObject)
250 4
                ? get_class($classOrObject)
251 3
                : $classOrObject;
252
253
            return $className . '::' . $method;
254 1
        }
255
256
        if (is_string($callable)) {
257 19
            return $callable;
258
        }
259 19
260 16
        if ($callable instanceof Closure) {
261
            return spl_object_hash($callable);
262 3
        }
263
264 3
        throw new InvalidArgumentException('Unsupported callable type');
265 3
    }
266
267
    /**
268 3
     * @psalm-suppress MissingClosureReturnType,MixedAssignment
269 3
     */
270
    private function generateExtendedInstance(Closure $instance, mixed $factory): Closure
271
    {
272
        if (is_callable($factory)) {
273
            return static function (self $container) use ($instance, $factory) {
274
                $result = $factory($container);
275
276
                return $instance($result, $container) ?? $result;
277
            };
278
        }
279
280
        if (is_object($factory) || is_array($factory)) {
281
            return static fn (self $container) => $instance($factory, $container) ?? $factory;
282
        }
283
284
        throw ContainerException::instanceNotExtendable();
285
    }
286
287
    private function extendService(string $id): void
288
    {
289
        if (!isset($this->instancesToExtend[$id]) || count($this->instancesToExtend[$id]) === 0) {
290
            return;
291
        }
292
        $this->currentlyExtending = $id;
293
294
        foreach ($this->instancesToExtend[$id] as $instance) {
295
            $this->extend($id, $instance);
296
        }
297
298
        unset($this->instancesToExtend[$id]);
299
        $this->currentlyExtending = null;
300
    }
301
}
302