Environment   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 68
ccs 33
cts 33
cp 1
rs 10
c 1
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A set() 0 4 1
A exists() 0 4 1
A get() 0 9 2
A find() 0 10 3
A makeChild() 0 8 1
A getParent() 0 4 1
A destroyChild() 0 4 1
A getNewEnvId() 0 7 2
1
<?php
2
namespace Desmond;
3
use Exception;
4
5
class Environment
6
{
7
    public $values = [];
8
    private $upperEnv = null;
9
10 343
    public function __construct(Environment $upperEnvironment=null)
11
    {
12 343
        $this->upperEnv = $upperEnvironment;
13 343
    }
14
15 340
    public function set($key, $val)
16
    {
17 340
        $this->values[$key] = $val;
18 340
    }
19
20 334
    public function exists($key)
21
    {
22 334
        return null !== $this->find($key);
23
    }
24
25 332
    public function get($key)
26
    {
27 332
        if ($this->exists($key)) {
28 295
            $envWithKey = $this->find($key);
29 295
            return $envWithKey->values[$key];
30
        } else {
31 129
            throw new Exception('Symbol "' . $key . '" not found in environment.');
32
        }
33
    }
34
35 334
    public function find($key)
36
    {
37 334
        if (array_key_exists($key, $this->values)) {
38 296
            return $this;
39 131
        } else if (null !== $this->upperEnv) {
40 27
            return $this->upperEnv->find($key);
41
        } else {
42 130
            return null;
43
        }
44
    }
45
46 27
    public function makeChild()
47
    {
48 27
        $newEnvId = Environment::getNewEnvId($this->values);
49 27
        $newEnv = new Environment($this);
50
51 27
        $this->set($newEnvId, $newEnv);
52 27
        return $newEnvId;
53
    }
54
55 20
    public function getParent()
56
    {
57 20
        return $this->upperEnv;
58
    }
59
60 24
    public function destroyChild($child)
61
    {
62 24
        unset($this->values[$child]);
63 24
    }
64
65 27
    public static function getNewEnvId($values)
66
    {
67
        do {
68 27
            $envId = 'let_' . mt_rand(); // Most probably, this will only happen once.
69 27
        } while (array_key_exists($envId, $values));
70 27
        return $envId;
71
    }
72
}
73