-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainer.php
More file actions
504 lines (412 loc) · 15.4 KB
/
Copy pathContainer.php
File metadata and controls
504 lines (412 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
declare(strict_types=1);
/*
* This file is part of the univeros/framework
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Altair\Container;
use Altair\Container\Contracts\DefinitionInterface;
use Altair\Container\Contracts\FactoryInterface;
use Altair\Container\Contracts\InvokerInterface;
use Altair\Container\Contracts\ReflectorInterface;
use Altair\Container\Definition\ContextualBindingBuilder;
use Altair\Container\Definition\Definition;
use Altair\Container\Exception\ContainerException;
use Altair\Container\Exception\NotFoundException;
use Altair\Container\Lazy\LazyFactory;
use Altair\Container\Reflection\CachedReflector;
use Altair\Container\Resolution\Invoker;
use Altair\Container\Resolution\ParameterResolver;
use Altair\Container\Resolution\ResolutionStack;
use Altair\Container\Resolution\Resolver;
use Altair\Container\Support\NameNormalizer;
use Closure;
use Override;
use Psr\Container\ContainerInterface;
use ReflectionException;
/**
* A runtime, auto-wiring dependency-injection container.
*
* Resolves typed constructor dependencies by reflection (cached), with fluent
* bindings, attribute autowiring, contextual bindings, tagged services, lazy
* services, and isolated child scopes. PSR-11 compliant; it resolves its own
* type to the active instance.
*/
final class Container implements ContainerInterface, FactoryInterface, InvokerInterface
{
private readonly ReflectorInterface $reflector;
private readonly ResolutionStack $stack;
private readonly ParameterResolver $parameterResolver;
private readonly Resolver $resolver;
private readonly Invoker $invoker;
private readonly LazyFactory $lazyFactory;
/**
* @var array<string, Definition>
*/
private array $definitions = [];
/**
* @var array<string, object>
*/
private array $singletons = [];
/**
* @var array<string, array<string, Closure>>
*/
private array $contextual = [];
/**
* @var array<string, list<Closure>>
*/
private array $extenders = [];
/**
* @var array<string, true>
*/
private array $selfNames = [];
public function __construct(
?ReflectorInterface $reflector = null,
private readonly ?Container $parent = null,
) {
$this->reflector = $reflector ?? new CachedReflector();
$this->stack = new ResolutionStack();
$this->parameterResolver = new ParameterResolver($this);
$this->resolver = new Resolver($this, $this->reflector, $this->parameterResolver);
$this->invoker = new Invoker($this, $this->reflector, $this->parameterResolver);
$this->lazyFactory = new LazyFactory();
foreach ([self::class, FactoryInterface::class, InvokerInterface::class, ContainerInterface::class] as $name) {
$this->selfNames[NameNormalizer::normalize($name)] = true;
}
}
#[Override]
public function get(string $id): mixed
{
$key = NameNormalizer::normalize($id);
if (isset($this->selfNames[$key])) {
return $this;
}
if (isset($this->singletons[$key])) {
return $this->singletons[$key];
}
$definition = $this->definitions[$key] ?? null;
if ($definition !== null) {
return $this->resolveDefinition($key, $definition);
}
if ($this->parent instanceof \Altair\Container\Container && $this->parent->has($id)) {
return $this->parent->get($id);
}
if (class_exists($id)) {
if ($this->reflector->classMetadata($id)->isLazy) {
return $this->applyExtenders($key, $this->lazyFactory->create($id, fn(): object => $this->build($id, [])));
}
return $this->applyExtenders($key, $this->build($id, []));
}
throw NotFoundException::forId($id);
}
#[Override]
public function has(string $id): bool
{
$key = NameNormalizer::normalize($id);
if (isset($this->selfNames[$key]) || isset($this->singletons[$key]) || isset($this->definitions[$key])) {
return true;
}
// Deliberately explicit-registration only (not every autowireable class):
// the framework uses `!has(Concrete::class)` as a register-if-absent guard.
// get() may still autowire an unregistered class as a convenience.
return $this->parent?->has($id) ?? false;
}
/**
* @template T of object
*
* @param class-string<T> $class
* @param array<string, mixed> $parameters
*
* @return T
*/
#[Override]
public function make(string $class, array $parameters = []): object
{
$key = NameNormalizer::normalize($class);
$definition = $this->definition($key);
if ($definition instanceof DefinitionInterface && !$definition->hasValue()) {
$instance = $definition->instance();
if ($instance !== null) {
/** @var T $instance */
return $instance;
}
$factory = $definition->factory();
if ($factory instanceof Closure) {
/** @var T $made */
$made = $this->applyExtenders($key, $this->invokeForObject($factory, $key));
return $made;
}
/** @var T $built */
$built = $this->applyExtenders(
$key,
$this->build($definition->concrete() ?? $class, array_merge($definition->parameters(), $parameters))
);
return $built;
}
/** @var T $object */
$object = $this->applyExtenders($key, $this->build($class, $parameters));
return $object;
}
/**
* @param callable|array{0: object|class-string, 1: string}|string $target
* @param array<string, mixed> $parameters
*/
#[Override]
public function call(callable|array|string $target, array $parameters = []): mixed
{
try {
return $this->invoker->call($target, $parameters, $this->stack);
} catch (ReflectionException $reflectionException) {
throw new ContainerException('Cannot invoke callable: ' . $reflectionException->getMessage(), 0, $reflectionException);
}
}
public function bind(string $id): Definition
{
$definition = new Definition($id);
$this->definitions[NameNormalizer::normalize($id)] = $definition;
return $definition;
}
public function singleton(string $id, Closure|string|null $concrete = null): Definition
{
$definition = $this->bind($id)->shared();
if ($concrete instanceof Closure) {
$definition->using($concrete);
} elseif (\is_string($concrete)) {
$definition->to($concrete);
}
return $definition;
}
public function factory(string $id, Closure $factory): Definition
{
return $this->bind($id)->using($factory);
}
public function instance(string $id, object $instance): Definition
{
$this->singletons[NameNormalizer::normalize($id)] = $instance;
return $this->bind($id)->withInstance($instance);
}
public function value(string $id, mixed $value): Definition
{
return $this->bind($id)->withValue($value);
}
/**
* @param class-string $concrete
*/
public function alias(string $abstract, string $concrete): Definition
{
return $this->bind($abstract)->to($concrete);
}
public function when(string $consumer): ContextualBindingBuilder
{
return new ContextualBindingBuilder($this, $consumer);
}
/**
* Register a decorator run against $id immediately after it is resolved.
* Decorators stack (multiple may apply) and run in registration order; a
* decorator that returns an object replaces the instance, otherwise the
* original is kept (allowing side-effect-only hooks).
*
* Register decorators during wiring: one added after a *shared* service has
* already been resolved does not retroactively decorate the cached instance.
*
* @param Closure(object, Container): mixed $decorator
*/
public function extend(string $id, Closure $decorator): void
{
$this->extenders[NameNormalizer::normalize($id)][] = $decorator;
}
/**
* Resolve every service tagged with $tag (lazily, in registration order).
*
* @return iterable<mixed>
*/
public function tagged(string $tag): iterable
{
$ids = [];
foreach ($this->mergedDefinitions() as $key => $definition) {
if (\in_array($tag, $definition->tags(), true)) {
$ids[$key] = true;
continue;
}
$concrete = $definition->concrete() ?? $definition->id();
if (class_exists($concrete) && \in_array($tag, $this->reflector->classMetadata($concrete)->tags, true)) {
$ids[$key] = true;
}
}
foreach (array_keys($ids) as $key) {
yield $this->get($key);
}
}
/**
* Create a child scope: it inherits this container's definitions but keeps
* its own singleton store and may override bindings without affecting the
* parent.
*
* Note: each scope has its own resolution stack, so a dependency cycle that
* spans a child and its parent is not detected (and is a design smell —
* resolve such graphs within a single container).
*/
public function createScope(): self
{
return new self($this->reflector, $this);
}
public function addContextualBinding(string $consumer, string $type, Closure $resolver): void
{
$this->contextual[NameNormalizer::normalize($consumer)][NameNormalizer::normalize($type)] = $resolver;
}
public function contextualBinding(string $consumer, string $type): ?Closure
{
$consumerKey = NameNormalizer::normalize($consumer);
$typeKey = NameNormalizer::normalize($type);
return $this->contextual[$consumerKey][$typeKey]
?? $this->parent?->contextualBinding($consumer, $type);
}
public function parameterValue(string $name): mixed
{
$definition = $this->definition(NameNormalizer::normalize($name));
if ($definition instanceof DefinitionInterface && $definition->hasValue()) {
return $definition->value();
}
if ($definition instanceof DefinitionInterface && $definition->hasInstance()) {
return $definition->instance();
}
throw new ContainerException(\sprintf('No container parameter "%s" is registered.', $name));
}
/**
* @return array<string, DefinitionInterface>
*/
public function getDefinitions(): array
{
return $this->definitions;
}
/**
* The instances the container has actually realised and is sharing.
*
* @return array<string, object>
*/
public function getRealisedSingletons(): array
{
return $this->singletons;
}
private function resolveDefinition(string $key, DefinitionInterface $definition): mixed
{
if ($definition->hasInstance()) {
return $definition->instance();
}
if ($definition->hasValue()) {
return $definition->value();
}
$object = $this->produce($definition, $key);
if (\is_object($object)) {
$object = $this->applyExtenders($key, $object);
}
if ($definition->isShared() && \is_object($object)) {
$this->singletons[$key] = $object;
}
return $object;
}
private function applyExtenders(string $key, object $object): object
{
foreach ($this->extendersFor($key) as $decorator) {
$result = $decorator($object, $this);
if (\is_object($result)) {
$object = $result;
}
}
return $object;
}
/**
* @return list<Closure>
*/
private function extendersFor(string $key): array
{
return array_merge($this->parent?->extendersFor($key) ?? [], $this->extenders[$key] ?? []);
}
private function produce(DefinitionInterface $definition, string $key): mixed
{
$concrete = $definition->concrete() ?? $definition->id();
if ($this->resolvesLazily($definition, $concrete)) {
$class = class_exists($concrete) ? $concrete : null;
return $this->lazyFactory->create($class, fn(): mixed => $this->produceEager($definition, $key));
}
return $this->produceEager($definition, $key);
}
/**
* Lazy when the binding opted in (`->lazy()`) or the target class carries
* the `#[Lazy]` attribute.
*/
private function resolvesLazily(DefinitionInterface $definition, string $concrete): bool
{
if ($definition->isLazy()) {
return true;
}
return class_exists($concrete) && $this->reflector->classMetadata($concrete)->isLazy;
}
private function produceEager(DefinitionInterface $definition, string $key): mixed
{
$factory = $definition->factory();
if ($factory instanceof Closure) {
return $this->callFactoryGuarded($factory, $key);
}
$concrete = $definition->concrete();
// An alias (`->to(B)`) pointing at a separately-bound concrete must
// resolve B through its own definition (factory, params, shared, …),
// not build it blindly. Only when the alias adds no parameters of its own.
if ($concrete !== null && $definition->parameters() === []) {
$concreteKey = NameNormalizer::normalize($concrete);
if ($concreteKey !== NameNormalizer::normalize($definition->id()) && $this->definition($concreteKey) instanceof DefinitionInterface) {
return $this->get($concrete);
}
}
return $this->build($concrete ?? $definition->id(), $definition->parameters());
}
/**
* Invoke a factory closure under the resolution-stack guard so factory-based
* dependency cycles raise {@see \Altair\Container\Exception\CircularDependencyException}
* instead of overflowing the PHP call stack.
*/
private function callFactoryGuarded(Closure $factory, string $key): mixed
{
$this->stack->enter($key);
try {
return $this->call($factory);
} finally {
$this->stack->leave($key);
}
}
private function invokeForObject(Closure $factory, string $key): object
{
$object = $this->callFactoryGuarded($factory, $key);
if (!\is_object($object)) {
throw new ContainerException('Factory closure must return an object.');
}
return $object;
}
/**
* @param array<string, mixed> $callTime
*/
private function build(string $class, array $callTime): object
{
$key = NameNormalizer::normalize($class);
$this->stack->enter($key);
try {
return $this->resolver->instantiate($class, $callTime, $this->stack);
} finally {
$this->stack->leave($key);
}
}
private function definition(string $key): ?DefinitionInterface
{
return $this->definitions[$key] ?? $this->parent?->definition($key);
}
/**
* @return array<string, Definition>
*/
private function mergedDefinitions(): array
{
$parent = $this->parent?->mergedDefinitions() ?? [];
return array_merge($parent, $this->definitions);
}
}