|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Micro\Component\DependencyInjection; |
| 4 | + |
| 5 | + |
| 6 | +use Micro\Component\DependencyInjection\Exception\ServiceNotRegisteredException; |
| 7 | +use Micro\Component\DependencyInjection\Exception\ServiceRegistrationException; |
| 8 | +use Psr\Container\ContainerInterface; |
| 9 | +use \Closure; |
| 10 | + |
| 11 | +class Container implements ContainerInterface, ContainerRegistryInterface |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var array<string, object> |
| 15 | + */ |
| 16 | + private array $services; |
| 17 | + |
| 18 | + /** |
| 19 | + * @var array<string, Closure> |
| 20 | + */ |
| 21 | + private array $servicesRaw; |
| 22 | + |
| 23 | + |
| 24 | + public function __construct() |
| 25 | + { |
| 26 | + $this->services = []; |
| 27 | + $this->servicesRaw = []; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * {@inheritDoc} |
| 32 | + */ |
| 33 | + public function get(string $id) |
| 34 | + { |
| 35 | + return $this->lookupService($id); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * {@inheritDoc} |
| 40 | + */ |
| 41 | + public function has(string $id): bool |
| 42 | + { |
| 43 | + return !empty($this->servicesRaw[$id]) || !empty($this->services[$id]); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * {@inheritDoc} |
| 48 | + */ |
| 49 | + public function register(string $id, \Closure $service): void |
| 50 | + { |
| 51 | + if($this->has($id)) { |
| 52 | + throw new ServiceRegistrationException($id); |
| 53 | + } |
| 54 | + |
| 55 | + $this->servicesRaw[$id] = $service; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * @param string $id |
| 60 | + * @return object |
| 61 | + */ |
| 62 | + private function lookupService(string $id): object |
| 63 | + { |
| 64 | + if(!empty($this->services[$id])) { |
| 65 | + return $this->services[$id]; |
| 66 | + } |
| 67 | + |
| 68 | + return $this->createServiceInstance($id); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * @param string $id |
| 73 | + * @return object |
| 74 | + */ |
| 75 | + private function createServiceInstance(string $id): object |
| 76 | + { |
| 77 | + if(empty($this->servicesRaw[$id])) { |
| 78 | + throw new ServiceNotRegisteredException($id); |
| 79 | + } |
| 80 | + |
| 81 | + $raw = $this->servicesRaw[$id]; |
| 82 | + $service = $raw($this); |
| 83 | + |
| 84 | + $this->services[$id] = $service; |
| 85 | + |
| 86 | + return $service; |
| 87 | + } |
| 88 | +} |
0 commit comments