-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVariableBag.php
89 lines (72 loc) · 2.08 KB
/
VariableBag.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace EXSyst\Common;
class VariableBag
{
private $data;
private $lazy;
public function __construct(array $data = [])
{
$this->data = $data;
$this->lazy = [];
}
public function get($key)
{
if (isset($this->lazy[$key])) {
$this->data[$key] = call_user_func($this->lazy[$key]);
unset($this->lazy[$key]);
}
if (!isset($this->data[$key])) {
throw new \LogicException(sprintf('The variable "%s" must be defined.', $key));
}
return $this->data[$key];
}
public function set($key, $value)
{
$this->data[$key] = $value;
unset($this->lazy[$key]);
return $this;
}
public function setLazy($key, $lazyValue, $service = null, $method = null)
{
if (isset($service)) {
$container = $lazyValue;
if (isset($method)) {
$lazyValue = function () use ($container, $service, $method) {
return call_user_func($container->get($service), $method);
};
} else {
$lazyValue = function () use ($container, $service) {
return $container->get($service);
};
}
} elseif (isset($method)) {
$lazyValue = [$lazyValue, $method];
}
if (!is_callable($lazyValue)) {
throw new \LogicException('A "lazy value" must be a callable.');
}
$this->lazy[$key] = $lazyValue;
unset($this->data[$key]);
return $this;
}
public function has($key)
{
return isset($this->data[$key]) || isset($this->lazy[$key]);
}
public function remove($key)
{
unset($this->data[$key]);
unset($this->lazy[$key]);
return $this;
}
public function toArray()
{
if (!empty($this->lazy)) {
foreach ($this->lazy as $key => $lazyValue) {
$this->data[$key] = call_user_func($lazyValue);
}
$this->lazy = [];
}
return $this->data;
}
}