[EventDispatcher] Add reference to the EventDispatcher on the Event
This commit is contained in:
parent
c18f5a8d94
commit
fabe818124
@ -151,18 +151,20 @@ class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
$service = $this->getMock('Symfony\Bundle\FrameworkBundle\Tests\Service');
|
||||
|
||||
$service
|
||||
->expects($this->once())
|
||||
->method('onEvent')
|
||||
->with($event)
|
||||
;
|
||||
|
||||
$container = new Container();
|
||||
$container->set('service.listener', $service);
|
||||
|
||||
$dispatcher = new ContainerAwareEventDispatcher($container);
|
||||
$dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
|
||||
|
||||
$event->setDispatcher($dispatcher);
|
||||
|
||||
$service
|
||||
->expects($this->once())
|
||||
->method('onEvent')
|
||||
->with($event)
|
||||
;
|
||||
|
||||
$this->assertTrue($dispatcher->hasListeners());
|
||||
|
||||
if ($dispatcher->hasListeners('onEvent')) {
|
||||
|
@ -37,6 +37,11 @@ class Event
|
||||
*/
|
||||
private $propagationStopped = false;
|
||||
|
||||
/**
|
||||
* @var EventDispatcher Dispatcher that dispatched this event
|
||||
*/
|
||||
private $dispatcher;
|
||||
|
||||
/**
|
||||
* Returns whether further event listeners should be triggered.
|
||||
*
|
||||
@ -63,4 +68,28 @@ class Event
|
||||
{
|
||||
$this->propagationStopped = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the EventDispatcher that dispatches this Event
|
||||
*
|
||||
* @param EventDispatcher $dispatcher
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function setDispatcher(EventDispatcher $dispatcher)
|
||||
{
|
||||
$this->dispatcher = $dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the EventDispatcher that dispatches this Event
|
||||
*
|
||||
* @return EventDispatcher
|
||||
*
|
||||
* @api
|
||||
*/
|
||||
public function getDispatcher()
|
||||
{
|
||||
return $this->dispatcher;
|
||||
}
|
||||
}
|
||||
|
@ -47,6 +47,8 @@ class EventDispatcher implements EventDispatcherInterface
|
||||
$event = new Event();
|
||||
}
|
||||
|
||||
$event->setDispatcher($this);
|
||||
|
||||
$this->doDispatch($this->getListeners($eventName), $eventName, $event);
|
||||
}
|
||||
|
||||
|
@ -228,6 +228,16 @@ class EventDispatcherTest extends \PHPUnit_Framework_TestCase
|
||||
$this->dispatcher->removeSubscriber($eventSubscriber);
|
||||
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
|
||||
}
|
||||
|
||||
public function testEventReceivesTheDispatcherInstance()
|
||||
{
|
||||
$test = $this;
|
||||
$this->dispatcher->addListener('test', function ($event) use (&$dispatcher) {
|
||||
$dispatcher = $event->getDispatcher();
|
||||
});
|
||||
$this->dispatcher->dispatch('test');
|
||||
$this->assertSame($this->dispatcher, $dispatcher);
|
||||
}
|
||||
}
|
||||
|
||||
class TestEventListener
|
||||
|
Reference in New Issue
Block a user