Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
99.25% covered (success)
99.25%
132 / 133
95.24% covered (success)
95.24%
20 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
ServiceProviderContainer
99.25% covered (success)
99.25%
132 / 133
95.24% covered (success)
95.24%
20 / 21
69
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 assertEntryIsNotResolving
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 restoreResolutionPath
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 resolveUncachedEntry
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 readProviderDefinitions
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 createExtendedService
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 inferredClassAlias
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 cacheResolvedService
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 hasEntry
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 applyServiceExtensions
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 applyIdentifierExtension
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 executeIdentifierExtension
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 applyConcreteClassExtension
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 completeClassExtensions
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 classExtensionResult
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 registeredClassExtensionResult
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 followClassExtensionResults
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 compressClassExtensionPath
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 rememberClassExtensionResult
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
5.02
1<?php
2
3declare(strict_types=1);
4
5/**
6 * This file is part of php-fast-forward/container.
7 *
8 * This source file is subject to the license bundled
9 * with this source code in the file LICENSE.
10 *
11 * @copyright Copyright (c) 2025-2026 Felipe SayĆ£o Lobato Abreu <github@mentordosnerds.com>
12 * @license   https://opensource.org/licenses/MIT MIT License
13 *
14 * @see       https://github.com/php-fast-forward/container
15 * @see       https://github.com/php-fast-forward
16 * @see       https://datatracker.ietf.org/doc/html/rfc2119
17 */
18
19namespace FastForward\Container;
20
21use Fiber;
22use Throwable;
23use WeakMap;
24use FastForward\Container\Exception\ContainerException;
25use FastForward\Container\Exception\NotFoundException;
26use FastForward\Container\Extension\ServiceExtension;
27use Interop\Container\ServiceProviderInterface;
28use Psr\Container\ContainerInterface as PsrContainerInterface;
29
30/**
31 * Implements a PSR-11 compliant dependency injection container using a container-interop/service-provider.
32 *
33 * This container SHALL resolve services by delegating to the factories and extensions defined in the
34 * provided ServiceProviderInterface instance.
35 *
36 * Services are lazily instantiated on first request and
37 * cached for subsequent retrieval, enforcing singleton-like behavior within the container scope.
38 *
39 * The container supports service extension mechanisms by allowing callable extensions to modify or
40 * enhance services after construction, based on the service identifier or its concrete class name.
41 *
42 * If an optional wrapper container is provided, it SHALL be passed to service factories and extensions,
43 * allowing for delegation or decoration of service resolution. If omitted, the container defaults to itself.
44 */
45 class ServiceProviderContainer implements ContainerInterface
46{
47    /**
48     * The container instance used for service resolution and extension application.
49     *
50     * This property MAY reference another container for delegation, or default to this container instance.
51     */
52    private  PsrContainerInterface $wrapperContainer;
53
54    /**
55     * Final class-extension values indexed by original and same-class resulting object identities.
56     *
57     * Weak keys permit discarded input objects to be collected after replacement.
58     * Wrapping values in an array distinguishes a cached null result from an absent entry.
59     *
60     * @var WeakMap<object, array{value: mixed}>|null
61     */
62    private ?WeakMap $classExtensionResults = null;
63
64    /**
65     * Cache of resolved services keyed by their identifier or class name.
66     *
67     * This array SHALL store already constructed services to enforce singleton-like behavior within the container scope.
68     *
69     * @var array<string, mixed>
70     */
71    private array $cache = [];
72
73    /**
74     * Active provider entries grouped by Fiber, or by wrapper in the main context.
75     *
76     * Provider identity permits ordered fallback to another source for the same ID.
77     * Completed resolutions remove their entries instead of retaining service graphs.
78     *
79     * @var WeakMap<object, list<array{container: self, id: string}>>|null
80     */
81    private static ?WeakMap $resolutionPaths = null;
82
83    /**
84     * Constructs a new ServiceProviderContainer instance.
85     *
86     * This constructor SHALL initialize the container with a service provider and an optional delegating container.
87     * If no wrapper container is provided, the container SHALL delegate to itself.
88     *
89     * @param ServiceProviderInterface $serviceProvider the service provider supplying factories and extensions
90     * @param PsrContainerInterface|null $wrapperContainer An optional container for delegation. Defaults to self.
91     */
92    public function __construct(
93        private  ServiceProviderInterface $serviceProvider,
94        ?PsrContainerInterface $wrapperContainer = null,
95    ) {
96        $this->wrapperContainer = $wrapperContainer ?? $this;
97    }
98
99    /**
100     * Determines if the container can return an entry for the given identifier.
101     *
102     * This method MUST return true for cached entries, callable factories, or callable ID-based extensions.
103     * It SHALL NOT execute factories or extensions to discover an entry.
104     *
105     * @param string $id identifier of the entry to look for
106     *
107     * @return bool true if the entry exists, false otherwise
108     *
109     * @throws ContainerException if provider metadata cannot be read
110     */
111    public function has(string $id): bool
112    {
113        if ($this->hasEntry($id)) {
114            return true;
115        }
116
117        try {
118            return $this->hasEntry($id, $this->serviceProvider->getFactories())
119                || $this->hasEntry($id, extensions: $this->serviceProvider->getExtensions());
120        } catch (Throwable $throwable) {
121            throw ContainerException::forInvalidService($id, $throwable);
122        }
123    }
124
125    /**
126     * Retrieves a service from the container by its identifier.
127     *
128     * This method SHALL return a cached instance if available, otherwise it resolves
129     * the service using the factory provided by the service provider.
130     *
131     * Extensions SHALL receive the previous value and may replace it. Without a factory,
132     * an ID-based extension receives null. The final value SHALL be cached, including null.
133     *
134     * @param string $id the identifier of the service to retrieve
135     *
136     * @return mixed the service instance associated with the identifier
137     *
138     * @throws NotFoundException if neither a callable factory nor an ID-based extension exists
139     * @throws ContainerException if factory or extension resolution fails or a dependency cycle exists
140     */
141    public function get(string $id): mixed
142    {
143        if (\array_key_exists($id, $this->cache)) {
144            return $this->cache[$id];
145        }
146
147        $context = Fiber::getCurrent() ?? $this->wrapperContainer;
148        $activePaths = self::$resolutionPaths ??= new WeakMap();
149        $previousPath = $activePaths[$context] ?? [];
150
151        $this->assertEntryIsNotResolving($id, $previousPath);
152
153        $currentEntry = [
154            'container' => $this,
155            'id' => $id,
156        ];
157        $activePaths[$context] = [...$previousPath, $currentEntry];
158
159        try {
160            return $this->resolveUncachedEntry($id);
161        } finally {
162            $this->restoreResolutionPath($activePaths, $context, $previousPath);
163        }
164    }
165
166    /**
167     * Rejects re-entry into this provider's active service while allowing ordered fallback to other providers.
168     *
169     * @param string $id the requested service identifier
170     * @param list<array{container: self, id: string}> $path the current execution context's active entries
171     *
172     * @return void
173     *
174     * @throws ContainerException if this provider is already resolving the same identifier
175     */
176    private function assertEntryIsNotResolving(string $id, array $path): void
177    {
178        foreach ($path as $entry) {
179            if ($entry['container'] === $this && $entry['id'] === $id) {
180                throw ContainerException::forCircularDependency([...array_column($path, 'id'), $id]);
181            }
182        }
183    }
184
185    /**
186     * Restores the caller's path after resolution or releases an empty execution context.
187     *
188     * @param WeakMap<object, list<array{container: self, id: string}>> $paths active paths by execution context
189     * @param object $context the current Fiber or main-context wrapper
190     * @param list<array{container: self, id: string}> $previousPath the path before this entry was resolved
191     *
192     * @return void
193     */
194    private function restoreResolutionPath(WeakMap $paths, object $context, array $previousPath): void
195    {
196        if ([] === $previousPath) {
197            unset($paths[$context]);
198
199            return;
200        }
201
202        $paths[$context] = $previousPath;
203    }
204
205    /**
206     * Resolves an entry once, preserving construction failures and the final cached value.
207     *
208     * @param string $id the requested service identifier
209     *
210     * @return mixed the fully extended service value
211     *
212     * @throws NotFoundException if neither a factory nor an ID extension can supply the entry
213     * @throws ContainerException if reading metadata or constructing the entry fails
214     */
215    private function resolveUncachedEntry(string $id): mixed
216    {
217        [$factories, $extensions] = $this->readProviderDefinitions($id);
218
219        $factory = $factories[$id] ?? null;
220
221        if (! \is_callable($factory) && ! \is_callable($extensions[$id] ?? null)) {
222            throw NotFoundException::forServiceID($id);
223        }
224
225        try {
226            $service = $this->createExtendedService($id, $factory, $extensions);
227            $alias = $this->inferredClassAlias($id, $service, $factories, $extensions);
228        } catch (Throwable $throwable) {
229            throw ContainerException::forInvalidService($id, $throwable);
230        }
231
232        return $this->cacheResolvedService($id, $service, $alias);
233    }
234
235    /**
236     * Reads factory and extension metadata in provider order without executing their callables.
237     *
238     * @param string $id the identifier used to report a metadata failure
239     *
240     * @return array{array<array-key, mixed>, array<array-key, mixed>} factories followed by extensions
241     *
242     * @throws ContainerException if provider metadata cannot be read
243     */
244    private function readProviderDefinitions(string $id): array
245    {
246        try {
247            return [$this->serviceProvider->getFactories(), $this->serviceProvider->getExtensions()];
248        } catch (Throwable $throwable) {
249            throw ContainerException::forInvalidService($id, $throwable);
250        }
251    }
252
253    /**
254     * Invokes an available factory and applies the entry's extensions to its value.
255     *
256     * @param string $id the requested service identifier
257     * @param mixed $factory the factory definition, which may be absent or non-callable
258     * @param array<array-key, mixed> $extensions the provider's extension definitions
259     *
260     * @return mixed the completed extension result, including null
261     */
262    private function createExtendedService(string $id, mixed $factory, array $extensions): mixed
263    {
264        $service = \is_callable($factory) ? $factory($this->wrapperContainer) : null;
265
266        return $this->applyServiceExtensions($id, $service, $extensions);
267    }
268
269    /**
270     * Infers a concrete-class alias only when it cannot replace another entry or definition.
271     *
272     * @param string $id the identifier being resolved
273     * @param mixed $service the completed service value
274     * @param array<array-key, mixed> $factories the provider's factory definitions
275     * @param array<array-key, mixed> $extensions the provider's extension definitions
276     *
277     * @return string|null the available class alias, or null when none should be registered
278     */
279    private function inferredClassAlias(string $id, mixed $service, array $factories, array $extensions): ?string
280    {
281        if (! \is_object($service)) {
282            return null;
283        }
284
285        $class = $service::class;
286
287        if ($id === $class || $this->hasEntry($class, $factories, $extensions)) {
288            return null;
289        }
290
291        return $class;
292    }
293
294    /**
295     * Stores the final value under its requested ID before adding any inferred alias.
296     *
297     * @param string $id the requested service identifier
298     * @param mixed $service the completed service value, including null
299     * @param string|null $alias the optional inferred class alias
300     *
301     * @return mixed the same value placed in the service cache
302     */
303    private function cacheResolvedService(string $id, mixed $service, ?string $alias): mixed
304    {
305        $this->cache[$id] = $service;
306
307        if (null === $alias) {
308            return $service;
309        }
310
311        $this->cache[$alias] = $service;
312
313        return $service;
314    }
315
316    /**
317     * Checks existing entries using metadata already loaded by the caller.
318     *
319     * @param string $id the entry identifier
320     * @param array<string, mixed> $factories the available factory definitions
321     * @param array<string, mixed> $extensions the available extension definitions
322     *
323     * @return bool whether a resolved entry or callable definition exists
324     */
325    private function hasEntry(string $id, array $factories = [], array $extensions = []): bool
326    {
327        return \array_key_exists($id, $this->cache)
328            || \is_callable($factories[$id] ?? null)
329            || \is_callable($extensions[$id] ?? null);
330    }
331
332    /**
333     * Applies ID-based and concrete-class extensions, retaining each returned value.
334     *
335     * The ID-based extension SHALL run first. If its result is an object, an extension
336     * for that object's concrete class MAY run next. Each object's class-extension result
337     * SHALL be reused for later aliases, including replacement objects and null values.
338     * ID-based extensions for other identifiers SHALL still run independently.
339     * Invalid extensions SHALL be ignored.
340     *
341     * Extensions declared void SHALL retain the previous value for compatibility.
342     *
343     * @param string $id the identifier of the resolved service
344     * @param mixed $service the previous entry value, or null when no factory exists
345     * @param array<string, mixed> $extensions the provider's extension definitions
346     *
347     * @return mixed the final entry value
348     *
349     * @throws ContainerException if an extension callable fails during execution
350     */
351    private function applyServiceExtensions(string $id, mixed $service, array $extensions): mixed
352    {
353        $classObjects = [];
354
355        if (\is_callable($extensions[$id] ?? null)) {
356            [$service, $classObjects] = $this->applyIdentifierExtension($id, $service, $extensions[$id]);
357        }
358
359        [$service, $concreteClassObjects] = $this->applyConcreteClassExtension(
360            $id,
361            $service,
362            $extensions,
363            $classObjects
364        );
365
366        return $this->completeClassExtensions([...$classObjects, ...$concreteClassObjects], $service);
367    }
368
369    /**
370     * Runs an ID extension against a reused value without repeating an already completed class-ID extension.
371     *
372     * @param string $id the requested service identifier
373     * @param mixed $service the factory result or previously extended object
374     * @param callable $extension the callable registered under this identifier
375     *
376     * @return array{mixed, list<object>} the ID-extension result and identities completed by a class-ID extension
377     */
378    private function applyIdentifierExtension(string $id, mixed $service, callable $extension): array
379    {
380        if (! \is_object($service) || null === ($cachedResult = $this->classExtensionResult($service))) {
381            return $this->executeIdentifierExtension($id, $service, $extension);
382        }
383
384        if ($id === $service::class) {
385            return [$cachedResult['value'], []];
386        }
387
388        return $this->executeIdentifierExtension($id, $cachedResult['value'], $extension);
389    }
390
391    /**
392     * Executes an ID callback and identifies whether it also completed a class-ID extension.
393     *
394     * @param string $id the requested service identifier
395     * @param mixed $service the previous entry value
396     * @param callable $extension the callable registered under this identifier
397     *
398     * @return array{mixed, list<object>} the callback result and any completed class identity
399     */
400    private function executeIdentifierExtension(string $id, mixed $service, callable $extension): array
401    {
402        $classObject = \is_object($service) && $id === $service::class ? $service : null;
403        $service = (new ServiceExtension($extension))($this->wrapperContainer, $service);
404
405        if (null !== $classObject) {
406            return [$service, [$classObject]];
407        }
408
409        if (\is_object($service) && $id === $service::class) {
410            return [$service, [$service]];
411        }
412
413        return [$service, []];
414    }
415
416    /**
417     * Reuses a completed result or executes one extension for the current concrete class.
418     *
419     * @param string $id the requested service identifier
420     * @param mixed $service the result after the ID extension
421     * @param array<string, mixed> $extensions the provider's extension definitions
422     * @param list<object> $pendingObjects class identities being completed in this resolution
423     *
424     * @return array{mixed, list<object>} the concrete-class result and any newly completed input identity
425     */
426    private function applyConcreteClassExtension(
427        string $id,
428        mixed $service,
429        array $extensions,
430        array $pendingObjects
431    ): array {
432        if (! \is_object($service)) {
433            return [$service, []];
434        }
435
436        $cachedResult = $this->classExtensionResult($service, $pendingObjects);
437
438        if (null !== $cachedResult) {
439            return [$cachedResult['value'], []];
440        }
441
442        if ($id === $service::class || ! \is_callable($extensions[$service::class] ?? null)) {
443            return [$service, []];
444        }
445
446        $extended = (new ServiceExtension($extensions[$service::class]))($this->wrapperContainer, $service);
447
448        return [$extended, [$service]];
449    }
450
451    /**
452     * Normalizes completed replacement values before recording the current class-extension chain.
453     *
454     * This method SHALL follow only recorded results; it SHALL NOT execute another class extension.
455     *
456     * @param list<object> $objects the class identities completed in this resolution
457     * @param mixed $service the final callback value
458     *
459     * @return mixed the latest completed replacement value
460     */
461    private function completeClassExtensions(array $objects, mixed $service): mixed
462    {
463        if ([] === $objects) {
464            return $service;
465        }
466
467        if (\is_object($service) && null !== ($result = $this->classExtensionResult($service, $objects))) {
468            $service = $result['value'];
469        }
470
471        $this->rememberClassExtensionResult($objects, $service);
472
473        return $service;
474    }
475
476    /**
477     * Reads the latest completed value and compresses acyclic identity paths.
478     *
479     * A cycle retains the input's recorded result without compressing the ambiguous path.
480     * A path returning to a pending input SHALL remain unchanged until its callback chain completes.
481     *
482     * @param object $object the original or same-class result identity
483     * @param list<object> $pendingObjects class identities being completed in this resolution
484     *
485     * @return array{value: mixed}|null the wrapped result, or null when no extension completed
486     */
487    private function classExtensionResult(object $object, array $pendingObjects = []): ?array
488    {
489        $initial = $this->registeredClassExtensionResult($object);
490
491        if (null === $initial) {
492            return null;
493        }
494
495        [$result, $path] = $this->followClassExtensionResults($object, $initial);
496
497        if (\is_object($result['value']) && \in_array($result['value'], $pendingObjects, true)) {
498            return [
499                'value' => $object,
500            ];
501        }
502
503        $this->compressClassExtensionPath($path, $result);
504
505        return $result;
506    }
507
508    /**
509     * Looks up an object identity without inspecting or executing extension definitions.
510     *
511     * @param object $object the class-extension input or same-class result
512     *
513     * @return array{value: mixed}|null the wrapped completed value, or null when absent
514     */
515    private function registeredClassExtensionResult(object $object): ?array
516    {
517        return $this->classExtensionResults[$object] ?? null;
518    }
519
520    /**
521     * Follows recorded identities while retaining a bounded result for cyclic paths.
522     *
523     * @param object $object the first identity to follow
524     * @param array{value: mixed} $initial the first identity's recorded value
525     *
526     * @return array{array{value: mixed}, list<object>} the completed result and safely compressible identities
527     */
528    private function followClassExtensionResults(object $object, array $initial): array
529    {
530        $visited = new WeakMap();
531        $path = [];
532        $current = $object;
533        $result = $initial;
534
535        while (null !== ($cached = $this->registeredClassExtensionResult($current))) {
536            if (isset($visited[$current])) {
537                return [$initial, []];
538            }
539
540            $visited[$current] = true;
541            $path[] = $current;
542            $result = $cached;
543
544            if (! \is_object($result['value']) || $result['value'] === $current) {
545                return [$result, $path];
546            }
547
548            $current = $result['value'];
549        }
550
551        return [$result, $path];
552    }
553
554    /**
555     * Updates existing acyclic identities to their latest completed result.
556     *
557     * @param list<object> $objects the recorded identities visited during lookup
558     * @param array{value: mixed} $result the latest completed result
559     *
560     * @return void
561     */
562    private function compressClassExtensionPath(array $objects, array $result): void
563    {
564        if ([] === $objects) {
565            return;
566        }
567
568        $results = $this->classExtensionResults ??= new WeakMap();
569
570        foreach ($objects as $object) {
571            $results[$object] = $result;
572        }
573    }
574
575    /**
576     * Records completed results while leaving different-class replacements eligible for their own extensions.
577     *
578     * @param list<object> $objects identities whose completed class-extension result can be reused
579     * @param mixed $service the final value of the completed extension chain
580     *
581     * @return void
582     */
583    private function rememberClassExtensionResult(array $objects, mixed $service): void
584    {
585        if ([] === $objects) {
586            return;
587        }
588
589        $results = $this->classExtensionResults ??= new WeakMap();
590
591        foreach ($objects as $object) {
592            $results[$object] = [
593                'value' => $service,
594            ];
595
596            if (\is_object($service) && $object::class === $service::class) {
597                $results[$service] = [
598                    'value' => $service,
599                ];
600            }
601        }
602    }
603}