1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace pjpawel\LightApi\Container; |
4
|
|
|
|
5
|
|
|
use pjpawel\LightApi\Container\Definition\ClassDefinition; |
6
|
|
|
use pjpawel\LightApi\Container\Definition\DefinedDefinition; |
7
|
|
|
use pjpawel\LightApi\Container\Definition\Definition; |
8
|
|
|
use pjpawel\LightApi\Container\Definition\InDirectDefinition; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
|
11
|
|
|
trait ContainerTrait |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var array<string,Definition> |
15
|
|
|
*/ |
16
|
|
|
public array $definitions; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param string $id |
20
|
|
|
* @return object |
21
|
|
|
* @throws \Psr\Container\ContainerExceptionInterface |
22
|
|
|
* @throws \Psr\Container\NotFoundExceptionInterface |
23
|
|
|
* @throws \ReflectionException |
24
|
|
|
* @throws \pjpawel\LightApi\Container\ContainerNotFoundException |
25
|
|
|
*/ |
26
|
|
|
public function get(string $id): object |
27
|
|
|
{ |
28
|
|
|
if (!isset($this->definitions[$id])) { |
29
|
|
|
throw new ContainerNotFoundException("Service $id not found"); |
30
|
|
|
} |
31
|
|
|
if ($this->definitions[$id]->object === null) { |
32
|
|
|
$definition = $this->definitions[$id]; |
33
|
|
|
if ($definition instanceof ClassDefinition) { |
34
|
|
|
$this->definitions[$id]->object = (new ReflectionClass($definition->name)) |
35
|
|
|
->newInstanceArgs($definition->arguments); |
36
|
|
|
} elseif ($definition instanceof InDirectDefinition) { |
37
|
|
|
return $this->get($definition->className); |
38
|
|
|
} else { |
39
|
|
|
/** @var DefinedDefinition $definition */ |
40
|
|
|
$this->definitions[$id]->object = $definition->load(); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
return $this->definitions[$id]->object; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $id |
48
|
|
|
* @return bool |
49
|
|
|
*/ |
50
|
|
|
public function has(string $id): bool |
51
|
|
|
{ |
52
|
|
|
return isset($this->definitions[$id]); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
} |