| Total Complexity | 9 |
| Total Lines | 55 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 9 | class Instantiator implements ContainerInterface |
||
| 10 | { |
||
| 11 | /** @var array<string, object> */ |
||
| 12 | private array $cache = []; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Implements ContainerInterface |
||
| 16 | * |
||
| 17 | * @param string $id |
||
| 18 | * @return object |
||
| 19 | */ |
||
| 20 | public function get($id) |
||
| 21 | { |
||
| 22 | return $this->getSharedObject($id); |
||
| 23 | } |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Implements ContainerInterface |
||
| 27 | * |
||
| 28 | * @param string $id |
||
| 29 | * @return boolean |
||
| 30 | */ |
||
| 31 | public function has($id) |
||
| 32 | { |
||
| 33 | return isset($this->cache[$id]); |
||
| 34 | } |
||
| 35 | |||
| 36 | public function getNewObject(string $classname): object |
||
| 37 | { |
||
| 38 | if (!class_exists($classname)) { |
||
| 39 | throw new \RuntimeException("Class '$classname' does not exist"); |
||
| 40 | } |
||
| 41 | |||
| 42 | $reflector = new \ReflectionClass($classname); |
||
| 43 | |||
| 44 | if (!$reflector->isInstantiable()) { |
||
| 45 | throw new \RuntimeException("Unable to instantiate non-instantiable class '$classname'"); |
||
| 46 | } |
||
| 47 | |||
| 48 | $constructor = $reflector->getConstructor(); |
||
| 49 | |||
| 50 | if ($constructor && $constructor->getNumberOfRequiredParameters()) { |
||
| 51 | throw new \RuntimeException("Unable to instantiate '$classname' with no parameters"); |
||
| 52 | } |
||
| 53 | |||
| 54 | return new $classname(); |
||
| 55 | } |
||
| 56 | |||
| 57 | public function getSharedObject(string $classname): object |
||
| 64 | } |
||
| 65 | } |
||
| 66 |