benanamen /
perfect-container
| 1 | <?php declare(strict_types=1); |
||
| 2 | |||
| 3 | namespace PerfectApp\Container; |
||
| 4 | |||
| 5 | use Closure; |
||
| 6 | use ReflectionClass; |
||
| 7 | use ReflectionException; |
||
| 8 | use RuntimeException; |
||
| 9 | |||
| 10 | class Container |
||
| 11 | { |
||
| 12 | private array $instances = []; |
||
| 13 | private array $bindings = []; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * Binds an abstract to a concrete implementation. |
||
| 17 | * |
||
| 18 | * @deprecated Will be removed in Version 2. Use set() instead. |
||
| 19 | */ |
||
| 20 | 2 | public function bind(string $abstract, mixed $concrete): void |
|
| 21 | { |
||
| 22 | 2 | $this->bindings[$abstract] = $concrete; |
|
| 23 | } |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Sets an abstract to a concrete implementation (alias for bind). |
||
| 27 | */ |
||
| 28 | 1 | public function set(string $abstract, mixed $concrete): void |
|
| 29 | { |
||
| 30 | 1 | $this->bindings[$abstract] = $concrete; |
|
| 31 | } |
||
| 32 | |||
| 33 | 8 | public function get(string $className): mixed |
|
| 34 | { |
||
| 35 | 8 | if (isset($this->bindings[$className])) { |
|
| 36 | 3 | $concrete = $this->bindings[$className]; |
|
| 37 | |||
| 38 | 3 | if ($concrete instanceof Closure) { |
|
| 39 | 1 | return $concrete($this); |
|
| 40 | } |
||
| 41 | |||
| 42 | 2 | $className = $concrete; |
|
| 43 | } |
||
| 44 | |||
| 45 | 7 | if (!isset($this->instances[$className])) { |
|
| 46 | try { |
||
| 47 | 7 | $reflectionClass = new ReflectionClass($className); |
|
| 48 | 1 | } catch (ReflectionException $e) { |
|
| 49 | 1 | error_log("Failed to create ReflectionClass for $className: {$e->getMessage()}"); |
|
| 50 | 1 | http_response_code(500); |
|
| 51 | 1 | throw new RuntimeException("Failed to create ReflectionClass for $className: {$e->getMessage()}"); |
|
| 52 | } |
||
| 53 | |||
| 54 | 6 | $constructor = $reflectionClass->getConstructor(); |
|
| 55 | |||
| 56 | 6 | if ($constructor) { |
|
| 57 | 2 | $params = $constructor->getParameters(); |
|
| 58 | 2 | $dependencies = []; |
|
| 59 | |||
| 60 | 2 | foreach ($params as $param) { |
|
| 61 | 1 | $type = $param->getType(); |
|
| 62 | 1 | if ($type && !$type->isBuiltin()) { |
|
| 63 | 1 | $dependency = $type->getName(); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 64 | 1 | $dependencies[] = $this->get($dependency); |
|
| 65 | } |
||
| 66 | } |
||
| 67 | |||
| 68 | try { |
||
| 69 | 2 | $this->instances[$className] = $reflectionClass->newInstanceArgs($dependencies); |
|
| 70 | 1 | } catch (ReflectionException $e) { |
|
| 71 | 2 | throw new RuntimeException("Failed to instantiate $className: {$e->getMessage()}"); |
|
| 72 | } |
||
| 73 | } else { |
||
| 74 | 5 | $this->instances[$className] = new $className(); |
|
| 75 | } |
||
| 76 | } |
||
| 77 | |||
| 78 | 5 | return $this->instances[$className]; |
|
| 79 | } |
||
| 80 | } |
||
| 81 |