44
55namespace Doctrine \Common ;
66
7+ use function func_get_arg ;
8+ use function func_num_args ;
79use function spl_object_hash ;
810
911/**
@@ -21,6 +23,14 @@ class EventManager
2123 */
2224 private array $ listeners = [];
2325
26+ /**
27+ * Map of registered listener configurations.
28+ * <hash><event> => <configuration>
29+ *
30+ * @var array<string, array<string, array{method?: string}>>
31+ */
32+ private array $ listenerConfigs = [];
33+
2434 /**
2535 * Dispatches an event to all registered listeners.
2636 *
@@ -37,8 +47,10 @@ public function dispatchEvent(string $eventName, EventArgs|null $eventArgs = nul
3747
3848 $ eventArgs ??= EventArgs::getEmptyInstance ();
3949
40- foreach ($ this ->listeners [$ eventName ] as $ listener ) {
41- $ listener ->$ eventName ($ eventArgs );
50+ foreach ($ this ->listeners [$ eventName ] as $ hash => $ listener ) {
51+ $ method = $ this ->listenerConfigs [$ hash ][$ eventName ]['method ' ] ?? $ eventName ;
52+
53+ $ listener ->$ method ($ eventArgs );
4254 }
4355 }
4456
@@ -75,18 +87,23 @@ public function hasListeners(string $event): bool
7587 /**
7688 * Adds an event listener that listens on the specified events.
7789 *
78- * @param string|string[] $events The event(s) to listen on.
79- * @param object $listener The listener object.
90+ * @param string|string[] $events The event(s) to listen on.
91+ * @param object $listener The listener object.
92+ * @param array<string, array{method?: string}> $listenerConfig The listener configuration, indexed by event.
8093 */
81- public function addEventListener (string |array $ events , object $ listener ): void
94+ public function addEventListener (string |array $ events , object $ listener, /* array $listenerConfig = [] */ ): void
8295 {
96+ /** @var array<string, array{method?: string}> $listenerConfig */
97+ $ listenerConfig = 3 <= func_num_args () ? func_get_arg (2 ) : [];
98+
8399 // Picks the hash code related to that listener
84100 $ hash = spl_object_hash ($ listener );
85101
86102 foreach ((array ) $ events as $ event ) {
87103 // Overrides listener if a previous one was associated already
88104 // Prevents duplicate listeners on same event (same instance only)
89- $ this ->listeners [$ event ][$ hash ] = $ listener ;
105+ $ this ->listeners [$ event ][$ hash ] = $ listener ;
106+ $ this ->listenerConfigs [$ hash ][$ event ] = $ listenerConfig [$ event ] ?? [];
90107 }
91108 }
92109
@@ -100,6 +117,7 @@ public function removeEventListener(string|array $events, object $listener): voi
100117 // Picks the hash code related to that listener
101118 $ hash = spl_object_hash ($ listener );
102119
120+ unset($ this ->listenerConfigs [$ hash ]);
103121 foreach ((array ) $ events as $ event ) {
104122 unset($ this ->listeners [$ event ][$ hash ]);
105123 }
0 commit comments