1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PSB\Core\ObjectBuilder; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use PSB\Core\Exception\ServiceNotFoundException; |
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
|
9
|
|
|
class Builder implements BuilderInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var Container |
13
|
|
|
*/ |
14
|
|
|
private $internalContainer; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var ContainerInterface |
18
|
|
|
*/ |
19
|
|
|
private $externalContainer; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Container $internalContainer |
23
|
|
|
* @param ContainerInterface|null $externalContainer |
24
|
|
|
*/ |
25
|
12 |
|
public function __construct( |
26
|
|
|
Container $internalContainer, |
27
|
|
|
ContainerInterface $externalContainer = null |
28
|
|
|
) { |
29
|
12 |
|
$this->internalContainer = $internalContainer; |
30
|
12 |
|
$this->externalContainer = $externalContainer; |
31
|
12 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $id The unique identifier for the parameter or object |
35
|
|
|
* @param mixed $value The value of the parameter or a closure to define an object |
36
|
|
|
*/ |
37
|
1 |
|
public function defineSingleton($id, $value) |
38
|
|
|
{ |
39
|
1 |
|
$this->internalContainer->offsetSet($id, $value); |
40
|
1 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $id The unique identifier for the parameter or object |
44
|
|
|
* @param callable $callable A service definition to be used as a factory |
45
|
|
|
*/ |
46
|
1 |
|
public function defineFactory($id, $callable) |
47
|
|
|
{ |
48
|
1 |
|
$this->internalContainer->offsetSet($id, $this->internalContainer->factory($callable)); |
49
|
1 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param string $id |
53
|
|
|
* |
54
|
|
|
* @return bool |
55
|
|
|
*/ |
56
|
3 |
|
public function isDefined($id) |
57
|
|
|
{ |
58
|
3 |
|
return $this->internalContainer->offsetExists($id) || |
59
|
3 |
|
$this->externalContainer && $this->externalContainer->has($id); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param string $id |
64
|
|
|
* |
65
|
|
|
* @return mixed |
66
|
|
|
* |
67
|
|
|
* @throws ServiceNotFoundException if the service does not exist |
68
|
|
|
*/ |
69
|
4 |
|
public function build($id) |
70
|
|
|
{ |
71
|
4 |
|
if ($this->internalContainer->offsetExists($id)) { |
72
|
1 |
|
return $this->internalContainer->offsetGet($id); |
73
|
|
|
} |
74
|
|
|
|
75
|
3 |
|
if ($this->externalContainer && $this->externalContainer->has($id)) { |
76
|
1 |
|
return $this->externalContainer->get($id); |
77
|
|
|
} |
78
|
|
|
|
79
|
2 |
|
throw new ServiceNotFoundException("Service '$id' not found in any of the containers."); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param string $id |
84
|
|
|
*/ |
85
|
1 |
|
public function dispose($id) |
86
|
|
|
{ |
87
|
1 |
|
$this->internalContainer->offsetUnset($id); |
88
|
1 |
|
} |
89
|
|
|
} |
90
|
|
|
|