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