-
Notifications
You must be signed in to change notification settings - Fork 22
/
LazyMembers.inc
138 lines (124 loc) · 2.33 KB
/
LazyMembers.inc
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php
/**
* @file
*
*/
module_load_include('inc', 'php_lib', 'Members');
/**
* Lazy Member.
*/
class LazyMember {
/**
* A valid argument for call_user_func.
*
* @var mixed
*/
protected $function;
/**
*
*
* @var mixed
*/
protected $parameters;
/**
* The result from the function.
*
* @var mixed
*/
protected $value;
/**
* Has the value
*
* @var boolean
*/
public $dirty;
/**
*
* @param mixed $function
* @param object $owner
*/
public function __construct($function, $parameters = NULL) {
$this->function = $function;
$this->parameters = $parameters;
$this->value = NULL;
$this->dirty = TRUE;
}
/**
*
*/
public function __invoke() {
if ($this->dirty) {
$this->value = call_user_func($this->function, $this->parameters);
$this->dirty = FALSE;
}
return $this->value;
}
}
/**
* Lazy Members.
*/
class LazyMembers extends Members {
/**
*
* @var array
*/
protected $functions;
/**
* Create a LazyMembers object.
*
* @param array $members
* @param array $params
*/
public function __construct(array $members, array $params = NULL) {
parent::__construct($members, $params);
}
/**
* Checks to see if a member is lazy.
*
* @param string $name
* @return boolean
*/
public function isLazy($name) {
return $this->exists($name) && ($this->values[$name] instanceof LazyMember);
}
/**
* Set the member is as dirty.
*
* @param string $name
*/
public function setDirty($name) {
if ($this->isLazy($name)) {
$this->values[$name]->dirty = TRUE;
}
}
/**
* Get a value for the given member if it exists.
*
* Return NULL if the member doesn't exist or isn't set.
*
* @param string $name
* @return mixed
*/
public function __get($name) {
if ($this->isLazy($name)) {
return $this->values[$name]();
}
elseif ($this->exists($name)) {
return $this->values[$name];
}
return NULL;
}
/**
* Set the value for the given member if it exists.
*
* Note that this doesn't create a new element.
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value) {
if ($this->has($name) && !$this->isLazy($name)) {
$this->values[$name] = $value;
}
}
}