Skip to content

Commit

Permalink
[EventDispatcher] make listeners removable from an executed listener
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed May 14, 2015
1 parent 5d428b7 commit 54bb399
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
Expand Up @@ -88,6 +88,18 @@ public function addSubscriber(EventSubscriberInterface $subscriber)
*/
public function removeListener($eventName, $listener)
{
if (isset($this->wrappedListeners[$this->lastEventId])) {
foreach ($this->wrappedListeners[$this->lastEventId] as $wrappedListener) {
$originalListener = $this->wrappedListeners[$this->lastEventId][$wrappedListener];

if ($originalListener === $listener) {
unset($this->wrappedListeners[$this->lastEventId][$wrappedListener]);

return $this->dispatcher->removeListener($eventName, $wrappedListener);
}
}
}

return $this->dispatcher->removeListener($eventName, $listener);
}

Expand Down
Expand Up @@ -223,6 +223,19 @@ public function testStopwatchStopControllerOnRequestEvent()
$kernel->handle($request);
}

public function testListenerCanRemoveItselfWhenExecuted()
{
$eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$listener1 = function () use ($eventDispatcher, &$listener1) {
$eventDispatcher->removeListener('foo', $listener1);
};
$eventDispatcher->addListener('foo', $listener1);
$eventDispatcher->addListener('foo', function () {});
$eventDispatcher->dispatch('foo');

$this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed');
}

protected function getHttpKernel($dispatcher, $controller)
{
$resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');
Expand Down

0 comments on commit 54bb399

Please sign in to comment.