1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\Container; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
|
9
|
|
|
class Container implements ContainerInterface |
10
|
|
|
{ |
11
|
|
|
private $autowire; |
12
|
|
|
private $loadedDependencies; |
13
|
|
|
private $configuredDependencies; |
14
|
|
|
/** @var InstanceResolver */ |
15
|
|
|
private $resolver; |
16
|
|
|
|
17
|
13 |
|
public function __construct(array $configuredDependencies, bool $autowire) |
18
|
|
|
{ |
19
|
13 |
|
$this->configuredDependencies = new ContainerConfig($configuredDependencies); |
20
|
13 |
|
$this->loadedDependencies = new InstanceCollection(); |
21
|
13 |
|
$this->loadedDependencies->set('config', $configuredDependencies['config']); |
22
|
13 |
|
$this->autowire = $autowire; |
23
|
13 |
|
} |
24
|
|
|
|
25
|
12 |
|
public function get($id) |
26
|
|
|
{ |
27
|
12 |
|
if ($this->loadedDependencies->has($id)) { |
28
|
4 |
|
return $this->loadedDependencies->get($id); |
29
|
|
|
} |
30
|
|
|
|
31
|
11 |
|
if ($this->autowire) { |
32
|
9 |
|
$this->setInstanceResolver(); |
33
|
9 |
|
$this->resolver->setInstanceOf($id); |
34
|
8 |
|
return $this->loadedDependencies->get($id); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
$this->loadedDependencies->set($id, $this->getService($id)); |
38
|
|
|
|
39
|
1 |
|
return $this->loadedDependencies->get($id); |
40
|
|
|
} |
41
|
|
|
|
42
|
6 |
|
public function has($id): bool |
43
|
|
|
{ |
44
|
6 |
|
return $this->loadedDependencies->has($id) |
45
|
6 |
|
|| $this->configuredDependencies->has($id); |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
private function getService(string $id) |
49
|
|
|
{ |
50
|
2 |
|
if (is_callable($this->configuredDependencies->get($id))) { |
51
|
1 |
|
$callableService = $this->configuredDependencies->get($id); |
52
|
1 |
|
return $callableService($this); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
if (is_object($this->configuredDependencies->get($id))) { |
56
|
1 |
|
return $this->configuredDependencies->get($id); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
throw ServiceNotFoundException::forId($id); |
60
|
|
|
} |
61
|
|
|
|
62
|
9 |
|
private function setInstanceResolver(): void |
63
|
|
|
{ |
64
|
9 |
|
if (null === $this->resolver) { |
65
|
9 |
|
$this->resolver = new InstanceResolver($this->configuredDependencies, $this->loadedDependencies, $this); |
66
|
|
|
} |
67
|
9 |
|
} |
68
|
|
|
} |
69
|
|
|
|