1 | <?php |
||
32 | trait CountableTrait |
||
33 | { |
||
34 | /** |
||
35 | * callable mapping |
||
36 | * |
||
37 | * @var callable[]; |
||
38 | * @access protected |
||
39 | */ |
||
40 | protected $callable_map = []; |
||
41 | |||
42 | /** |
||
43 | * {@inheritDoc} |
||
44 | */ |
||
45 | public function many( |
||
46 | /*# int */ $times, |
||
47 | /*# string */ $eventName, |
||
48 | callable $callable, |
||
49 | /*# int */ $priority = 0 |
||
50 | )/*# : bool */ { |
||
51 | // wrap the callable |
||
52 | $wrapper = function (EventInterface $event) use ($callable, $times) { |
||
53 | static $cnt = 0; |
||
54 | if ($cnt++ < $times) { |
||
55 | call_user_func($callable, $event); |
||
56 | } |
||
57 | }; |
||
58 | |||
59 | // mapping callable |
||
60 | $oid = $this->hashCallable($callable); |
||
61 | $this->callable_map[$eventName][$oid] = $wrapper; |
||
62 | |||
63 | // bind wrapper instead of the $callable |
||
64 | $this->attach($eventName, $wrapper, $priority); |
||
65 | |||
66 | return true; |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * {@inheritDoc} |
||
71 | */ |
||
72 | public function one( |
||
73 | /*# string */ $eventName, |
||
74 | callable $callable, |
||
75 | /*# int */ $priority = 0 |
||
76 | )/*# : bool */ { |
||
77 | return $this->many(1, $eventName, $callable, $priority); |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Override `detach()` in EventManager |
||
82 | * |
||
83 | * Added support for countable callable |
||
84 | * |
||
85 | * {@inheritDoc} |
||
86 | */ |
||
87 | public function detach($event, $callback) |
||
88 | { |
||
89 | if (null !== $callback) { |
||
90 | $oid = $this->hashCallable($callback); |
||
91 | if (isset($this->callable_map[$event][$oid])) { |
||
92 | $callback = $this->callable_map[$event][$oid]; |
||
93 | unset($this->callable_map[$event][$oid]); |
||
94 | } |
||
95 | } else { |
||
96 | unset($this->callable_map[$event]); |
||
97 | } |
||
98 | return parent::detach($event, $callback); |
||
99 | } |
||
100 | |||
101 | /** |
||
102 | * Returns a unique id for $callable with $eventName |
||
103 | * |
||
104 | * @param callable $callable |
||
105 | * @return string |
||
106 | * @access protected |
||
107 | */ |
||
108 | protected function hashCallable(callable $callable)/*# string */ |
||
109 | { |
||
110 | return spl_object_hash((object) $callable); |
||
111 | } |
||
112 | |||
113 | // from EventManagerInterface |
||
114 | abstract public function attach($event, $callback, $priority = 0); |
||
115 | } |
||
116 |