EventDispatcher.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\EventDispatcher;
  8. use OC\Broadcast\Events\BroadcastEvent;
  9. use OC\Log;
  10. use OCP\Broadcast\Events\IBroadcastEvent;
  11. use OCP\EventDispatcher\ABroadcastedEvent;
  12. use OCP\EventDispatcher\Event;
  13. use OCP\EventDispatcher\IEventDispatcher;
  14. use OCP\IServerContainer;
  15. use Psr\Log\LoggerInterface;
  16. use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyDispatcher;
  17. use function get_class;
  18. class EventDispatcher implements IEventDispatcher {
  19. public function __construct(
  20. private SymfonyDispatcher $dispatcher,
  21. private IServerContainer $container,
  22. private LoggerInterface $logger,
  23. ) {
  24. // inject the event dispatcher into the logger
  25. // this is done here because there is a cyclic dependency between the event dispatcher and logger
  26. if ($this->logger instanceof Log || $this->logger instanceof Log\PsrLoggerAdapter) {
  27. $this->logger->setEventDispatcher($this);
  28. }
  29. }
  30. public function addListener(string $eventName,
  31. callable $listener,
  32. int $priority = 0): void {
  33. $this->dispatcher->addListener($eventName, $listener, $priority);
  34. }
  35. public function removeListener(string $eventName,
  36. callable $listener): void {
  37. $this->dispatcher->removeListener($eventName, $listener);
  38. }
  39. public function addServiceListener(string $eventName,
  40. string $className,
  41. int $priority = 0): void {
  42. $listener = new ServiceEventListener(
  43. $this->container,
  44. $className,
  45. $this->logger
  46. );
  47. $this->addListener($eventName, $listener, $priority);
  48. }
  49. public function hasListeners(string $eventName): bool {
  50. return $this->dispatcher->hasListeners($eventName);
  51. }
  52. /**
  53. * @deprecated
  54. */
  55. public function dispatch(string $eventName,
  56. Event $event): void {
  57. $this->dispatcher->dispatch($event, $eventName);
  58. if ($event instanceof ABroadcastedEvent && !$event->isPropagationStopped()) {
  59. // Propagate broadcast
  60. $this->dispatch(
  61. IBroadcastEvent::class,
  62. new BroadcastEvent($event)
  63. );
  64. }
  65. }
  66. public function dispatchTyped(Event $event): void {
  67. $this->dispatch(get_class($event), $event);
  68. }
  69. /**
  70. * @return SymfonyDispatcher
  71. * @deprecated 20.0.0
  72. */
  73. public function getSymfonyDispatcher(): SymfonyDispatcher {
  74. return $this->dispatcher;
  75. }
  76. }