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