Completed
Push — v4.0-dev ( b14a8f...3b7e85 )
by
unknown
19:33 queued 05:42
created

Container   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 48
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
    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