|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace PerfectApp\Container; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use ReflectionClass; |
|
7
|
|
|
use ReflectionException; |
|
8
|
|
|
|
|
9
|
|
|
class Container |
|
10
|
|
|
{ |
|
11
|
|
|
private array $instances = []; |
|
12
|
|
|
private array $bindings = []; |
|
13
|
|
|
|
|
14
|
1 |
|
public function bind(string $abstract, mixed $concrete): void |
|
15
|
|
|
{ |
|
16
|
1 |
|
$this->bindings[$abstract] = $concrete; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
4 |
|
public function get(string $className): object |
|
20
|
|
|
{ |
|
21
|
4 |
|
if (isset($this->bindings[$className])) { |
|
22
|
1 |
|
$concrete = $this->bindings[$className]; |
|
23
|
|
|
|
|
24
|
1 |
|
if ($concrete instanceof Closure) { |
|
25
|
|
|
return $concrete($this); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
1 |
|
$className = $concrete; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
4 |
|
if (!isset($this->instances[$className])) { |
|
32
|
|
|
try { |
|
33
|
4 |
|
$reflectionClass = new ReflectionClass($className); |
|
34
|
|
|
} catch (ReflectionException $e) { |
|
35
|
|
|
error_log("Failed to create ReflectionClass for $className: {$e->getMessage()}"); |
|
36
|
|
|
http_response_code(500); |
|
37
|
|
|
die('Fatal Error. See Error log for details.'); |
|
|
|
|
|
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
4 |
|
$constructor = $reflectionClass->getConstructor(); |
|
41
|
|
|
|
|
42
|
4 |
|
if ($constructor) { |
|
43
|
1 |
|
$params = $constructor->getParameters(); |
|
44
|
1 |
|
$dependencies = []; |
|
45
|
|
|
|
|
46
|
1 |
|
foreach ($params as $param) { |
|
47
|
1 |
|
$type = $param->getType(); |
|
48
|
1 |
|
if ($type && !$type->isBuiltin()) { |
|
49
|
1 |
|
$dependency = $type->getName(); |
|
|
|
|
|
|
50
|
1 |
|
$dependencies[] = $this->get($dependency); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
try { |
|
55
|
1 |
|
$this->instances[$className] = $reflectionClass->newInstanceArgs($dependencies); |
|
56
|
|
|
} catch (ReflectionException $e) { |
|
57
|
|
|
error_log("Failed to instantiate $className: {$e->getMessage()}"); |
|
58
|
1 |
|
die('Fatal Error. See Error log for details.'); |
|
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
} else { |
|
61
|
4 |
|
$this->instances[$className] = new $className(); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
4 |
|
return $this->instances[$className]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example: