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

tempestphp / tempest-framework / 14184527880

01 Apr 2025 12:49AM UTC coverage: 80.967% (+0.003%) from 80.964%
14184527880

Pull #1105

github

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

44 of 51 new or added lines in 9 files covered. (86.27%)

1 existing line in 1 file now uncovered.

11073 of 13676 relevant lines covered (80.97%)

101.29 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)),
8✔
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 non-dynamic tagged dependency and
286
        // haven't resolved it at this point, something's wrong
287
        if ($tag !== null && ! $class->getAttribute(AllowDynamicTags::class)) {
745✔
288
            throw new CannotResolveTaggedDependency($this->chain, new Dependency($className), $this->resolveTag($tag));
2✔
289
        }
290

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

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

301
        return null;
×
302
    }
303

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

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

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

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

326
            return $initializer;
8✔
327
        }
328

329
        return null;
736✔
330
    }
331

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

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

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

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

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

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

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

370
        return $instance;
741✔
371
    }
372

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

380
        $dependencies = [];
735✔
381

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

394
        return $dependencies;
730✔
395
    }
396

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

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

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

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

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

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

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

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

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

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

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

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

463
            return $object;
1✔
464
        }
465

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

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

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

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

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

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

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

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

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

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

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

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

528
        return $tag;
721✔
529
    }
530

531
    private function resolveTaggedName(string $className, null|string|UnitEnum $tag): string
754✔
532
    {
533
        return $tag
754✔
534
            ? "{$className}#{$this->resolveTag($tag)}"
719✔
535
            : $className;
754✔
536
    }
537
}
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