Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 09246f2

Browse files
[EventDispatcher] swap arguments of dispatch() to allow registering events by FQCN
1 parent bcff647 commit 09246f2

File tree

54 files changed

+734
-170
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+734
-170
lines changed

src/Symfony/Bridge/Doctrine/Tests/Form/EventListener/MergeDoctrineCollectionListenerTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public function testOnSubmitDoNothing()
6363
$submittedData = array('test');
6464
$event = new FormEvent($this->getForm(), $submittedData);
6565

66-
$this->dispatcher->dispatch(FormEvents::SUBMIT, $event);
66+
$this->dispatcher->dispatch($event, FormEvents::SUBMIT);
6767

6868
$this->assertTrue($this->collection->contains('test'));
6969
$this->assertSame(1, $this->collection->count());
@@ -74,7 +74,7 @@ public function testOnSubmitNullClearCollection()
7474
$submittedData = array();
7575
$event = new FormEvent($this->getForm(), $submittedData);
7676

77-
$this->dispatcher->dispatch(FormEvents::SUBMIT, $event);
77+
$this->dispatcher->dispatch($event, FormEvents::SUBMIT);
7878

7979
$this->assertTrue($this->collection->isEmpty());
8080
}

src/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,12 @@ public function testLogsFromListeners()
196196
});
197197

198198
$event = new ConsoleCommandEvent(new Command('foo'), $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(), $output);
199-
$dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
199+
$dispatcher->dispatch($event, ConsoleEvents::COMMAND);
200200
$this->assertContains('Before command message.', $out = $output->fetch());
201201
$this->assertContains('After command message.', $out);
202202

203203
$event = new ConsoleTerminateEvent(new Command('foo'), $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(), $output, 0);
204-
$dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
204+
$dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
205205
$this->assertContains('Before terminate message.', $out = $output->fetch());
206206
$this->assertContains('After terminate message.', $out);
207207
}

src/Symfony/Bundle/FrameworkBundle/Resources/config/debug.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<argument type="service" id="debug.event_dispatcher.inner" />
1313
<argument type="service" id="debug.stopwatch" />
1414
<argument type="service" id="logger" on-invalid="null" />
15+
<argument>%event_dispatcher.event_aliases%</argument>
1516
</service>
1617

1718
<service id="debug.controller_resolver" decorates="controller_resolver" class="Symfony\Component\HttpKernel\Controller\TraceableControllerResolver">

src/Symfony/Bundle/FrameworkBundle/Resources/config/services.xml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,37 @@
44
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
55
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
66

7+
<parameters>
8+
<parameter key="event_dispatcher.event_aliases" type="collection">
9+
<parameter key="Symfony\Component\Workflow\Event\GuardEvent">workflow.guard</parameter>
10+
<parameter key="Symfony\Component\Workflow\Event\LeaveEvent">workflow.leave</parameter>
11+
<parameter key="Symfony\Component\Workflow\Event\TransitionEvent">workflow.transition</parameter>
12+
<parameter key="Symfony\Component\Workflow\Event\EnterEvent">workflow.enter</parameter>
13+
<parameter key="Symfony\Component\Workflow\Event\EnteredEvent">workflow.entered</parameter>
14+
<parameter key="Symfony\Component\Workflow\Event\CompletedEvent">workflow.completed</parameter>
15+
<parameter key="Symfony\Component\Workflow\Event\AnnounceEvent">workflow.announce</parameter>
16+
<parameter key="Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent">security.authentication.success</parameter>
17+
<parameter key="Symfony\Component\Security\Core\Event\AuthenticationFailureEvent">security.authentication.failure</parameter>
18+
<parameter key="Symfony\Component\Security\Http\Event\InteractiveLoginEvent">security.interactive_login</parameter>
19+
<parameter key="Symfony\Component\Security\Http\Event\SwitchUserEvent">security.switch_user</parameter>
20+
<parameter key="Symfony\Component\Console\Event\ConsoleCommandEvent">console.command</parameter>
21+
<parameter key="Symfony\Component\Console\Event\ConsoleErrorEvent">console.error</parameter>
22+
<parameter key="Symfony\Component\Console\Event\ConsoleTerminateEvent">console.terminate</parameter>
23+
<parameter key="Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent">kernel.controller_arguments</parameter>
24+
<parameter key="Symfony\Component\HttpKernel\Event\FilterControllerEvent">kernel.controller</parameter>
25+
<parameter key="Symfony\Component\HttpKernel\Event\FilterResponseEvent">kernel.response</parameter>
26+
<parameter key="Symfony\Component\HttpKernel\Event\FinishRequestEvent">kernel.finish_request</parameter>
27+
<parameter key="Symfony\Component\HttpKernel\Event\GetResponseEvent">kernel.request</parameter>
28+
<parameter key="Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent">kernel.view</parameter>
29+
<parameter key="Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent">kernel.exception</parameter>
30+
<parameter key="Symfony\Component\HttpKernel\Event\PostResponseEvent">kernel.terminate</parameter>
31+
<parameter key="Symfony\Component\Form\PreSubmitEvent">form.pre_submit</parameter>
32+
<parameter key="Symfony\Component\Form\SubmitEvent">form.submit</parameter>
33+
<parameter key="Symfony\Component\Form\PostSubmitEvent">form.post_submit</parameter>
34+
<parameter key="Symfony\Component\Form\PreSetDataEvent">form.pre_set_data</parameter>
35+
<parameter key="Symfony\Component\Form\PostSetDataEvent">form.post_set_data</parameter>
36+
</parameter>
37+
</parameters>
738
<services>
839
<defaults public="false" />
940

