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/lugnsk/micro |
12
|
|
|
* @copyright Copyright © 2013 Oleg Lunegov |
13
|
|
|
* @license /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
|
|
|
* Add listener on event |
26
|
|
|
* |
27
|
|
|
* @access public |
28
|
|
|
* |
29
|
|
|
* @param string $listener listener name |
30
|
|
|
* @param array $event ['Object', 'method'] or callable |
31
|
|
|
* @param int|null $prior priority |
32
|
|
|
* |
33
|
|
|
* @return bool |
34
|
|
|
*/ |
35
|
|
|
public function addListener($listener, $event, $prior = null) |
36
|
|
|
{ |
37
|
|
|
if (!is_callable($event)) { |
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (!array_key_exists($listener, $this->listeners)) { |
42
|
|
|
$this->listeners[$listener] = []; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (!$prior) { |
|
|
|
|
46
|
|
|
$this->listeners[$listener][] = $event; |
47
|
|
|
} else { |
48
|
|
|
array_splice($this->listeners[$listener], $prior, 0, $event); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Send signal to run event |
56
|
|
|
* |
57
|
|
|
* @access public |
58
|
|
|
* |
59
|
|
|
* @param string $listener listener name |
60
|
|
|
* @param array $params Signal parameters |
61
|
|
|
* |
62
|
|
|
* @return mixed |
63
|
|
|
*/ |
64
|
|
|
public function signal($listener, array $params = []) |
65
|
|
|
{ |
66
|
|
|
$result = null; |
67
|
|
|
|
68
|
|
|
if ($this->listeners && array_key_exists($listener, $this->listeners)) { |
|
|
|
|
69
|
|
|
foreach ($this->listeners[$listener] as $listen) { |
70
|
|
|
$result = call_user_func($listen, $params); |
71
|
|
|
|
72
|
|
|
if ($result instanceof IResponse) { |
73
|
|
|
return $result; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $result; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
integer
values, zero is a special case, in particular the following results might be unexpected: