[FEATURE] Introduce PSR-14-based EventDispatcher as alternative for hooks
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / EventDispatcher / EventDispatcher.php
1 <?php
2 declare(strict_types = 1);
3
4 namespace TYPO3\CMS\Core\EventDispatcher;
5
6 /*
7 * This file is part of the TYPO3 CMS project.
8 *
9 * It is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU General Public License, either version 2
11 * of the License, or any later version.
12 *
13 * For the full copyright and license information, please read the
14 * LICENSE.txt file that was distributed with this source code.
15 *
16 * The TYPO3 project - inspiring people to share!
17 */
18
19 use Psr\EventDispatcher\EventDispatcherInterface;
20 use Psr\EventDispatcher\ListenerProviderInterface;
21 use Psr\EventDispatcher\StoppableEventInterface;
22 use TYPO3\CMS\Core\SingletonInterface;
23
24 /**
25 * Base PSR-14 event dispatcher which has only one listener provider, given at runtime
26 * Is a singleton instance in order to be published once.
27 */
28 class EventDispatcher implements EventDispatcherInterface, SingletonInterface
29 {
30 /**
31 * @var ListenerProviderInterface
32 */
33 protected $listenerProvider;
34
35 public function __construct(ListenerProviderInterface $listenerProvider)
36 {
37 $this->listenerProvider = $listenerProvider;
38 }
39
40 /**
41 * @inheritdoc
42 */
43 public function dispatch(object $event)
44 {
45 // If the event is already stopped, nothing to do here.
46 if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
47 return $event;
48 }
49 foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
50 $listener($event);
51 if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
52 break;
53 }
54 }
55 return $event;
56 }
57 }