@@ -15,6 +46,7 @@
1546

1647
<service id="event_dispatcher" class="Symfony\Component\EventDispatcher\EventDispatcher" public="true">
1748
<tag name="container.hot_path" />
49+
<argument>%event_dispatcher.event_aliases%</argument>
1850
</service>
1951
<service id="Symfony\Component\EventDispatcher\EventDispatcherInterface" alias="event_dispatcher" />
2052

src/Symfony/Component/Console/Application.php

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
use Symfony\Component\Debug\ErrorHandler;
4545
use Symfony\Component\Debug\Exception\FatalThrowableError;
4646
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
47+
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
4748

4849
/**
4950
* An Application is the container for a collection of commands.
@@ -92,7 +93,7 @@ public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN
9293

9394
public function setDispatcher(EventDispatcherInterface $dispatcher)
9495
{
95-
$this->dispatcher = $dispatcher;
96+
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
9697
}
9798

9899
public function setCommandLoader(CommandLoaderInterface $commandLoader)
@@ -228,7 +229,7 @@ public function doRun(InputInterface $input, OutputInterface $output)
228229
if (!($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException) || 1 !== \count($alternatives = $e->getAlternatives()) || !$input->isInteractive()) {
229230
if (null !== $this->dispatcher) {
230231
$event = new ConsoleErrorEvent($input, $output, $e);
231-
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
232+
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
232233

233234
if (0 === $event->getExitCode()) {
234235
return 0;
@@ -247,7 +248,7 @@ public function doRun(InputInterface $input, OutputInterface $output)
247248
if (!$style->confirm(sprintf('Do you want to run "%s" instead? ', $alternative), false)) {
248249
if (null !== $this->dispatcher) {
249250
$event = new ConsoleErrorEvent($input, $output, $e);
250-
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
251+
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
251252

252253
return $event->getExitCode();
253254
}
@@ -906,7 +907,7 @@ protected function doRunCommand(Command $command, InputInterface $input, OutputI
906907
$e = null;
907908

908909
try {
909-
$this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
910+
$this->dispatcher->dispatch($event, ConsoleEvents::COMMAND);
910911

911912
if ($event->commandShouldRun()) {
912913
$exitCode = $command->run($input, $output);
@@ -915,7 +916,7 @@ protected function doRunCommand(Command $command, InputInterface $input, OutputI
915916
}
916917
} catch (\Throwable $e) {
917918
$event = new ConsoleErrorEvent($input, $output, $e, $command);
918-
$this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
919+
$this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
919920
$e = $event->getError();
920921

921922
if (0 === $exitCode = $event->getExitCode()) {
@@ -924,7 +925,7 @@ protected function doRunCommand(Command $command, InputInterface $input, OutputI
924925
}
925926

926927
$event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
927-
$this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
928+
$this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
928929

929930
if (null !== $e) {
930931
throw $e;

src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php

Lines changed: 71 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Symfony\Component\EventDispatcher\Event;
1616
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
1717
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18+
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
1819
use Symfony\Component\Stopwatch\Stopwatch;
1920

2021
/**
@@ -33,38 +34,52 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
3334
private $dispatcher;
3435
private $wrappedListeners;
3536
private $orphanedEvents;
37+
private $aliases;
3638

37-
public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null)
39+
public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null, array $aliases = null)
3840
{
39-
$this->dispatcher = $dispatcher;
41+
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
4042
$this->stopwatch = $stopwatch;
4143
$this->logger = $logger;
4244
$this->called = array();
4345
$this->wrappedListeners = array();
4446
$this->orphanedEvents = array();
47+
$this->aliases = $aliases;
4548
}
4649

4750
/**
4851
* {@inheritdoc}
4952
*/
5053
public function addListener($eventName, $listener, $priority = 0)
5154
{
52-
$this->dispatcher->addListener($eventName, $listener, $priority);
55+
$this->dispatcher->addListener($this->aliases[$eventName] ?? $eventName, $listener, $priority);
5356
}
5457

