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

Container   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 78.79%

Importance

Changes 0
Metric Value
dl 0
loc 48
ccs 26
cts 33
cp 0.7879
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 6 3
A merge() 0 4 1
A wrap() 0 9 2
A get() 0 13 4
A has() 0 3 1
A unbox() 0 7 2
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