|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Effectra\Router; |
| 6 | + |
| 7 | +use Psr\Container\ContainerInterface; |
| 8 | + |
| 9 | +/** |
| 10 | + * Class Resolver |
| 11 | + * |
| 12 | + * A simple class resolver that supports dependency injection through a PSR-11 container. |
| 13 | + */ |
| 14 | +class Resolver |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @var ContainerInterface|null The dependency injection container. |
| 18 | + */ |
| 19 | + protected static ?ContainerInterface $container = null; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var bool Flag indicating whether the container is in use. |
| 23 | + */ |
| 24 | + protected static bool $isUseContainer = false; |
| 25 | + |
| 26 | + /** |
| 27 | + * Set the dependency injection container for the Resolver class. |
| 28 | + * |
| 29 | + * @param ContainerInterface $container The dependency injection container to set. |
| 30 | + * @return void |
| 31 | + */ |
| 32 | + public static function setContainer(ContainerInterface $container): void |
| 33 | + { |
| 34 | + static::$container = $container; |
| 35 | + static::$isUseContainer = true; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Resolve an instance of a class, supporting dependency injection through the container. |
| 40 | + * |
| 41 | + * @param string $class The class to resolve. |
| 42 | + * @param mixed ...$args Accepts a variable number of arguments which are passed to the class constructor, much like {@see call_user_func} |
| 43 | + * @return object An instance of the resolved class. |
| 44 | + * @throws \RuntimeException If the class has dependencies but no container is provided. |
| 45 | + */ |
| 46 | + public static function resolveClass($class,...$args): object |
| 47 | + { |
| 48 | + if (static::$isUseContainer) { |
| 49 | + return static::$container->get($class); |
| 50 | + } else { |
| 51 | + $reflectionClass = new \ReflectionClass($class); |
| 52 | + |
| 53 | + $constructor = $reflectionClass->getConstructor(); |
| 54 | + |
| 55 | + if (null === $constructor) { |
| 56 | + return $reflectionClass->newInstance($args); |
| 57 | + } |
| 58 | + throw new \RuntimeException("You must use psr/container to resolve class dependencies in $class"); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments