|
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 addComposed($id, callable $define_composers) { |
|
17
|
|
|
$this->add($id, function($c) use ($id) { |
|
18
|
|
|
return compose(...array_values($c->get($id . '.composers'))); |
|
19
|
|
|
}); |
|
20
|
|
|
$this->add($id . '.composers', $define_composers); |
|
21
|
|
|
} |
|
22
|
|
|
public function wrapComposed($id, callable $wrapped) { |
|
23
|
|
|
$this->wrap($id . '.composers', $wrapped); |
|
24
|
|
|
} |
|
25
|
|
|
public function addStack($id, callable $define_stack) { |
|
26
|
|
|
$this->add($id, function($c) use ($id) { |
|
27
|
|
|
return stack($c->get($id . '.stack')); |
|
28
|
|
|
}); |
|
29
|
|
|
$this->add($id . '.stack', $define_stack); |
|
30
|
|
|
} |
|
31
|
|
|
public function wrapStack($id, callable $wrapped) { |
|
32
|
|
|
$this->wrap($id . '.stack', $wrapped); |
|
33
|
|
|
} |
|
34
|
|
|
public function merge($id, array $values) { |
|
35
|
|
|
$old = $this->get($id); |
|
36
|
|
|
$this->add($id, array_merge($old, $values)); |
|
37
|
|
|
} |
|
38
|
|
|
public function wrap($id, $wrapper) { |
|
39
|
|
|
if (!$this->has($id)) { |
|
40
|
|
|
throw new \LogicException('Cannot wrap service ' . $id . ' that does not exist.'); |
|
41
|
|
|
} |
|
42
|
|
|
$box = $this->boxes[$id]; |
|
43
|
|
|
$this->boxes[$id] = [function($c) use ($box, $wrapper) { |
|
44
|
|
|
return $wrapper($this->unbox($box, $c), $c); |
|
45
|
|
|
}, true]; |
|
46
|
|
|
} |
|
47
|
|
|
public function get($id) { |
|
48
|
|
|
if (array_key_exists($id, $this->cached)) { |
|
49
|
|
|
return $this->cached[$id]; |
|
50
|
|
|
} |
|
51
|
|
|
if (!$this->has($id)) { |
|
52
|
|
|
throw new \LogicException('Cannot retrieve service ' . $id . ' that does exist.'); |
|
53
|
|
|
} |
|
54
|
|
|
$result = $this->unbox($this->boxes[$id], $this); |
|
55
|
|
|
if ($this->boxes[$id][1]) { // only cache services |
|
56
|
|
|
$this->cached[$id] = $result; |
|
57
|
|
|
} |
|
58
|
|
|
return $result; |
|
59
|
|
|
} |
|
60
|
|
|
public function has($id) { |
|
61
|
|
|
return array_key_exists($id, $this->boxes); |
|
62
|
|
|
} |
|
63
|
|
|
private function unbox($box, Container $c) { |
|
64
|
|
|
list($value, $is_factory) = $box; |
|
65
|
|
|
if (!$is_factory) { |
|
66
|
|
|
return $value; |
|
67
|
|
|
} |
|
68
|
|
|
return $value($c); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|