1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Plates\Util; |
4
|
|
|
|
5
|
|
|
final class Container |
6
|
|
|
{ |
7
|
|
|
private $boxes = []; |
8
|
|
|
private $cached = []; |
9
|
|
|
|
10
|
|
|
public function add($id, $value) { |
11
|
|
|
if (array_key_exists($id, $this->cached)) { |
12
|
|
|
throw new \LogicException('Cannot add service after it has been frozen.'); |
13
|
|
|
} |
14
|
|
|
$this->boxes[$id] = [$value, $value instanceof \Closure ? true : false]; |
15
|
|
|
} |
16
|
|
|
public function merge($id, array $values) { |
17
|
|
|
$old = $this->get($id); |
18
|
|
|
$this->add($id, array_merge($old, $values)); |
19
|
|
|
} |
20
|
|
|
public function wrap($id, $wrapper) { |
21
|
|
|
if (!$this->has($id)) { |
22
|
|
|
throw new \LogicException('Cannot wrap a service that does not exist.'); |
23
|
|
|
} |
24
|
|
|
$box = $this->boxes[$id]; |
25
|
|
|
$this->boxes[$id] = [function($c) use ($box, $wrapper) { |
26
|
|
|
return $wrapper($this->unbox($box, $c), $c); |
27
|
|
|
}, true]; |
28
|
|
|
} |
29
|
|
|
public function get($id) { |
30
|
|
|
if (array_key_exists($id, $this->cached)) { |
31
|
|
|
return $this->cached[$id]; |
32
|
|
|
} |
33
|
|
|
if (!$this->has($id)) { |
34
|
|
|
throw new \LogicException('Cannot retrieve service that does exist.'); |
35
|
|
|
} |
36
|
|
|
$result = $this->unbox($this->boxes[$id], $this); |
37
|
|
|
if ($this->boxes[$id][1]) { // only cache services |
38
|
|
|
$this->cached[$id] = $result; |
39
|
|
|
} |
40
|
|
|
return $result; |
41
|
|
|
} |
42
|
|
|
public function has($id) { |
43
|
|
|
return array_key_exists($id, $this->boxes); |
44
|
|
|
} |
45
|
|
|
private function unbox($box, Container $c) { |
46
|
|
|
list($value, $is_factory) = $box; |
47
|
|
|
if (!$is_factory) { |
48
|
|
|
return $value; |
49
|
|
|
} |
50
|
|
|
return $value($c); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|