EventDispatcher.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Event;
  12. use Psr\EventDispatcher\EventDispatcherInterface;
  13. use Psr\EventDispatcher\ListenerProviderInterface;
  14. use Psr\EventDispatcher\StoppableEventInterface;
  15. use Psr\Log\LoggerInterface;
  16. class EventDispatcher implements EventDispatcherInterface
  17. {
  18. public function __construct(
  19. private ListenerProviderInterface $listeners,
  20. private ?LoggerInterface $logger = null
  21. ) {
  22. }
  23. /**
  24. * Provide all listeners with an event to process.
  25. *
  26. * @param object $event The object to process
  27. * @return object The Event that was passed, now modified by listeners
  28. */
  29. public function dispatch(object $event)
  30. {
  31. foreach ($this->listeners->getListenersForEvent($event) as $listener) {
  32. $listener($event);
  33. $this->dump($listener, $event);
  34. if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
  35. break;
  36. }
  37. }
  38. return $event;
  39. }
  40. /**
  41. * Dump the debug message if $logger property is provided.
  42. * @param mixed $listener
  43. */
  44. private function dump($listener, object $event)
  45. {
  46. if (! $this->logger) {
  47. return;
  48. }
  49. $eventName = get_class($event);
  50. $listenerName = '[ERROR TYPE]';
  51. if (is_array($listener)) {
  52. $listenerName = is_string($listener[0]) ? $listener[0] : get_class($listener[0]);
  53. } elseif (is_string($listener)) {
  54. $listenerName = $listener;
  55. } elseif (is_object($listener)) {
  56. $listenerName = get_class($listener);
  57. }
  58. $this->logger->debug(sprintf('Event %s handled by %s listener.', $eventName, $listenerName));
  59. }
  60. }