• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tempestphp / tempest-framework / 14184240034

01 Apr 2025 12:28AM UTC coverage: 80.979% (+0.02%) from 80.964%
14184240034

Pull #1105

github

web-flow
Merge 9dad13691 into 80e661e93
Pull Request #1105: feat(core): introduce tagged configurations

53 of 60 new or added lines in 10 files covered. (88.33%)

1 existing line in 1 file now uncovered.

11082 of 13685 relevant lines covered (80.98%)

101.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.0
/src/Tempest/Container/src/GenericContainer.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Tempest\Container;
6

7
use ArrayIterator;
8
use Closure;
9
use ReflectionFunction;
10
use Tempest\Container\Exceptions\CannotAutowireException;
11
use Tempest\Container\Exceptions\CannotInstantiateDependencyException;
12
use Tempest\Container\Exceptions\CannotResolveTaggedDependency;
13
use Tempest\Container\Exceptions\InvalidCallableException;
14
use Tempest\Reflection\ClassReflector;
15
use Tempest\Reflection\FunctionReflector;
16
use Tempest\Reflection\MethodReflector;
17
use Tempest\Reflection\ParameterReflector;
18
use Tempest\Reflection\TypeReflector;
19
use Throwable;
20
use UnitEnum;
21

22
final class GenericContainer implements Container
23
{
24
    use HasInstance;
25

26
    public function __construct(
760✔
27
        /** @var ArrayIterator<array-key, mixed> $definitions */
28
        private ArrayIterator $definitions = new ArrayIterator(),
29

30
        /** @var ArrayIterator<array-key, mixed> $singletons */
31
        private ArrayIterator $singletons = new ArrayIterator(),
32

33
        /** @var ArrayIterator<array-key, class-string> $initializers */
34
        private ArrayIterator $initializers = new ArrayIterator(),
35

36
        /** @var ArrayIterator<array-key, class-string> $dynamicInitializers */
37
        private ArrayIterator $dynamicInitializers = new ArrayIterator(),
38
        private ?DependencyChain $chain = null,
39
    ) {}
760✔
40

41
    public function setDefinitions(array $definitions): self
×
42
    {
43
        $this->definitions = new ArrayIterator($definitions);
×
44

45
        return $this;
×
46
    }
47

48
    public function setInitializers(array $initializers): self
1✔
49
    {
50
        $this->initializers = new ArrayIterator($initializers);
1✔
51

52
        return $this;
1✔
53
    }
54

55
    public function setDynamicInitializers(array $dynamicInitializers): self
×
56
    {
57
        $this->dynamicInitializers = new ArrayIterator($dynamicInitializers);
×
58

59
        return $this;
×
60
    }
61

62
    public function getDefinitions(): array
×
63
    {
64
        return $this->definitions->getArrayCopy();
×
65
    }
66

67
    public function getInitializers(): array
1✔
68
    {
69
        return $this->initializers->getArrayCopy();
1✔
70
    }
71

72
    public function getDynamicInitializers(): array
×
73
    {
74
        return $this->dynamicInitializers->getArrayCopy();
×
75
    }
76

77
    public function register(string $className, callable $definition): self
713✔
78
    {
79
        $this->definitions[$className] = $definition;
713✔
80

81
        return $this;
713✔
82
    }
83

84
    public function unregister(string $className): self
24✔
85
    {
86
        unset($this->definitions[$className], $this->singletons[$className]);
24✔
87

88
        return $this;
24✔
89
    }
90

91
    public function has(string $className, null|string|UnitEnum $tag = null): bool
21✔
92
    {
93
        return isset($this->definitions[$className]) || isset($this->singletons[$this->resolveTaggedName($className, $tag)]);
21✔
94
    }
95

96
    public function singleton(string $className, mixed $definition, null|string|UnitEnum $tag = null): self
727✔
97
    {
98
        $className = $this->resolveTaggedName($className, $tag);
727✔
99

100
        $this->singletons[$className] = $definition;
727✔
101

102
        return $this;
727✔
103
    }
104

105
    public function config(object $config): self
713✔
106
    {
107
        $tag = ($config instanceof TaggedConfig)
713✔
108
            ? $config->tag
712✔
109
            : null;
713✔
110

111
        $this->singleton($config::class, $config, $tag);
713✔
112

113
        foreach (new ClassReflector($config)->getInterfaces() as $interface) {
713✔
114
            if ($interface->getName() === TaggedConfig::class) {
712✔
115
                continue;
712✔
116
            }
117

118
            $this->singleton($interface->getName(), $config);
712✔
119
        }
120

121
        return $this;
713✔
122
    }
123

124
    public function get(string $className, null|string|UnitEnum $tag = null, mixed ...$params): ?object
749✔
125
    {
126
        $this->resolveChain();
749✔
127

128
        $dependency = $this->resolve(
749✔
129
            className: $className,
749✔
130
            tag: $tag,
749✔
131
            params: $params,
749✔
132
        );
749✔
133

134
        $this->stopChain();
744✔
135

136
        return $dependency;
744✔
137
    }
138

139
    public function invoke(MethodReflector|FunctionReflector|callable|string $method, mixed ...$params): mixed
724✔
140
    {
141
        if ($method instanceof MethodReflector) {
724✔
142
            return $this->invokeMethod($method, ...$params);
43✔
143
        }
144

145
        if ($method instanceof FunctionReflector) {
723✔
146
            return $this->invokeFunction($method, ...$params);
×
147
        }
148

149
        if ($method instanceof Closure) {
723✔
150
            return $this->invokeClosure($method, ...$params);
25✔
151
        }
152

153
        if (is_array($method) && count($method) === 2) {
717✔
154
            return $this->invokeClosure($method(...), ...$params);
1✔
155
        }
156

157
        if (method_exists($method, '__invoke')) {
717✔
158
            return $this->invokeClosure(
716✔
159
                $this->get($method)->__invoke(...),
716✔
160
                ...$params,
716✔
161
            );
716✔
162
        }
163

164
        throw new InvalidCallableException(new Dependency($method));
1✔
165
    }
166

167
    private function invokeClosure(Closure $closure, mixed ...$params): mixed
722✔
168
    {
169
        $this->resolveChain();
722✔
170

171
        $parameters = $this->autowireDependencies(
722✔
172
            method: $reflector = new FunctionReflector($closure),
722✔
173
            parameters: $params,
722✔
174
        );
722✔
175

176
        $this->stopChain();
721✔
177

178
        return $reflector->invokeArgs($parameters);
721✔
179
    }
180

181
    private function invokeMethod(MethodReflector $method, mixed ...$params): mixed
43✔
182
    {
183
        $this->resolveChain();
43✔
184

185
        $object = $this->get($method->getDeclaringClass()->getName());
43✔
186

187
        $parameters = $this->autowireDependencies($method, $params);
43✔
188

189
        $this->stopChain();
43✔
190

191
        return $method->invokeArgs($object, $parameters);
43✔
192
    }
193

194
    private function invokeFunction(FunctionReflector|Closure $callback, mixed ...$params): mixed
×
195
    {
196
        $this->resolveChain();
×
197

198
        $reflector = match (true) {
×
199
            $callback instanceof FunctionReflector => $callback,
×
200
            default => new ReflectionFunction($callback),
×
201
        };
×
202

203
        $parameters = $this->autowireDependencies($reflector, $params);
×
204

205
        $this->stopChain();
×
206

207
        return $reflector->invokeArgs($parameters);
×
208
    }
209

210
    public function addInitializer(ClassReflector|string $initializerClass): Container
724✔
211
    {
212
        if (! ($initializerClass instanceof ClassReflector)) {
724✔
213
            $initializerClass = new ClassReflector($initializerClass);
724✔
214
        }
215

216
        // First, we check whether this is a DynamicInitializer,
217
        // which don't have a one-to-one mapping
218
        if ($initializerClass->getType()->matches(DynamicInitializer::class)) {
724✔
219
            $this->dynamicInitializers[] = $initializerClass->getName();
714✔
220

221
            return $this;
714✔
222
        }
223

224
        $initializeMethod = $initializerClass->getMethod('initialize');
722✔
225

226
        // We resolve the optional Tag attribute from this initializer class
227
        $singleton = $initializeMethod->getAttribute(Singleton::class);
722✔
228

229
        // For normal Initializers, we'll use the return type
230
        // to determine which dependency they resolve
231
        $returnType = $initializeMethod->getReturnType();
722✔
232

233
        foreach ($returnType->split() as $type) {
722✔
234
            $this->initializers[$this->resolveTaggedName($type->getName(), $singleton?->tag)] = $initializerClass->getName();
722✔
235
        }
236

237
        return $this;
722✔
238
    }
239

240
    private function resolve(string $className, null|string|UnitEnum $tag = null, mixed ...$params): ?object
751✔
241
    {
242
        $class = new ClassReflector($className);
751✔
243

244
        $dependencyName = $this->resolveTaggedName($className, $tag);
751✔
245

246
        // Check if the class has been registered as a singleton.
247
        if ($instance = $this->singletons[$dependencyName] ?? null) {
751✔
248
            if ($instance instanceof Closure) {
722✔
249
                $instance = $instance($this);
717✔
250
                $this->singletons[$className] = $instance;
717✔
251
            }
252

253
            $this->resolveChain()->add($class);
722✔
254

255
            return $instance;
722✔
256
        }
257

258
        // Check if a callable has been registered to resolve this class.
259
        if ($definition = $this->definitions[$dependencyName] ?? null) {
746✔
260
            $this->resolveChain()->add(new FunctionReflector($definition));
30✔
261

262
            return $definition($this);
30✔
263
        }
264

265
        // Next we check if any of our default initializers can initialize this class.
266
        if (($initializer = $this->initializerForClass($class, $tag)) !== null) {
745✔
267
            $initializerClass = new ClassReflector($initializer);
723✔
268

269
            $this->resolveChain()->add($initializerClass);
723✔
270

271
            $object = match (true) {
723✔
272
                $initializer instanceof Initializer => $initializer->initialize($this->clone()),
723✔
273
                $initializer instanceof DynamicInitializer => $initializer->initialize($class, $this->clone(), $this->resolveTag($tag)),
712✔
274
            };
723✔
275

276
            $singleton = $initializerClass->getAttribute(Singleton::class) ?? $initializerClass->getMethod('initialize')->getAttribute(Singleton::class);
723✔
277

278
            if ($singleton !== null) {
723✔
279
                $this->singleton($className, $object, $tag);
715✔
280
            }
281

282
            return $object;
723✔
283
        }
284

285
        // If we're requesting a tagged dependency and haven't resolved it at this point, something's wrong
286
        if ($tag !== null) {
745✔
287
            throw new CannotResolveTaggedDependency($this->chain, new Dependency($className), $this->resolveTag($tag));
2✔
288
        }
289

290
        // Finally, autowire the class.
291
        return $this->autowire($className, $params, $tag);
744✔
292
    }
293

294
    private function initializerForBuiltin(TypeReflector $target, string $tag): ?Initializer
1✔
295
    {
296
        if ($initializerClass = $this->initializers[$this->resolveTaggedName($target->getName(), $tag)] ?? null) {
1✔
297
            return $this->resolve($initializerClass);
1✔
298
        }
299

300
        return null;
×
301
    }
302

303
    private function initializerForClass(ClassReflector $target, null|string|UnitEnum $tag = null): null|Initializer|DynamicInitializer
745✔
304
    {
305
        // Initializers themselves can't be initialized,
306
        // otherwise you'd end up with infinite loops
307
        if ($target->getType()->matches(Initializer::class) || $target->getType()->matches(DynamicInitializer::class)) {
745✔
308
            return null;
724✔
309
        }
310

311
        if ($initializerClass = $this->initializers[$this->resolveTaggedName($target->getName(), $tag)] ?? null) {
745✔
312
            return $this->resolve($initializerClass);
721✔
313
        }
314

315
        // Loop through the registered initializers to see if
316
        // we have something to handle this class.
317
        foreach ($this->dynamicInitializers as $initializerClass) {
737✔
318
            /** @var DynamicInitializer $initializer */
319
            $initializer = $this->resolve($initializerClass);
714✔
320

321
            if (! $initializer->canInitialize($target, $this->resolveTag($tag))) {
714✔
322
                continue;
713✔
323
            }
324

325
            return $initializer;
712✔
326
        }
327

328
        return null;
736✔
329
    }
330

331
    private function autowire(string $className, array $params, null|string|UnitEnum $tag): object
744✔
332
    {
333
        $classReflector = new ClassReflector($className);
744✔
334

335
        $constructor = $classReflector->getConstructor();
744✔
336

337
        if (! $classReflector->isInstantiable()) {
744✔
338
            throw new CannotInstantiateDependencyException($classReflector, $this->chain);
714✔
339
        }
340

341
        $instance = $constructor === null
742✔
342
            ? // If there isn't a constructor, don't waste time
742✔
343
            // trying to build it.
344
            $classReflector->newInstanceWithoutConstructor()
737✔
345
            : // Otherwise, use our autowireDependencies helper to automagically
742✔
346
            // build up each parameter.
347
            $classReflector->newInstanceArgs(
724✔
348
                $this->autowireDependencies($constructor, $params, $tag),
724✔
349
            );
724✔
350

351
        if (
352
            ! $classReflector->getType()->matches(Initializer::class) &&
741✔
353
                ! $classReflector->getType()->matches(DynamicInitializer::class) &&
741✔
354
                $classReflector->hasAttribute(Singleton::class)
741✔
355
        ) {
356
            $this->singleton($className, $instance);
713✔
357
        }
358

359
        foreach ($classReflector->getProperties() as $property) {
741✔
360
            if ($property->hasAttribute(Inject::class) && ! $property->isInitialized($instance)) {
726✔
361
                $property->set($instance, $this->get($property->getType()->getName()));
74✔
362
            }
363

364
            if ($tag && $property->hasAttribute(TagName::class) && ! $property->isInitialized($instance)) {
726✔
NEW
365
                $property->set($instance, $property->accepts(UnitEnum::class) ? $tag : $this->resolveTag($tag));
×
366
            }
367
        }
368

369
        return $instance;
741✔
370
    }
371

372
    /**
373
     * @return ParameterReflector[]
374
     */
375
    private function autowireDependencies(MethodReflector|FunctionReflector $method, array $parameters = [], null|string|UnitEnum $tag = null): array
735✔
376
    {
377
        $this->resolveChain()->add($method);
735✔
378

379
        $dependencies = [];
735✔
380

381
        // Build the class by iterating through its
382
        // dependencies and resolving them.
383
        foreach ($method->getParameters() as $parameter) {
735✔
384
            $dependencies[] = $this->clone()->autowireDependency(
734✔
385
                parameter: $parameter,
734✔
386
                tag: $parameter->getAttribute(ForwardTag::class) && $tag
734✔
NEW
387
                    ? $tag
×
388
                    : $parameter->getAttribute(Tag::class)?->name,
734✔
389
                providedValue: $parameters[$parameter->getName()] ?? null,
734✔
390
            );
734✔
391
        }
392

393
        return $dependencies;
730✔
394
    }
395

396
    private function autowireDependency(ParameterReflector $parameter, null|string|UnitEnum $tag, mixed $providedValue = null): mixed
734✔
397
    {
398
        $parameterType = $parameter->getType();
734✔
399

400
        // If the parameter is a built-in type, skip reflection and attempt to provide the value by
401
        // tagged initializer, a default value or null value.
402
        if ($parameterType->isBuiltin()) {
734✔
403
            return $this->autowireBuiltinDependency($parameter, $providedValue);
171✔
404
        }
405

406
        // Loop through each type until we hit a match.
407
        foreach ($parameter->getType()->split() as $type) {
726✔
408
            try {
409
                return $this->autowireObjectDependency(
726✔
410
                    type: $type,
726✔
411
                    tag: $tag,
726✔
412
                    providedValue: $providedValue,
726✔
413
                );
726✔
414
            } catch (Throwable $throwable) {
717✔
415
                // We were unable to resolve the dependency for the last union
416
                // type, so we are moving on to the next one. We hang onto
417
                // the exception in case it is a circular reference.
418
                $lastThrowable = $throwable;
717✔
419
            }
420
        }
421

422
        // If the dependency has a default value, we do our best to prevent
423
        // an error by using that.
424
        if ($parameter->hasDefaultValue()) {
716✔
425
            return $parameter->getDefaultValue();
712✔
426
        }
427

428
        // At this point, there is nothing else we can do; we don't know
429
        // how to autowire this dependency.
430
        throw $lastThrowable ?? new CannotAutowireException($this->chain, new Dependency($parameter));
5✔
431
    }
432

433
    private function autowireObjectDependency(TypeReflector $type, null|string|UnitEnum $tag, mixed $providedValue): mixed
726✔
434
    {
435
        // If the provided value is of the right type,
436
        // don't waste time autowiring, return it!
437
        if ($type->accepts($providedValue)) {
726✔
438
            return $providedValue;
135✔
439
        }
440

441
        // If we can successfully retrieve an instance
442
        // of the necessary dependency, return it.
443
        return $this->resolve(className: $type->getName(), tag: $tag);
724✔
444
    }
445

446
    private function autowireBuiltinDependency(ParameterReflector $parameter, mixed $providedValue): mixed
171✔
447
    {
448
        $typeName = $parameter->getType()->getName();
171✔
449
        $tag = $parameter->getAttribute(Tag::class);
171✔
450

451
        if ($tag !== null && ($initializer = $this->initializerForBuiltin($parameter->getType(), $tag->name))) {
171✔
452
            $initializerClass = new ClassReflector($initializer);
1✔
453

454
            $object = $initializer->initialize($this->clone());
1✔
455

456
            $singleton = $initializerClass->getAttribute(Singleton::class) ?? $initializerClass->getMethod('initialize')->getAttribute(Singleton::class);
1✔
457

458
            if ($singleton !== null) {
1✔
459
                $this->singleton($typeName, $object, $tag->name);
1✔
460
            }
461

462
            return $object;
1✔
463
        }
464

465
        // Due to type coercion, the provided value may (or may not) work.
466
        // Here we give up trying to do type work for people. If they
467
        // didn't provide the right type, that's on them.
468
        if ($providedValue !== null) {
170✔
469
            return $providedValue;
18✔
470
        }
471

472
        // If the dependency has a default value, we might as well
473
        // use that at this point.
474
        if ($parameter->hasDefaultValue()) {
159✔
475
            return $parameter->getDefaultValue();
43✔
476
        }
477

478
        // If the dependency's type is an array or variadic variable, we'll
479
        // try to prevent an error by returning an empty array.
480
        if ($parameter->isVariadic() || $parameter->isIterable()) {
124✔
481
            return [];
1✔
482
        }
483

484
        // If the dependency's type allows null or is optional, we'll
485
        // try to prevent an error by returning null.
486
        if (! $parameter->isRequired()) {
123✔
487
            return null;
1✔
488
        }
489

490
        // At this point, there is nothing else we can do; we don't know
491
        // how to autowire this dependency.
492
        throw new CannotAutowireException($this->chain, new Dependency($parameter));
122✔
493
    }
494

495
    private function clone(): self
743✔
496
    {
497
        return clone $this;
743✔
498
    }
499

500
    private function resolveChain(): DependencyChain
754✔
501
    {
502
        if ($this->chain === null) {
754✔
503
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
754✔
504

505
            $this->chain = new DependencyChain($trace[1]['file'] . ':' . $trace[1]['line']);
754✔
506
        }
507

508
        return $this->chain;
754✔
509
    }
510

511
    private function stopChain(): void
748✔
512
    {
513
        $this->chain = null;
748✔
514
    }
515

516
    public function __clone(): void
743✔
517
    {
518
        $this->chain = $this->chain?->clone();
743✔
519
    }
520

521
    private function resolveTag(null|string|UnitEnum $tag): ?string
721✔
522
    {
523
        if ($tag instanceof UnitEnum) {
721✔
524
            return $tag->name;
1✔
525
        }
526

527
        return $tag;
721✔
528
    }
529

530
    private function resolveTaggedName(string $className, null|string|UnitEnum $tag): string
754✔
531
    {
532
        return $tag
754✔
533
            ? "{$className}#{$this->resolveTag($tag)}"
719✔
534
            : $className;
754✔
535
    }
536
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc