|
1
|
|
|
<?php /** MicroDispatcher */ |
|
2
|
|
|
|
|
3
|
|
|
namespace Micro\Base; |
|
4
|
|
|
|
|
5
|
|
|
use Micro\Web\IResponse; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Dispatcher class file. |
|
9
|
|
|
* |
|
10
|
|
|
* @author Oleg Lunegov <[email protected]> |
|
11
|
|
|
* @link https://github.com/linpax/microphp-framework |
|
12
|
|
|
* @copyright Copyright (c) 2013 Oleg Lunegov |
|
13
|
|
|
* @license https://github.com/linpax/microphp-framework/blob/master/LICENSE |
|
14
|
|
|
* @package Micro |
|
15
|
|
|
* @subpackage Base |
|
16
|
|
|
* @version 1.0 |
|
17
|
|
|
* @since 1.0 |
|
18
|
|
|
*/ |
|
19
|
|
|
class Dispatcher implements IDispatcher |
|
20
|
|
|
{ |
|
21
|
|
|
/** @var array $listeners Listeners objects on events */ |
|
22
|
|
|
protected $listeners = []; |
|
23
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Add listener on event |
|
27
|
|
|
* |
|
28
|
|
|
* @access public |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $listener listener name |
|
31
|
|
|
* @param array $event ['Object', 'method'] or callable |
|
32
|
|
|
* @param int|null $prior priority |
|
33
|
|
|
* |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
|
|
public function addListener($listener, $event, $prior = null) |
|
37
|
|
|
{ |
|
38
|
|
|
if (!is_callable($event)) { |
|
39
|
|
|
return false; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
if (!array_key_exists($listener, $this->listeners)) { |
|
43
|
|
|
$this->listeners[$listener] = []; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
if (!$prior) { |
|
|
|
|
|
|
47
|
|
|
$this->listeners[$listener][] = $event; |
|
48
|
|
|
} else { |
|
49
|
|
|
array_splice($this->listeners[$listener], $prior, 0, $event); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
return true; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Send signal to run event |
|
57
|
|
|
* |
|
58
|
|
|
* @access public |
|
59
|
|
|
* |
|
60
|
|
|
* @param string $listener listener name |
|
61
|
|
|
* @param array $params Signal parameters |
|
62
|
|
|
* |
|
63
|
|
|
* @return mixed |
|
64
|
|
|
*/ |
|
65
|
|
|
public function signal($listener, array $params = []) |
|
66
|
|
|
{ |
|
67
|
|
|
$result = null; |
|
68
|
|
|
|
|
69
|
|
|
if (array_key_exists($listener, $this->listeners) && 0 !== count($this->listeners[$listener])) { |
|
70
|
|
|
/** @noinspection ForeachSourceInspection */ |
|
71
|
|
|
foreach ($this->listeners[$listener] as $listen) { |
|
72
|
|
|
$result = call_user_func($listen, $params); |
|
73
|
|
|
|
|
74
|
|
|
if ($result instanceof IResponse) { |
|
75
|
|
|
return $result; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
return $result; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: