EventArgs.php
4 years ago
EventManager.php
4 years ago
EventSubscriber.php
4 years ago
index.php
3 years ago
EventManager.php
53 lines
| 1 | <?php |
| 2 | namespace MailPoetVendor\Doctrine\Common; |
| 3 | if (!defined('ABSPATH')) exit; |
| 4 | use function spl_object_hash; |
| 5 | class EventManager |
| 6 | { |
| 7 | private $_listeners = []; |
| 8 | public function dispatchEvent($eventName, ?EventArgs $eventArgs = null) |
| 9 | { |
| 10 | if (!isset($this->_listeners[$eventName])) { |
| 11 | return; |
| 12 | } |
| 13 | $eventArgs = $eventArgs ?? EventArgs::getEmptyInstance(); |
| 14 | foreach ($this->_listeners[$eventName] as $listener) { |
| 15 | $listener->{$eventName}($eventArgs); |
| 16 | } |
| 17 | } |
| 18 | public function getListeners($event = null) |
| 19 | { |
| 20 | return $event ? $this->_listeners[$event] : $this->_listeners; |
| 21 | } |
| 22 | public function hasListeners($event) |
| 23 | { |
| 24 | return !empty($this->_listeners[$event]); |
| 25 | } |
| 26 | public function addEventListener($events, $listener) |
| 27 | { |
| 28 | // Picks the hash code related to that listener |
| 29 | $hash = spl_object_hash($listener); |
| 30 | foreach ((array) $events as $event) { |
| 31 | // Overrides listener if a previous one was associated already |
| 32 | // Prevents duplicate listeners on same event (same instance only) |
| 33 | $this->_listeners[$event][$hash] = $listener; |
| 34 | } |
| 35 | } |
| 36 | public function removeEventListener($events, $listener) |
| 37 | { |
| 38 | // Picks the hash code related to that listener |
| 39 | $hash = spl_object_hash($listener); |
| 40 | foreach ((array) $events as $event) { |
| 41 | unset($this->_listeners[$event][$hash]); |
| 42 | } |
| 43 | } |
| 44 | public function addEventSubscriber(EventSubscriber $subscriber) |
| 45 | { |
| 46 | $this->addEventListener($subscriber->getSubscribedEvents(), $subscriber); |
| 47 | } |
| 48 | public function removeEventSubscriber(EventSubscriber $subscriber) |
| 49 | { |
| 50 | $this->removeEventListener($subscriber->getSubscribedEvents(), $subscriber); |
| 51 | } |
| 52 | } |
| 53 |