Lines
100.00%
10 / 10
Functions and Methods
100.00%
2 / 2
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| TypedContainer | 100.00% | 10 / 10 | 100.00% | 2 / 2 | 3 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| resolveService | 100.00% | 9 / 9 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Container; | |
| 6 | ||
| 7 | use Stewart\Runtime\Exception\ContainerError; | |
| 8 | use Stewart\Runtime\Exception\ContainerException; | |
| 9 | use Symfony\Component\DependencyInjection\ContainerInterface; | |
| 10 | ||
| 11 | final readonly class TypedContainer | |
| 12 | { | |
| 13 | public function __construct(private ContainerInterface $container) {} | |
| 14 | ||
| 15 | /** | |
| 16 | * @template T of object | |
| 17 | * @param class-string<T> $type | |
| 18 | * @return T | |
| 19 | * @throws ContainerException | |
| 20 | */ | |
| 21 | public function resolveService(string $type, ?string $id = null): object | |
| 22 | { | |
| 23 | $service = $this->container->get($id ?? $type); | |
| 24 | ||
| 25 | if (!$service instanceof $type) { | |
| 26 | throw ContainerException::createForReason( | |
| 27 | ContainerError::ServiceTypeMismatch, | |
| 28 | serviceId: $id ?? $type, | |
| 29 | expectedType: $type, | |
| 30 | actualType: get_debug_type($service), | |
| 31 | ); | |
| 32 | } | |
| 33 | ||
| 34 | return $service; | |
| 35 | } | |
| 36 | } |