|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Deployee\Components\Container; |
|
4
|
|
|
|
|
5
|
|
|
class Container implements ContainerInterface |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* @var \Pimple\Container |
|
9
|
|
|
*/ |
|
10
|
|
|
private $container; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @param array $values |
|
14
|
|
|
* @throws ContainerException |
|
15
|
|
|
*/ |
|
16
|
6 |
|
public function __construct(array $values = array()) |
|
17
|
|
|
{ |
|
18
|
6 |
|
$this->container = new \Pimple\Container(); |
|
19
|
6 |
|
foreach ($values as $id => $value){ |
|
20
|
4 |
|
$this->set($id, $value); |
|
21
|
|
|
} |
|
22
|
6 |
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param string $id |
|
26
|
|
|
* @return mixed |
|
27
|
|
|
* @throws ContainerException |
|
28
|
|
|
*/ |
|
29
|
4 |
|
public function get(string $id) |
|
30
|
|
|
{ |
|
31
|
4 |
|
if(!isset($this->container[$id])){ |
|
32
|
1 |
|
throw new ContainerException(sprintf('Unknown identifier %s', $id)); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
3 |
|
return $this->container[$id]; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param string $id |
|
40
|
|
|
* @param mixed $value |
|
41
|
|
|
* @return void |
|
42
|
|
|
* @throws ContainerException |
|
43
|
|
|
*/ |
|
44
|
4 |
|
public function set(string $id, $value) |
|
45
|
|
|
{ |
|
46
|
4 |
|
if(isset($this->container[$id])){ |
|
47
|
1 |
|
throw new ContainerException(sprintf( |
|
48
|
1 |
|
'Element with id %s already exists. You must use "extend" to modify the value', |
|
49
|
|
|
$id |
|
50
|
|
|
)); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
4 |
|
if(is_callable($value)){ |
|
54
|
3 |
|
$me = $this; |
|
55
|
3 |
|
$result = function() use($value, $me){ |
|
56
|
3 |
|
return $value($me); |
|
57
|
3 |
|
}; |
|
58
|
|
|
|
|
59
|
3 |
|
$value = $result; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
4 |
|
$this->container[$id] = $value; |
|
63
|
4 |
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param string $id |
|
67
|
|
|
* @param callable $callable |
|
68
|
|
|
*/ |
|
69
|
2 |
|
public function extend(string $id, callable $callable) |
|
70
|
|
|
{ |
|
71
|
2 |
|
$value = $this->get($id); |
|
72
|
2 |
|
$this->container->offsetUnset($id); |
|
73
|
2 |
|
$this->set($id, function(ContainerInterface $container) use ($value, $callable){ |
|
74
|
2 |
|
return $callable($value, $container); |
|
75
|
2 |
|
}); |
|
76
|
|
|
} |
|
77
|
|
|
} |