ContextBag   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 79
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 9 2
A tryGet() 0 12 4
A set() 0 4 1
A remove() 0 6 2
1
<?php
2
namespace PSB\Core\Util;
3
4
5
use PSB\Core\Exception\OutOfBoundsException;
6
7
class ContextBag
8
{
9
    /**
10
     * @var ContextBag
11
     */
12
    protected $parent;
13
14
    /**
15
     * @var array
16
     */
17
    protected $stash = [];
18
19
    /**
20
     * @param ContextBag|null $parent
21
     */
22 123
    public function __construct(ContextBag $parent = null)
23
    {
24 123
        $this->parent = $parent;
25 123
    }
26
27
    /**
28
     * Searches for value of $key in this context and the parent context.
29
     * Returns the value if found, throws an exception it's not found.
30
     *
31
     * @param string $key
32
     *
33
     * @throws OutOfBoundsException
34
     * @return mixed
35
     */
36 6
    public function get($key)
37
    {
38 6
        $value = $this->tryGet($key);
39 6
        if (!$value) {
40 2
            throw new OutOfBoundsException("The given key '$key' was not present in the context.");
41
        }
42
43 4
        return $value;
44
    }
45
46
    /**
47
     * Searches for value of $key in this context and the parent context.
48
     * Returns the value if found, null if not found.
49
     *
50
     * @param string $key
51
     *
52
     * @return mixed
53
     */
54 7
    public function tryGet($key)
55
    {
56 7
        if (isset($this->stash[$key])) {
57 4
            return $this->stash[$key];
58
        }
59
60 4
        if ($this->parent && $this->parent->tryGet($key) !== null) {
61 1
            return $this->parent->tryGet($key);
62
        }
63
64 3
        return null;
65
    }
66
67
    /**
68
     * @param string $key
69
     * @param mixed  $value
70
     */
71 5
    public function set($key, $value)
72
    {
73 5
        $this->stash[$key] = $value;
74 5
    }
75
76
    /**
77
     * @param string $key
78
     */
79 1
    public function remove($key)
80
    {
81 1
        if (isset($this->stash[$key])) {
82 1
            unset($this->stash[$key]);
83
        }
84 1
    }
85
}
86