| 1 |
<?php |
| 2 |
/** |
| 3 |
* This file is part of the Peast package |
| 4 |
* |
| 5 |
* (c) Marco Marchiò <[email protected]> |
| 6 |
* |
| 7 |
* For the full copyright and license information refer to the LICENSE file |
| 8 |
* distributed with this source code |
| 9 |
*/ |
| 10 |
namespace Peast\Syntax; |
| 11 |
|
| 12 |
/** |
| 13 |
* Events emitter class. An instance of this class is used by Parser and Scanner |
| 14 |
* to emit events and attach listeners to them |
| 15 |
* |
| 16 |
* @author Marco Marchiò <[email protected]> |
| 17 |
*/ |
| 18 |
class EventsEmitter |
| 19 |
{ |
| 20 |
/** |
| 21 |
* Events registry array |
| 22 |
* |
| 23 |
* @var array |
| 24 |
*/ |
| 25 |
protected $eventsRegistry = array(); |
| 26 |
|
| 27 |
/** |
| 28 |
* Attaches a listener function to the given event |
| 29 |
* |
| 30 |
* @param string $event Event name |
| 31 |
* @param callable $listener Listener function |
| 32 |
* |
| 33 |
* @return $this |
| 34 |
*/ |
| 35 |
public function addListener($event, $listener) |
| 36 |
{ |
| 37 |
if (!isset($this->eventsRegistry[$event])) { |
| 38 |
$this->eventsRegistry[$event] = array(); |
| 39 |
} |
| 40 |
$this->eventsRegistry[$event][] = $listener; |
| 41 |
return $this; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Fires an event |
| 46 |
* |
| 47 |
* @param string $event Event name |
| 48 |
* @param array $args Arguments to pass to functions attached to the |
| 49 |
* event |
| 50 |
* |
| 51 |
* @return $this |
| 52 |
*/ |
| 53 |
public function fire($event, $args = array()) |
| 54 |
{ |
| 55 |
if (isset($this->eventsRegistry[$event])) { |
| 56 |
foreach ($this->eventsRegistry[$event] as $listener) { |
| 57 |
call_user_func_array($listener, $args); |
| 58 |
} |
| 59 |
} |
| 60 |
return $this; |
| 61 |
} |
| 62 |
} |