1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace OpenEngine\Mika\Core\Components\Di; |
4
|
|
|
|
5
|
|
|
use OpenEngine\Mika\Core\Components\Di\Exceptions\MethodNotFoundException; |
6
|
|
|
use OpenEngine\Mika\Core\Components\Di\Exceptions\MissingMethodArgumentException; |
7
|
|
|
use OpenEngine\Mika\Core\Components\Di\Exceptions\ServiceNotFoundException; |
8
|
|
|
use OpenEngine\Mika\Core\Components\Di\Interfaces\DiConfigInterface; |
9
|
|
|
use OpenEngine\Mika\Core\Components\Di\Traits\CreateObjectTrait; |
10
|
|
|
use Psr\Container\ContainerInterface; |
11
|
|
|
|
12
|
|
|
class Di implements ContainerInterface |
13
|
|
|
{ |
14
|
|
|
use CreateObjectTrait; |
|
|
|
|
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Created services |
18
|
|
|
* |
19
|
|
|
* @var object[] |
20
|
|
|
*/ |
21
|
|
|
private $singletons; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Registered service names |
25
|
|
|
* |
26
|
|
|
* @var string[] |
27
|
|
|
*/ |
28
|
|
|
private $services; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Di constructor. |
32
|
|
|
* @param DiConfigInterface $diConfig |
33
|
|
|
*/ |
34
|
|
|
public function __construct(DiConfigInterface $diConfig) |
35
|
|
|
{ |
36
|
|
|
$diConfig->registerObject(ContainerInterface::class, $this); |
37
|
|
|
$this->services = $diConfig->getServices(); |
38
|
|
|
$this->singletons = $diConfig->getServiceObjects(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* {@inheritdoc} |
43
|
|
|
* @throws MethodNotFoundException |
44
|
|
|
* @throws MissingMethodArgumentException |
45
|
|
|
*/ |
46
|
|
|
public function get($id): object |
47
|
|
|
{ |
48
|
|
|
if (!$this->has($id)) { |
49
|
|
|
throw new ServiceNotFoundException('Service ' . $id . ' is not found'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$singleton = $this->getSingleton($id); |
53
|
|
|
|
54
|
|
|
if ($singleton !== null) { |
55
|
|
|
return $singleton; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $this->createObject($this->getService($id)); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @inheritdoc |
63
|
|
|
*/ |
64
|
|
|
public function has($id): bool |
65
|
|
|
{ |
66
|
|
|
return $this->getService($id) !== null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param string $id |
71
|
|
|
* @return string|null |
72
|
|
|
*/ |
73
|
|
|
private function getService(string $id): ?string |
74
|
|
|
{ |
75
|
|
|
if (isset($this->services[$id])) { |
76
|
|
|
return $this->services[$id]; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return null; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param string $id |
84
|
|
|
* @return \object|null |
85
|
|
|
*/ |
86
|
|
|
private function getSingleton(string $id): ?object |
87
|
|
|
{ |
88
|
|
|
if (isset($this->singletons[$id])) { |
89
|
|
|
return $this->singletons[$id]; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return null; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|