Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
AggregateContainer
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
6 / 6
16
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 append
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 prepend
100.00% covered (success)
100.00%
2 / 2
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
7
 isResolvedByContainer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
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 FastForward\Container\Exception\NotFoundException;
22use Psr\Container\ContainerExceptionInterface;
23use Psr\Container\ContainerInterface as PsrContainerInterface;
24use Psr\Container\NotFoundExceptionInterface;
25
26/**
27 * Aggregates multiple PSR-11 containers and delegates resolution requests among them.
28 *
29 * This container implementation respects PSR-11 expectations and throws a
30 * NotFoundException when a requested service cannot be found in any delegated container.
31 *
32 * It caches resolved entries to prevent redundant calls to delegated containers.
33 */
34class AggregateContainer implements ContainerInterface
35{
36    /**
37     * @var string container alias for reference binding
38     */
39    public const ALIAS = 'container';
40
41    /**
42     * @var ContainerInterface[] the array of containers aggregated by this instance
43     */
44    private array $containers = [];
45
46    /**
47     * @var array<string, mixed> a registry of already resolved service identifiers
48     */
49    private array $resolved = [];
50
51    /**
52     * Constructs the AggregateContainer with one or more delegated containers.
53     *
54     * The constructor SHALL bind itself to common aliases, including the class name
55     * and the PSR-11 interface, to simplify resolution of the container itself.
56     *
57     * @param PsrContainerInterface ...$containers One or more container implementations to aggregate.
58     */
59    public function __construct(PsrContainerInterface ...$containers)
60    {
61        $this->resolved = [
62            self::ALIAS                  => $this,
63            self::class                  => $this,
64            ContainerInterface::class    => $this,
65            PsrContainerInterface::class => $this,
66        ];
67
68        foreach ($containers as $container) {
69            $this->append($container);
70        }
71    }
72
73    /**
74     * Appends a container to the end of the aggregated list.
75     *
76     * This method MAY be used to dynamically expand the resolution pool.
77     *
78     * @param PsrContainerInterface $container the container to append
79     *
80     * @return void
81     */
82    public function append(PsrContainerInterface $container): void
83    {
84        $this->containers[] = $container;
85
86        $this->resolved[$container::class] ??= $container;
87    }
88
89    /**
90     * Prepends a container to the beginning of the aggregated list.
91     *
92     * This method MAY be used to prioritize a container during resolution.
93     *
94     * @param PsrContainerInterface $container the container to prepend
95     *
96     * @return void
97     */
98    public function prepend(PsrContainerInterface $container): void
99    {
100        $this->resolved[$container::class] = $container;
101        array_unshift($this->containers, $container);
102    }
103
104    /**
105     * Determines whether a service identifier can be resolved.
106     *
107     * This method SHALL return true if the identifier is pre-resolved or can be located
108     * in any of the aggregated containers.
109     *
110     * @param string $id the identifier of the entry to look for
111     *
112     * @return bool true if the entry exists, false otherwise
113     */
114    public function has(string $id): bool
115    {
116        if ($this->isResolvedByContainer($id)) {
117            return true;
118        }
119
120        foreach ($this->containers as $container) {
121            if ($container->has($id)) {
122                return true;
123            }
124        }
125
126        return false;
127    }
128
129    /**
130     * Retrieves the entry associated with the given identifier.
131     *
132     * This method SHALL resolve from its internal cache first, and otherwise iterate
133     * through the aggregated containers to resolve the entry. It MUST throw a
134     * NotFoundException if the identifier is absent. If all candidates fail, the first
135     * delegated construction exception SHALL be retained instead.
136     *
137     * @param string $id the identifier of the entry to retrieve
138     *
139     * @return mixed the resolved entry
140     *
141     * @throws NotFoundException if the identifier cannot be found in any aggregated container
142     * @throws ContainerExceptionInterface if the container cannot resolve the entry
143     */
144    public function get(string $id): mixed
145    {
146        if ($this->isResolvedByContainer($id)) {
147            return $this->resolved[$id];
148        }
149
150        $exception = NotFoundException::forServiceID($id);
151
152        foreach ($this->containers as $container) {
153            if (! $container->has($id)) {
154                continue;
155            }
156
157            try {
158                $this->resolved[$id] = $container->get($id);
159
160                return $this->resolved[$id];
161            } catch (NotFoundExceptionInterface) {
162                // Ignore NotFoundExceptionInterface
163            } catch (ContainerExceptionInterface $failure) {
164                if ($exception instanceof NotFoundExceptionInterface) {
165                    $exception = $failure;
166                }
167            }
168        }
169
170        throw $exception;
171    }
172
173    /**
174     * Determines whether the identifier has already been resolved by this container.
175     *
176     * This method is used internally to avoid unnecessary delegation to sub-containers.
177     *
178     * @param string $id the identifier to check
179     *
180     * @return bool true if the identifier is already resolved, false otherwise
181     */
182    private function isResolvedByContainer(string $id): bool
183    {
184        return \array_key_exists($id, $this->resolved);
185    }
186}