Completed
Push — master ( 2f7cd3...6e4050 )
by Scott
03:46
created

Environment::exists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace Desmond;
3
use Exception;
4
5
class Environment
6
{
7
    public $values = [];
8
    private $upperEnv = null;
9
10 317
    public function __construct(Environment $upperEnvironment=null)
11
    {
12 317
        $this->upperEnv = $upperEnvironment;
13 317
    }
14
15 314
    public function set($key, $val)
16
    {
17 314
        $this->values[$key] = $val;
18 314
    }
19
20 308
    public function exists($key)
21
    {
22 308
        return null !== $this->find($key);
23
    }
24
25 306
    public function get($key)
26
    {
27 306
        if ($this->exists($key)) {
28 270
            $envWithKey = $this->find($key);
29 270
            return $envWithKey->values[$key];
30
        } else {
31 127
            throw new Exception('Symbol "' . $key . '" not found in environment.');
32
        }
33
    }
34
35 308
    public function find($key)
36
    {
37 308
        if (array_key_exists($key, $this->values)) {
38 271
            return $this;
39 129
        } else if (null !== $this->upperEnv) {
40 26
            return $this->upperEnv->find($key);
41
        } else {
42 128
            return null;
43
        }
44
    }
45
46 26
    public function makeChild()
47
    {
48 26
        $newEnvId = Environment::getNewEnvId($this->values);
49 26
        $newEnv = new Environment($this);
50
51 26
        $this->set($newEnvId, $newEnv);
52 26
        return $newEnvId;
53
    }
54
55 20
    public function getParent()
56
    {
57 20
        return $this->upperEnv;
58
    }
59
60 23
    public function destroyChild($child)
61
    {
62 23
        unset($this->values[$child]);
63 23
    }
64
65 26
    public static function getNewEnvId($values)
66
    {
67
        do {
68 26
            $envId = 'let_' . mt_rand(); // Most probably, this will only happen once.
69 26
        } while (array_key_exists($envId, $values));
70 26
        return $envId;
71
    }
72
}
73