5558
/**
5659
* {@inheritdoc}
5760
*/
5861
public function addSubscriber(EventSubscriberInterface $subscriber)
5962
{
60-
$this->dispatcher->addSubscriber($subscriber);
63+
if ($this->aliases) {
64+
AliasedEventSubscriber::$subscriber = $subscriber;
65+
AliasedEventSubscriber::$aliases = $this->aliases;
66+
$subscriber = new AliasedEventSubscriber();
67+
}
68+
69+
try {
70+
$this->dispatcher->addSubscriber($subscriber);
71+
} finally {
72+
AliasedEventSubscriber::$subscriber = AliasedEventSubscriber::$aliases = null;
73+
}
6174
}
6275

6376
/**
6477
* {@inheritdoc}
6578
*/
6679
public function removeListener($eventName, $listener)
6780
{
81+
$eventName = $this->aliases[$eventName] ?? $eventName;
82+
6883
if (isset($this->wrappedListeners[$eventName])) {
6984
foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
7085
if ($wrappedListener->getWrappedListener() === $listener) {
@@ -83,22 +98,34 @@ public function removeListener($eventName, $listener)
8398
*/
8499
public function removeSubscriber(EventSubscriberInterface $subscriber)
85100
{
86-
return $this->dispatcher->removeSubscriber($subscriber);
101+
if ($this->aliases) {
102+
AliasedEventSubscriber::$subscriber = $subscriber;
103+
AliasedEventSubscriber::$aliases = $this->aliases;
104+
$subscriber = new AliasedEventSubscriber();
105+
}
106+
107+
try {
108+
return $this->dispatcher->removeSubscriber($subscriber);
109+
} finally {
110+
AliasedEventSubscriber::$subscriber = AliasedEventSubscriber::$aliases = null;
111+
}
87112
}
88113

89114
/**
90115
* {@inheritdoc}
91116
*/
92117
public function getListeners($eventName = null)
93118
{
94-
return $this->dispatcher->getListeners($eventName);
119+
return $this->dispatcher->getListeners($this->aliases[$eventName] ?? $eventName);
95120
}
96121

97122
/**
98123
* {@inheritdoc}
99124
*/
100125
public function getListenerPriority($eventName, $listener)
101126
{
127+
$eventName = $this->aliases[$eventName] ?? $eventName;
128+
102129
// we might have wrapped listeners for the event (if called while dispatching)
103130
// in that case get the priority by wrapper
104131
if (isset($this->wrappedListeners[$eventName])) {
@@ -117,18 +144,31 @@ public function getListenerPriority($eventName, $listener)
117144
*/
118145
public function hasListeners($eventName = null)
119146
{
120-
return $this->dispatcher->hasListeners($eventName);
147+
return $this->dispatcher->hasListeners($this->aliases[$eventName] ?? $eventName);
121148
}
122149

123150
/**
124151
* {@inheritdoc}
152+
*
153+
* @param string|null $eventName
125154
*/
126-
public function dispatch($eventName, Event $event = null)
155+
public function dispatch($event/*, string $eventName = null */)
127156
{
128-
if (null === $event) {
129-
$event = new Event();
157+
$eventName = 1 < \func_num_args() ? \func_get_arg(1) : null;
158+
159+
if (\is_scalar($event)) {
160+
// deprecated
161+
$swap = $event;
162+
$event = $eventName ?? new Event();
163+
$eventName = $swap;
164+
}
165+
166+
if (!$event instanceof Event) {
167+
throw new \TypeError();
130168
}
131169

170+
$eventName = $this->aliases[$eventName] ?? $eventName;
171+
132172
if (null !== $this->logger && $event->isPropagationStopped()) {
133173
$this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
134174
}
@@ -138,7 +178,7 @@ public function dispatch($eventName, Event $event = null)
138178

139179
$e = $this->stopwatch->start($eventName, 'section');
140180

141-
$this->dispatcher->dispatch($eventName, $event);
181+
$this->dispatcher->dispatch($event, $eventName);
142182

143183
if ($e->isStarted()) {
144184
$e->stop();
@@ -334,3 +374,23 @@ private function sortListenersByPriority($a, $b)
334374
return 1;
335375
}
336376
}
377+
378+
/**
379+
* @internal
380+
*/
381+
class AliasedEventSubscriber implements EventSubscriberInterface
382+
{
383+
public static $subscriber;
384+
public static $aliases;
385+
386+
public static function getSubscribedEvents()
387+
{
388+
$events = array();
389+
390+
foreach (self::$subscriber->getSubscribedEvents() as $eventName => $params) {
391+
$events[self::$aliases[$eventName] ?? $eventName] = $params;
392+
}
393+
394+
return $events;
395+
}
396+
}

src/Symfony/Component/EventDispatcher/DependencyInjection/RegisterListenersPass.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ public function process(ContainerBuilder $container)
5252
return;
5353
}
5454

55+
$aliases = $container->hasParameter('event_dispatcher.aliases') ? $container->getParameter('event_dispatcher.aliases') : array();
5556
$definition = $container->findDefinition($this->dispatcherService);
5657

5758
foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
@@ -61,6 +62,7 @@ public function process(ContainerBuilder $container)
6162
if (!isset($event['event'])) {
6263
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
6364
}
65+
$event['event'] = $aliases[$event['event']] ?? $event['event'];
6466

6567
if (!isset($event['method'])) {
6668
$event['method'] = 'on'.preg_replace_callback(array(
@@ -98,6 +100,7 @@ public function process(ContainerBuilder $container)
98100
}
99101
$class = $r->name;
100102

103+
ExtractingEventDispatcher::$aliases = $aliases;
101104
ExtractingEventDispatcher::$subscriber = $class;
102105
$extractingDispatcher->addSubscriber($extractingDispatcher);
103106
foreach ($extractingDispatcher->listeners as $args) {
@@ -109,6 +112,7 @@ public function process(ContainerBuilder $container)
109112
}
110113
}
111114
$extractingDispatcher->listeners = array();
115+
ExtractingEventDispatcher::$aliases = array();
112116
}
113117
}
114118
}
@@ -120,6 +124,7 @@ class ExtractingEventDispatcher extends EventDispatcher implements EventSubscrib
120124
{
121125
public $listeners = array();
122126

127+
public static $aliases = array();
123128
public static $subscriber;
124129

125130
public function addListener($eventName, $listener, $priority = 0)
@@ -129,8 +134,12 @@ public function addListener($eventName, $listener, $priority = 0)
129134

130135
public static function getSubscribedEvents()
131136
{
132-
$callback = array(self::$subscriber, 'getSubscribedEvents');
137+
$events = array();
133138

134-
return $callback();
139+
foreach (array(self::$subscriber, 'getSubscribedEvents')() as $eventName => $params) {
140+
$events[self::$aliases[$eventName] ?? $eventName] = $params;
141+
}
142+
143+
return $events;
135144
}
136145
}

0 commit comments

Comments
 (0)