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

Environment   A

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 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