Completed
Push — v4.0-dev ( 6660e2...b14a8f )
by
unknown
11s
created

Container::merge()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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