-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.php
More file actions
367 lines (306 loc) · 10.3 KB
/
Queue.php
File metadata and controls
367 lines (306 loc) · 10.3 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<?PHP
/**
* qcEvents - Call multiple asynchronous functions in parallel and wait until they are all finished
*
* Copyright (C) 2016 Bernd Holzmueller <bernd@quarxconnect.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
class qcEvents_Queue {
/* Operation-Mode */
const MODE_PARALLEL = 0;
const MODE_SERIAL = 1;
private $Mode = qcEvents_Queue::MODE_PARALLEL;
/* Queued calls */
private $Queue = array ();
/* Invoked calls */
private $Invoked = array ();
/* Call-Results */
private $Results = array ();
/* Result-Callbacks */
private $resultCallbacks = array ();
/* Finish-Callbacks */
private $finishCallbacks = array ();
/* Lock finishQueue()-Call after result-callbacks */
private $lockFinish = false;
// {{{ __debugInfo
/**
* Preprocess output for var_dump()
*
* @access friendly
* @return array
**/
function __debugInfo () {
return array (
'Mode' => ($this->Mode == self::MODE_PARALLEL ? 'parallel' : 'serial'),
'Queued' => count ($this->Queue),
'Invoked' => count ($this->Invoked),
'Finished' => count ($this->Results),
'onResultCallbacks' => count ($this->resultCallbacks),
'onFinishCallbacks' => count ($this->finishCallbacks),
);
}
// }}}
// {{{ setMode
/**
* Set mode of invocation
*
* @param enum $Mode
*
* @access public
* @return void
**/
public function setMode ($Mode) {
if (($Mode == self::MODE_PARALLEL) || ($Mode == self::MODE_SERIAL))
$this->Mode = (int)$Mode;
}
// }}}
// {{{ addCall
/**
* Append a call to our queue and invoke execution
* The first arguement needs to be a callable or instance of a class,
* if an instance is given a second arguement is taken as method-name.
* All other arguments will be passed to the callable.
*
* @param callable $Callable
* @param ...
*
* @access public
* @return mixed
**/
public function addCall ($Callable) {
// Peek all given arguments
$Parameters = func_get_args ();
$Callable = array_shift ($Parameters);
// Make sure we pick the right callable
if (is_object ($Callable) && !($Callable instanceof Closure)) {
// Check if there were enough arguments given
if (count ($Parameters) < 1) {
trigger_error ('Invalid callable given - an object requires a function-name to call');
return false;
}
// Rewrite the callable
$Callable = array ($Callable, array_shift ($Parameters));
// Validate the callable
if (!is_callable ($Callable)) {
trigger_error ('Method does not exist');
return false;
}
// Bail out error if not callable
} elseif (!is_callable ($Callable)) {
trigger_error ('First argument must be callable');
return false;
}
// Push to our queue
if (($this->Mode == self::MODE_SERIAL) && (count ($this->Invoked) > 0)) {
$this->Queue [] = array ($Callable, $Parameters);
return;
}
return $this->invokeCall ($Callable, $Parameters);
}
// }}}
// {{{ invokeCall
/**
* Invoke a callable
*
* @param callable $Callable
* @param array $Parameters
*
* @access private
* @return mixed
**/
private function invokeCall (callable $Callable, array $Parameters) {
// Store as invoked
$this->Invoked [] = array ($Callable, $Parameters);
// Prepare the callback
$Callback = function () use ($Callable, $Parameters) {
$this->processResult ($Callable, $Parameters, func_get_args ());
};
// Create Reflection-Class
if (is_array ($Callable))
$Function = new ReflectionMethod ($Callable [0], $Callable [1]);
else
$Function = new ReflectionFunction ($Callable);
// Analyze parameters of the call
if (!($isPromise = ($Function->getReturnType () == 'qcEvents_Promise'))) {
$CallbackIndex = null;
foreach ($Function->getParameters () as $Index=>$Parameter)
if ($Parameter->isCallable ()) {
$CallbackIndex = $Index;
break;
}
// Store the callback on parameters
if ($CallbackIndex !== null) {
// Make sure parameters is big enough
if (count ($Parameters) < $CallbackIndex)
for ($i = 0; $i < $CallbackIndex; $i++)
if (!isset ($Parameters [$i]))
$Parameters [$i] = null;
// Set the callback
$Parameters [$CallbackIndex] = $Callback;
} else {
trigger_error ('No position for callback detected, just giving it a try', E_USER_NOTICE);
$Parameters [] = $Callback;
}
}
// Do the call
if (is_array ($Callable))
$rc = $Function->invokeArgs ($Callable [0], $Parameters);
else
$rc = $Function->invokeArgs ($Parameters);
if (!$isPromise)
return $rc;
if (!($rc instanceof qcEvents_Promise)) {
trigger_error ('Expected promise as result, but did not get one');
return;
}
return $rc->then (
$Callback,
function () use ($Callable, $Parameters) {
$this->processResult ($Callable, $Parameters, array (false));
}
);
}
// }}}
// {{{ onResult
/**
* Register a callback to forward results to
*
* @param callable $Callback
* @param mixed $Private (optional)
*
* @access public
* @return void
**/
public function onResult (callable $Callback, $Private = null) {
// Register the callback
$this->resultCallbacks [] = array ($Callback, $Private);
// Push already pending results there
$Results = $this->Results;
$this->lockFinish = true;
foreach ($Results as $Result)
call_user_func ($Callback, $this, $Result, $Private);
$this->lockFinish = false;
}
// }}}
// {{{ finish
/**
* Register a callback to raise once completed
*
* @param callable $Callback (optional)
* @param mixed $Private (optional)
*
* @access public
* @return void
**/
public function finish (callable $Callback = null, $Private = null, $Force = false) {
// Push callback to callbacks
if ($Callback)
$this->finishCallbacks [] = array ($Callback, $Private);
// Check if we are already done
$this->finishQueue (($Callback === null) || $Force);
}
// }}}
// {{{ stop
/**
* Stop processing of the queue
*
* @access public
* @return void
**/
public function stop () {
// Just empty the queue
$this->Queue = array ();
$this->finishCallbacks = array ();
$this->resultCallbacks = array ();
}
// }}}
// {{{ processResult
/**
* Process an incomming result
*
* @param callable $Callable The initially called function
* @param array $Parameters All parameters given to that function
* @param array $Result All parameters given to the callback
*
* @access private
* @return void
**/
private function processResult (callable $Callable, array $Parameters, array $Result) {
// Find the callable on queue
$Call = null;
foreach ($this->Invoked as $Key=>$Info)
if (($Info [0] === $Callable) && ($Info [1] === $Parameters)) {
$Call = $Key;
break;
}
// Make sure we found anything
if ($Call === null) {
trigger_error ('Result without call recevied');
return false;
}
// Remove the call from queue
unset ($this->Invoked [$Call]);
// Push the result to results
if (isset ($this->Results [$Call]))
$this->Results [] = $Result;
else
$this->Results [$Call] = $Result;
// Run callbacks
foreach ($this->resultCallbacks as $resultCallback) {
if ($resultCallback [1] === null)
$resultCallback [1] = (is_array ($Callable) ? $Callable [0] : null);
call_user_func ($resultCallback [0], $this, $Result, $resultCallback [1]);
}
// Try to finish the queue
if (!$this->lockFinish)
return $this->finishQueue ();
}
// }}}
// {{{ finishQueue
/**
* Finish processing of queue by forwarding all results to all registered callbacks
*
* @access private
* @return void
**/
private function finishQueue ($Force = false) {
// Check if we are done
if (count ($this->Invoked) > 0)
return;
// Check wheter to run from queue
if (count ($this->Queue) > 0) {
do {
// Get the next call
$Next = array_shift ($this->Queue);
// Invoke
$this->invokeCall ($Next [0], $Next [1]);
} while (($this->Mode != self::MODE_SERIAL) && (count ($this->Queue) > 0));
return;
}
// Check if we may finish
if (((count ($this->finishCallbacks) == 0) &&
(count ($this->resultCallbacks) == 0)) ||
((count ($this->Results) == 0) && !$Force))
return;
// Peek results
$Results = $this->Results;
$this->Results = array ();
// Run all callbacks
foreach ($this->finishCallbacks as $Info)
call_user_func ($Info [0], $this, $Results, $Info [1]);
}
// }}}
}
?>