Upgrading to 1.0.0-beta1 version of the API PHP implementation.

This commit is contained in:
ekes 2017-06-09 13:30:20 +01:00
parent 4424f09f06
commit 4ed51243b5
56 changed files with 1330 additions and 824 deletions

View file

@ -1,6 +1,20 @@
CHANGELOG
=========
3.3.0
-----
* The ContainerAwareEventDispatcher class has been deprecated. Use EventDispatcher with closure factories instead.
3.0.0
-----
* The method `getListenerPriority($eventName, $listener)` has been added to the
`EventDispatcherInterface`.
* The methods `Event::setDispatcher()`, `Event::getDispatcher()`, `Event::setName()`
and `Event::getName()` have been removed.
The event dispatcher and the event name are passed to the listener call.
2.5.0
-----

View file

@ -20,6 +20,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
* @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Jordan Alliot <jordan.alliot@gmail.com>
*
* @deprecated since 3.3, to be removed in 4.0. Use EventDispatcher with closure factories instead.
*/
class ContainerAwareEventDispatcher extends EventDispatcher
{
@ -52,6 +54,14 @@ class ContainerAwareEventDispatcher extends EventDispatcher
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$class = get_class($this);
if ($this instanceof \PHPUnit_Framework_MockObject_MockObject || $this instanceof \Prophecy\Doubler\DoubleInterface) {
$class = get_parent_class($class);
}
if (__CLASS__ !== $class) {
@trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED);
}
}
/**
@ -68,6 +78,8 @@ class ContainerAwareEventDispatcher extends EventDispatcher
*/
public function addListenerService($eventName, $callback, $priority = 0)
{
@trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED);
if (!is_array($callback) || 2 !== count($callback)) {
throw new \InvalidArgumentException('Expected an array("service", "method") argument');
}
@ -80,8 +92,7 @@ class ContainerAwareEventDispatcher extends EventDispatcher
$this->lazyLoad($eventName);
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as $i => $args) {
list($serviceId, $method, $priority) = $args;
foreach ($this->listenerIds[$eventName] as $i => list($serviceId, $method, $priority)) {
$key = $serviceId.'.'.$method;
if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) {
unset($this->listeners[$eventName][$key]);
@ -100,12 +111,12 @@ class ContainerAwareEventDispatcher extends EventDispatcher
}
/**
* @see EventDispatcherInterface::hasListeners()
* {@inheritdoc}
*/
public function hasListeners($eventName = null)
{
if (null === $eventName) {
return (bool) count($this->listenerIds) || (bool) count($this->listeners);
return $this->listenerIds || $this->listeners || parent::hasListeners();
}
if (isset($this->listenerIds[$eventName])) {
@ -116,12 +127,12 @@ class ContainerAwareEventDispatcher extends EventDispatcher
}
/**
* @see EventDispatcherInterface::getListeners()
* {@inheritdoc}
*/
public function getListeners($eventName = null)
{
if (null === $eventName) {
foreach (array_keys($this->listenerIds) as $serviceEventName) {
foreach ($this->listenerIds as $serviceEventName => $args) {
$this->lazyLoad($serviceEventName);
}
} else {
@ -131,6 +142,16 @@ class ContainerAwareEventDispatcher extends EventDispatcher
return parent::getListeners($eventName);
}
/**
* {@inheritdoc}
*/
public function getListenerPriority($eventName, $listener)
{
$this->lazyLoad($eventName);
return parent::getListenerPriority($eventName, $listener);
}
/**
* Adds a service as event subscriber.
*
@ -139,6 +160,8 @@ class ContainerAwareEventDispatcher extends EventDispatcher
*/
public function addSubscriberService($serviceId, $class)
{
@trigger_error(sprintf('The %s class is deprecated since version 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED);
foreach ($class::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->listenerIds[$eventName][] = array($serviceId, $params, 0);
@ -152,23 +175,10 @@ class ContainerAwareEventDispatcher extends EventDispatcher
}
}
/**
* {@inheritdoc}
*
* Lazily loads listeners for this event from the dependency injection
* container.
*
* @throws \InvalidArgumentException if the service is not defined
*/
public function dispatch($eventName, Event $event = null)
{
$this->lazyLoad($eventName);
return parent::dispatch($eventName, $event);
}
public function getContainer()
{
@trigger_error('The '.__METHOD__.'() method is deprecated since version 3.3 as its class will be removed in 4.0. Inject the container or the services you need in your listeners/subscribers instead.', E_USER_DEPRECATED);
return $this->container;
}
@ -183,8 +193,7 @@ class ContainerAwareEventDispatcher extends EventDispatcher
protected function lazyLoad($eventName)
{
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as $args) {
list($serviceId, $method, $priority) = $args;
foreach ($this->listenerIds[$eventName] as list($serviceId, $method, $priority)) {
$listener = $this->container->get($serviceId);
$key = $serviceId.'.'.$method;

View file

@ -31,6 +31,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
private $called;
private $dispatcher;
private $wrappedListeners;
/**
* Constructor.
@ -45,6 +46,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$this->stopwatch = $stopwatch;
$this->logger = $logger;
$this->called = array();
$this->wrappedListeners = array();
}
/**
@ -68,6 +70,16 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
*/
public function removeListener($eventName, $listener)
{
if (isset($this->wrappedListeners[$eventName])) {
foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
if ($wrappedListener->getWrappedListener() === $listener) {
$listener = $wrappedListener;
unset($this->wrappedListeners[$eventName][$index]);
break;
}
}
}
return $this->dispatcher->removeListener($eventName, $listener);
}
@ -87,6 +99,24 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
return $this->dispatcher->getListeners($eventName);
}
/**
* {@inheritdoc}
*/
public function getListenerPriority($eventName, $listener)
{
// we might have wrapped listeners for the event (if called while dispatching)
// in that case get the priority by wrapper
if (isset($this->wrappedListeners[$eventName])) {
foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) {
if ($wrappedListener->getWrappedListener() === $listener) {
return $this->dispatcher->getListenerPriority($eventName, $wrappedListener);
}
}
}
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
/**
* {@inheritdoc}
*/
@ -104,6 +134,10 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$event = new Event();
}
if (null !== $this->logger && $event->isPropagationStopped()) {
$this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName));
}
$this->preProcess($eventName);
$this->preDispatch($eventName, $event);
@ -129,8 +163,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$called = array();
foreach ($this->called as $eventName => $listeners) {
foreach ($listeners as $listener) {
$info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
$called[$eventName.'.'.$info['pretty']] = $info;
$called[$eventName.'.'.$listener->getPretty()] = $listener->getInfo($eventName);
}
}
@ -146,7 +179,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$allListeners = $this->getListeners();
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->info(sprintf('An exception was thrown while getting the uncalled listeners (%s)', $e->getMessage()), array('exception' => $e));
$this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e));
}
// unable to retrieve the uncalled listeners
@ -168,12 +201,16 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
}
if (!$called) {
$info = $this->getListenerInfo($listener, $eventName);
$notCalled[$eventName.'.'.$info['pretty']] = $info;
if (!$listener instanceof WrappedListener) {
$listener = new WrappedListener($listener, null, $this->stopwatch, $this);
}
$notCalled[$eventName.'.'.$listener->getPretty()] = $listener->getInfo($eventName);
}
}
}
uasort($notCalled, array($this, 'sortListenersByPriority'));
return $notCalled;
}
@ -213,28 +250,34 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
private function preProcess($eventName)
{
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
$priority = $this->getListenerPriority($eventName, $listener);
$wrappedListener = new WrappedListener($listener, null, $this->stopwatch, $this);
$this->wrappedListeners[$eventName][] = $wrappedListener;
$this->dispatcher->removeListener($eventName, $listener);
$info = $this->getListenerInfo($listener, $eventName);
$name = isset($info['class']) ? $info['class'] : $info['type'];
$this->dispatcher->addListener($eventName, new WrappedListener($listener, $name, $this->stopwatch, $this));
$this->dispatcher->addListener($eventName, $wrappedListener, $priority);
}
}
private function postProcess($eventName)
{
unset($this->wrappedListeners[$eventName]);
$skipped = false;
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch.
continue;
}
// Unwrap listener
$priority = $this->getListenerPriority($eventName, $listener);
$this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $listener->getWrappedListener());
$this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);
if (null !== $this->logger) {
$context = array('event' => $eventName, 'listener' => $listener->getPretty());
}
$info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
if ($listener->wasCalled()) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Notified event "%s" to listener "%s".', $eventName, $info['pretty']));
$this->logger->debug('Notified event "{event}" to listener "{listener}".', $context);
}
if (!isset($this->called[$eventName])) {
@ -245,12 +288,12 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
}
if (null !== $this->logger && $skipped) {
$this->logger->debug(sprintf('Listener "%s" was not called for event "%s".', $info['pretty'], $eventName));
$this->logger->debug('Listener "{listener}" was not called for event "{event}".', $context);
}
if ($listener->stoppedPropagation()) {
if (null !== $this->logger) {
$this->logger->debug(sprintf('Listener "%s" stopped propagation of the event "%s".', $info['pretty'], $eventName));
$this->logger->debug('Listener "{listener}" stopped propagation of the event "{event}".', $context);
}
$skipped = true;
@ -258,63 +301,24 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
}
}
/**
* Returns information about the listener
*
* @param object $listener The listener
* @param string $eventName The event name
*
* @return array Information about the listener
*/
private function getListenerInfo($listener, $eventName)
private function sortListenersByPriority($a, $b)
{
$info = array(
'event' => $eventName,
);
if ($listener instanceof \Closure) {
$info += array(
'type' => 'Closure',
'pretty' => 'closure',
);
} elseif (is_string($listener)) {
try {
$r = new \ReflectionFunction($listener);
$file = $r->getFileName();
$line = $r->getStartLine();
} catch (\ReflectionException $e) {
$file = null;
$line = null;
}
$info += array(
'type' => 'Function',
'function' => $listener,
'file' => $file,
'line' => $line,
'pretty' => $listener,
);
} elseif (is_array($listener) || (is_object($listener) && is_callable($listener))) {
if (!is_array($listener)) {
$listener = array($listener, '__invoke');
}
$class = is_object($listener[0]) ? get_class($listener[0]) : $listener[0];
try {
$r = new \ReflectionMethod($class, $listener[1]);
$file = $r->getFileName();
$line = $r->getStartLine();
} catch (\ReflectionException $e) {
$file = null;
$line = null;
}
$info += array(
'type' => 'Method',
'class' => $class,
'method' => $listener[1],
'file' => $file,
'line' => $line,
'pretty' => $class.'::'.$listener[1],
);
if (is_int($a['priority']) && !is_int($b['priority'])) {
return 1;
}
return $info;
if (!is_int($a['priority']) && is_int($b['priority'])) {
return -1;
}
if ($a['priority'] === $b['priority']) {
return 0;
}
if ($a['priority'] > $b['priority']) {
return -1;
}
return 1;
}
}

View file

@ -14,6 +14,8 @@ namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\VarDumper\Caster\ClassStub;
use Symfony\Component\VarDumper\Cloner\VarCloner;
/**
* @author Fabien Potencier <fabien@symfony.com>
@ -26,6 +28,10 @@ class WrappedListener
private $stoppedPropagation;
private $stopwatch;
private $dispatcher;
private $pretty;
private $stub;
private static $cloner;
public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
{
@ -35,6 +41,26 @@ class WrappedListener
$this->dispatcher = $dispatcher;
$this->called = false;
$this->stoppedPropagation = false;
if (is_array($listener)) {
$this->name = is_object($listener[0]) ? get_class($listener[0]) : $listener[0];
$this->pretty = $this->name.'::'.$listener[1];
} elseif ($listener instanceof \Closure) {
$this->pretty = $this->name = 'closure';
} elseif (is_string($listener)) {
$this->pretty = $this->name = $listener;
} else {
$this->name = get_class($listener);
$this->pretty = $this->name.'::__invoke';
}
if (null !== $name) {
$this->name = $name;
}
if (null === self::$cloner) {
self::$cloner = class_exists(ClassStub::class) ? new VarCloner() : false;
}
}
public function getWrappedListener()
@ -52,6 +78,25 @@ class WrappedListener
return $this->stoppedPropagation;
}
public function getPretty()
{
return $this->pretty;
}
public function getInfo($eventName)
{
if (null === $this->stub) {
$this->stub = false === self::$cloner ? $this->pretty.'()' : new ClassStub($this->pretty.'()', $this->listener);
}
return array(
'event' => $eventName,
'priority' => null !== $this->dispatcher ? $this->dispatcher->getListenerPriority($eventName, $this->listener) : null,
'pretty' => $this->pretty,
'stub' => $this->stub,
);
}
public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher)
{
$this->called = true;

View file

@ -11,8 +11,13 @@
namespace Symfony\Component\EventDispatcher\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Compiler pass to register tagged services for an event dispatcher.
@ -56,21 +61,14 @@ class RegisterListenersPass implements CompilerPassInterface
$definition = $container->findDefinition($this->dispatcherService);
foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) {
foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id));
}
if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id));
}
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;
if (!isset($event['event'])) {
throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
}
if (!isset($event['method'])) {
@ -81,30 +79,57 @@ class RegisterListenersPass implements CompilerPassInterface
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
}
$definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
$definition->addMethodCall('addListener', array($event['event'], array(new ServiceClosureArgument(new Reference($id)), $event['method']), $priority));
}
}
foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) {
$def = $container->getDefinition($id);
if (!$def->isPublic()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id));
}
$extractingDispatcher = new ExtractingEventDispatcher();
if ($def->isAbstract()) {
throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id));
}
foreach ($container->findTaggedServiceIds($this->subscriberTag, true) as $id => $attributes) {
$def = $container->getDefinition($id);
// We must assume that the class value has been correctly filled, even if the service is created by a factory
$class = $container->getParameterBag()->resolveValue($def->getClass());
$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
}
$definition->addMethodCall('addSubscriberService', array($id, $class));
if (!is_subclass_of($class, $interface)) {
if (!class_exists($class, false)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
}
$container->addObjectResource($class);
ExtractingEventDispatcher::$subscriber = $class;
$extractingDispatcher->addSubscriber($extractingDispatcher);
foreach ($extractingDispatcher->listeners as $args) {
$args[1] = array(new ServiceClosureArgument(new Reference($id)), $args[1]);
$definition->addMethodCall('addListener', $args);
}
$extractingDispatcher->listeners = array();
}
}
}
/**
* @internal
*/
class ExtractingEventDispatcher extends EventDispatcher implements EventSubscriberInterface
{
public $listeners = array();
public static $subscriber;
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[] = array($eventName, $listener[1], $priority);
}
public static function getSubscribedEvents()
{
$callback = array(self::$subscriber, 'getSubscribedEvents');
return $callback();
}
}

View file

@ -24,8 +24,6 @@ namespace Symfony\Component\EventDispatcher;
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
*/
class Event
{
@ -34,24 +32,12 @@ class Event
*/
private $propagationStopped = false;
/**
* @var EventDispatcher Dispatcher that dispatched this event
*/
private $dispatcher;
/**
* @var string This event's name
*/
private $name;
/**
* Returns whether further event listeners should be triggered.
*
* @see Event::stopPropagation()
*
* @return bool Whether propagation was already stopped for this event.
*
* @api
* @return bool Whether propagation was already stopped for this event
*/
public function isPropagationStopped()
{
@ -64,67 +50,9 @@ class Event
* If multiple event listeners are connected to the same event, no
* further event listener will be triggered once any trigger calls
* stopPropagation().
*
* @api
*/
public function stopPropagation()
{
$this->propagationStopped = true;
}
/**
* Stores the EventDispatcher that dispatches this Event.
*
* @param EventDispatcherInterface $dispatcher
*
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*
* @api
*/
public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Returns the EventDispatcher that dispatches this Event.
*
* @return EventDispatcherInterface
*
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*
* @api
*/
public function getDispatcher()
{
return $this->dispatcher;
}
/**
* Gets the event's name.
*
* @return string
*
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call.
*
* @api
*/
public function getName()
{
return $this->name;
}
/**
* Sets the event's name property.
*
* @param string $name The event name.
*
* @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call.
*
* @api
*/
public function setName($name)
{
$this->name = $name;
}
}

View file

@ -24,8 +24,7 @@ namespace Symfony\Component\EventDispatcher;
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Jordan Alliot <jordan.alliot@gmail.com>
*
* @api
* @author Nicolas Grekas <p@tchwork.com>
*/
class EventDispatcher implements EventDispatcherInterface
{
@ -33,9 +32,7 @@ class EventDispatcher implements EventDispatcherInterface
private $sorted = array();
/**
* @see EventDispatcherInterface::dispatch()
*
* @api
* {@inheritdoc}
*/
public function dispatch($eventName, Event $event = null)
{
@ -43,24 +40,23 @@ class EventDispatcher implements EventDispatcherInterface
$event = new Event();
}
$event->setDispatcher($this);
$event->setName($eventName);
if (!isset($this->listeners[$eventName])) {
return $event;
if ($listeners = $this->getListeners($eventName)) {
$this->doDispatch($listeners, $eventName, $event);
}
$this->doDispatch($this->getListeners($eventName), $eventName, $event);
return $event;
}
/**
* @see EventDispatcherInterface::getListeners()
* {@inheritdoc}
*/
public function getListeners($eventName = null)
{
if (null !== $eventName) {
if (empty($this->listeners[$eventName])) {
return array();
}
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
@ -68,7 +64,7 @@ class EventDispatcher implements EventDispatcherInterface
return $this->sorted[$eventName];
}
foreach (array_keys($this->listeners) as $eventName) {
foreach ($this->listeners as $eventName => $eventListeners) {
if (!isset($this->sorted[$eventName])) {
$this->sortListeners($eventName);
}
@ -78,17 +74,51 @@ class EventDispatcher implements EventDispatcherInterface
}
/**
* @see EventDispatcherInterface::hasListeners()
* {@inheritdoc}
*/
public function hasListeners($eventName = null)
public function getListenerPriority($eventName, $listener)
{
return (bool) count($this->getListeners($eventName));
if (empty($this->listeners[$eventName])) {
return;
}
if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
foreach ($listeners as $k => $v) {
if ($v !== $listener && is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
$v[0] = $v[0]();
$this->listeners[$eventName][$priority][$k] = $v;
}
if ($v === $listener) {
return $priority;
}
}
}
}
/**
* @see EventDispatcherInterface::addListener()
*
* @api
* {@inheritdoc}
*/
public function hasListeners($eventName = null)
{
if (null !== $eventName) {
return !empty($this->listeners[$eventName]);
}
foreach ($this->listeners as $eventListeners) {
if ($eventListeners) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function addListener($eventName, $listener, $priority = 0)
{
@ -97,25 +127,40 @@ class EventDispatcher implements EventDispatcherInterface
}
/**
* @see EventDispatcherInterface::removeListener()
* {@inheritdoc}
*/
public function removeListener($eventName, $listener)
{
if (!isset($this->listeners[$eventName])) {
if (empty($this->listeners[$eventName])) {
return;
}
if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
if (false !== ($key = array_search($listener, $listeners, true))) {
unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]);
foreach ($listeners as $k => $v) {
if ($v !== $listener && is_array($v) && isset($v[0]) && $v[0] instanceof \Closure) {
$v[0] = $v[0]();
}
if ($v === $listener) {
unset($listeners[$k], $this->sorted[$eventName]);
} else {
$listeners[$k] = $v;
}
}
if ($listeners) {
$this->listeners[$eventName][$priority] = $listeners;
} else {
unset($this->listeners[$eventName][$priority]);
}
}
}
/**
* @see EventDispatcherInterface::addSubscriber()
*
* @api
* {@inheritdoc}
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
@ -133,7 +178,7 @@ class EventDispatcher implements EventDispatcherInterface
}
/**
* @see EventDispatcherInterface::removeSubscriber()
* {@inheritdoc}
*/
public function removeSubscriber(EventSubscriberInterface $subscriber)
{
@ -154,32 +199,38 @@ class EventDispatcher implements EventDispatcherInterface
* This method can be overridden to add functionality that is executed
* for each listener.
*
* @param callable[] $listeners The event listeners.
* @param string $eventName The name of the event to dispatch.
* @param Event $event The event object to pass to the event handlers/listeners.
* @param callable[] $listeners The event listeners
* @param string $eventName The name of the event to dispatch
* @param Event $event The event object to pass to the event handlers/listeners
*/
protected function doDispatch($listeners, $eventName, Event $event)
{
foreach ($listeners as $listener) {
call_user_func($listener, $event, $eventName, $this);
if ($event->isPropagationStopped()) {
break;
}
call_user_func($listener, $event, $eventName, $this);
}
}
/**
* Sorts the internal list of listeners for the given event by priority.
*
* @param string $eventName The name of the event.
* @param string $eventName The name of the event
*/
private function sortListeners($eventName)
{
krsort($this->listeners[$eventName]);
$this->sorted[$eventName] = array();
if (isset($this->listeners[$eventName])) {
krsort($this->listeners[$eventName]);
$this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]);
foreach ($this->listeners[$eventName] as $priority => $listeners) {
foreach ($listeners as $k => $listener) {
if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
$this->listeners[$eventName][$priority][$k] = $listener;
}
$this->sorted[$eventName][] = $listener;
}
}
}
}

View file

@ -17,8 +17,6 @@ namespace Symfony\Component\EventDispatcher;
* manager.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
*/
interface EventDispatcherInterface
{
@ -28,12 +26,10 @@ interface EventDispatcherInterface
* @param string $eventName The name of the event to dispatch. The name of
* the event is the name of the method that is
* invoked on listeners.
* @param Event $event The event to pass to the event handlers/listeners.
* @param Event $event The event to pass to the event handlers/listeners
* If not supplied, an empty Event instance is created.
*
* @return Event
*
* @api
*/
public function dispatch($eventName, Event $event = null);
@ -44,8 +40,6 @@ interface EventDispatcherInterface
* @param callable $listener The listener
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*
* @api
*/
public function addListener($eventName, $listener, $priority = 0);
@ -55,9 +49,7 @@ interface EventDispatcherInterface
* The subscriber is asked for all the events he is
* interested in and added as a listener for these events.
*
* @param EventSubscriberInterface $subscriber The subscriber.
*
* @api
* @param EventSubscriberInterface $subscriber The subscriber
*/
public function addSubscriber(EventSubscriberInterface $subscriber);
@ -77,7 +69,7 @@ interface EventDispatcherInterface
public function removeSubscriber(EventSubscriberInterface $subscriber);
/**
* Gets the listeners of a specific event or all listeners.
* Gets the listeners of a specific event or all listeners sorted by descending priority.
*
* @param string $eventName The name of the event
*
@ -85,6 +77,18 @@ interface EventDispatcherInterface
*/
public function getListeners($eventName = null);
/**
* Gets the listener priority for a specific event.
*
* Returns null if the event or the listener does not exist.
*
* @param string $eventName The name of the event
* @param callable $listener The listener
*
* @return int|null The event listener priority
*/
public function getListenerPriority($eventName, $listener);
/**
* Checks whether an event has any registered listeners.
*

View file

@ -21,8 +21,6 @@ namespace Symfony\Component\EventDispatcher;
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api
*/
interface EventSubscriberInterface
{
@ -40,11 +38,9 @@ interface EventSubscriberInterface
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
*
* @return array The event names to listen to
*
* @api
*/
public static function getSubscribedEvents();
}

View file

@ -37,8 +37,8 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* Encapsulate an event with $subject and $args.
*
* @param mixed $subject The subject of the event, usually an object.
* @param array $arguments Arguments to store in the event.
* @param mixed $subject The subject of the event, usually an object
* @param array $arguments Arguments to store in the event
*/
public function __construct($subject = null, array $arguments = array())
{
@ -49,7 +49,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* Getter for subject property.
*
* @return mixed $subject The observer subject.
* @return mixed $subject The observer subject
*/
public function getSubject()
{
@ -59,11 +59,11 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* Get argument by key.
*
* @param string $key Key.
* @param string $key Key
*
* @return mixed Contents of array key
*
* @throws \InvalidArgumentException If key is not found.
*
* @return mixed Contents of array key.
*/
public function getArgument($key)
{
@ -71,16 +71,16 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
return $this->arguments[$key];
}
throw new \InvalidArgumentException(sprintf('%s not found in %s', $key, $this->getName()));
throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key));
}
/**
* Add argument to event.
*
* @param string $key Argument name.
* @param mixed $value Value.
* @param string $key Argument name
* @param mixed $value Value
*
* @return GenericEvent
* @return $this
*/
public function setArgument($key, $value)
{
@ -102,9 +102,9 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* Set args property.
*
* @param array $args Arguments.
* @param array $args Arguments
*
* @return GenericEvent
* @return $this
*/
public function setArguments(array $args = array())
{
@ -116,7 +116,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* Has argument.
*
* @param string $key Key of arguments array.
* @param string $key Key of arguments array
*
* @return bool
*/
@ -128,11 +128,11 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* ArrayAccess for argument getter.
*
* @param string $key Array key.
*
* @throws \InvalidArgumentException If key does not exist in $this->args.
* @param string $key Array key
*
* @return mixed
*
* @throws \InvalidArgumentException If key does not exist in $this->args.
*/
public function offsetGet($key)
{
@ -142,8 +142,8 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* ArrayAccess for argument setter.
*
* @param string $key Array key to set.
* @param mixed $value Value.
* @param string $key Array key to set
* @param mixed $value Value
*/
public function offsetSet($key, $value)
{
@ -153,7 +153,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* ArrayAccess for unset argument.
*
* @param string $key Array key.
* @param string $key Array key
*/
public function offsetUnset($key)
{
@ -165,7 +165,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
/**
* ArrayAccess has argument.
*
* @param string $key Array key.
* @param string $key Array key
*
* @return bool
*/

View file

@ -28,7 +28,7 @@ class ImmutableEventDispatcher implements EventDispatcherInterface
/**
* Creates an unmodifiable proxy for an event dispatcher.
*
* @param EventDispatcherInterface $dispatcher The proxied event dispatcher.
* @param EventDispatcherInterface $dispatcher The proxied event dispatcher
*/
public function __construct(EventDispatcherInterface $dispatcher)
{
@ -83,6 +83,14 @@ class ImmutableEventDispatcher implements EventDispatcherInterface
return $this->dispatcher->getListeners($eventName);
}
/**
* {@inheritdoc}
*/
public function getListenerPriority($eventName, $listener)
{
return $this->dispatcher->getListenerPriority($eventName, $listener);
}
/**
* {@inheritdoc}
*/

View file

@ -1,4 +1,4 @@
Copyright (c) 2004-2015 Fabien Potencier
Copyright (c) 2004-2017 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -0,0 +1,15 @@
EventDispatcher Component
=========================
The EventDispatcher component provides tools that allow your application
components to communicate with each other by dispatching events and listening to
them.
Resources
---------
* [Documentation](https://symfony.com/doc/current/components/event_dispatcher/index.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)

View file

@ -1,27 +0,0 @@
EventDispatcher Component
=========================
The Symfony EventDispatcher component implements the Mediator pattern in a
simple and effective way to make your projects truly extensible.
```php
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
$dispatcher = new EventDispatcher();
$dispatcher->addListener('event_name', function (Event $event) {
// ...
});
$dispatcher->dispatch('event_name');
```
Resources
---------
You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/EventDispatcher/
$ composer install
$ phpunit

View file

@ -1,100 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\EventDispatcher\Tests;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
/**
* Test class for Event.
*/
class EventTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Symfony\Component\EventDispatcher\Event
*/
protected $event;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
protected $dispatcher;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->event = new Event();
$this->dispatcher = new EventDispatcher();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->event = null;
$this->dispatcher = null;
}
public function testIsPropagationStopped()
{
$this->assertFalse($this->event->isPropagationStopped());
}
public function testStopPropagationAndIsPropagationStopped()
{
$this->event->stopPropagation();
$this->assertTrue($this->event->isPropagationStopped());
}
/**
* @group legacy
*/
public function testLegacySetDispatcher()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$this->event->setDispatcher($this->dispatcher);
$this->assertSame($this->dispatcher, $this->event->getDispatcher());
}
/**
* @group legacy
*/
public function testLegacyGetDispatcher()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$this->assertNull($this->event->getDispatcher());
}
/**
* @group legacy
*/
public function testLegacyGetName()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$this->assertNull($this->event->getName());
}
/**
* @group legacy
*/
public function testLegacySetName()
{
$this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);
$this->event->setName('foo');
$this->assertEquals('foo', $this->event->getName());
}
}

View file

@ -11,10 +11,12 @@
namespace Symfony\Component\EventDispatcher\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
abstract class AbstractEventDispatcherTest extends TestCase
{
/* Some pseudo events */
const preFoo = 'pre.foo';
@ -54,6 +56,7 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
$this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
$this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'));
$this->assertTrue($this->dispatcher->hasListeners());
$this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
$this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
$this->assertCount(1, $this->dispatcher->getListeners(self::preFoo));
@ -107,6 +110,20 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertSame($expected, $this->dispatcher->getListeners());
}
public function testGetListenerPriority()
{
$listener1 = new TestEventListener();
$listener2 = new TestEventListener();
$this->dispatcher->addListener('pre.foo', $listener1, -10);
$this->dispatcher->addListener('pre.foo', $listener2);
$this->assertSame(-10, $this->dispatcher->getListenerPriority('pre.foo', $listener1));
$this->assertSame(0, $this->dispatcher->getListenerPriority('pre.foo', $listener2));
$this->assertNull($this->dispatcher->getListenerPriority('pre.bar', $listener2));
$this->assertNull($this->dispatcher->getListenerPriority('pre.foo', function () {}));
}
public function testDispatch()
{
$this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
@ -118,7 +135,6 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo));
$event = new Event();
$return = $this->dispatcher->dispatch(self::preFoo, $event);
$this->assertEquals('pre.foo', $event->getName());
$this->assertSame($event, $return);
}
@ -126,7 +142,7 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
$invoked = 0;
$listener = function () use (&$invoked) {
$invoked++;
++$invoked;
};
$this->dispatcher->addListener('pre.foo', $listener);
$this->dispatcher->addListener('post.foo', $listener);
@ -239,16 +255,6 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
}
public function testEventReceivesTheDispatcherInstance()
{
$dispatcher = null;
$this->dispatcher->addListener('test', function ($event) use (&$dispatcher) {
$dispatcher = $event->getDispatcher();
});
$this->dispatcher->dispatch('test');
$this->assertSame($this->dispatcher, $dispatcher);
}
public function testEventReceivesTheDispatcherInstanceAsArgument()
{
$listener = new TestWithDispatcher();
@ -297,6 +303,73 @@ abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($this->dispatcher->hasListeners('foo'));
$this->assertFalse($this->dispatcher->hasListeners());
}
public function testHasListenersIsLazy()
{
$called = 0;
$listener = array(function () use (&$called) { ++$called; }, 'onFoo');
$this->dispatcher->addListener('foo', $listener);
$this->assertTrue($this->dispatcher->hasListeners());
$this->assertTrue($this->dispatcher->hasListeners('foo'));
$this->assertSame(0, $called);
}
public function testDispatchLazyListener()
{
$called = 0;
$factory = function () use (&$called) {
++$called;
return new TestWithDispatcher();
};
$this->dispatcher->addListener('foo', array($factory, 'foo'));
$this->assertSame(0, $called);
$this->dispatcher->dispatch('foo', new Event());
$this->dispatcher->dispatch('foo', new Event());
$this->assertSame(1, $called);
}
public function testRemoveFindsLazyListeners()
{
$test = new TestWithDispatcher();
$factory = function () use ($test) { return $test; };
$this->dispatcher->addListener('foo', array($factory, 'foo'));
$this->assertTrue($this->dispatcher->hasListeners('foo'));
$this->dispatcher->removeListener('foo', array($test, 'foo'));
$this->assertFalse($this->dispatcher->hasListeners('foo'));
$this->dispatcher->addListener('foo', array($test, 'foo'));
$this->assertTrue($this->dispatcher->hasListeners('foo'));
$this->dispatcher->removeListener('foo', array($factory, 'foo'));
$this->assertFalse($this->dispatcher->hasListeners('foo'));
}
public function testPriorityFindsLazyListeners()
{
$test = new TestWithDispatcher();
$factory = function () use ($test) { return $test; };
$this->dispatcher->addListener('foo', array($factory, 'foo'), 3);
$this->assertSame(3, $this->dispatcher->getListenerPriority('foo', array($test, 'foo')));
$this->dispatcher->removeListener('foo', array($factory, 'foo'));
$this->dispatcher->addListener('foo', array($test, 'foo'), 5);
$this->assertSame(5, $this->dispatcher->getListenerPriority('foo', array($factory, 'foo')));
}
public function testGetLazyListeners()
{
$test = new TestWithDispatcher();
$factory = function () use ($test) { return $test; };
$this->dispatcher->addListener('foo', array($factory, 'foo'), 3);
$this->assertSame(array(array($test, 'foo')), $this->dispatcher->getListeners('foo'));
$this->dispatcher->removeListener('foo', array($test, 'foo'));
$this->dispatcher->addListener('bar', array($factory, 'foo'), 3);
$this->assertSame(array('bar' => array(array($test, 'foo'))), $this->dispatcher->getListeners());
}
}
class CallableClass

View file

@ -12,11 +12,13 @@
namespace Symfony\Component\EventDispatcher\Tests;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @group legacy
*/
class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
{
protected function createEventDispatcher()
@ -30,7 +32,7 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
{
$event = new Event();
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$service
->expects($this->once())
@ -51,7 +53,7 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
{
$event = new Event();
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\SubscriberService');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\SubscriberService')->getMock();
$service
->expects($this->once())
@ -59,6 +61,18 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
->with($event)
;
$service
->expects($this->once())
->method('onEventWithPriority')
->with($event)
;
$service
->expects($this->once())
->method('onEventNested')
->with($event)
;
$container = new Container();
$container->set('service.subscriber', $service);
@ -66,13 +80,15 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
$dispatcher->addSubscriberService('service.subscriber', 'Symfony\Component\EventDispatcher\Tests\SubscriberService');
$dispatcher->dispatch('onEvent', $event);
$dispatcher->dispatch('onEventWithPriority', $event);
$dispatcher->dispatch('onEventNested', $event);
}
public function testPreventDuplicateListenerService()
{
$event = new Event();
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$service
->expects($this->once())
@ -90,73 +106,11 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
$dispatcher->dispatch('onEvent', $event);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testTriggerAListenerServiceOutOfScope()
{
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$scope = new Scope('scope');
$container = new Container();
$container->addScope($scope);
$container->enterScope('scope');
$container->set('service.listener', $service, 'scope');
$dispatcher = new ContainerAwareEventDispatcher($container);
$dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
$container->leaveScope('scope');
$dispatcher->dispatch('onEvent');
}
public function testReEnteringAScope()
{
$event = new Event();
$service1 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service1
->expects($this->exactly(2))
->method('onEvent')
->with($event)
;
$scope = new Scope('scope');
$container = new Container();
$container->addScope($scope);
$container->enterScope('scope');
$container->set('service.listener', $service1, 'scope');
$dispatcher = new ContainerAwareEventDispatcher($container);
$dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
$dispatcher->dispatch('onEvent', $event);
$service2 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service2
->expects($this->once())
->method('onEvent')
->with($event)
;
$container->enterScope('scope');
$container->set('service.listener', $service2, 'scope');
$dispatcher->dispatch('onEvent', $event);
$container->leaveScope('scope');
$dispatcher->dispatch('onEvent');
}
public function testHasListenersOnLazyLoad()
{
$event = new Event();
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$container = new Container();
$container->set('service.listener', $service);
@ -164,9 +118,6 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
$dispatcher = new ContainerAwareEventDispatcher($container);
$dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
$event->setDispatcher($dispatcher);
$event->setName('onEvent');
$service
->expects($this->once())
->method('onEvent')
@ -182,7 +133,7 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
public function testGetListenersOnLazyLoad()
{
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$container = new Container();
$container->set('service.listener', $service);
@ -199,7 +150,7 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
public function testRemoveAfterDispatch()
{
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$container = new Container();
$container->set('service.listener', $service);
@ -214,7 +165,7 @@ class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest
public function testRemoveBeforeDispatch()
{
$service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');
$service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock();
$container = new Container();
$container->set('service.listener', $service);
@ -239,11 +190,21 @@ class SubscriberService implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
'onEvent' => array('onEvent'),
'onEvent' => 'onEvent',
'onEventWithPriority' => array('onEventWithPriority', 10),
'onEventNested' => array(array('onEventNested')),
);
}
public function onEvent(Event $e)
{
}
public function onEventWithPriority(Event $e)
{
}
public function onEventNested(Event $e)
{
}
}

View file

@ -11,20 +11,22 @@
namespace Symfony\Component\EventDispatcher\Tests\Debug;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Stopwatch\Stopwatch;
class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
class TraceableEventDispatcherTest extends TestCase
{
public function testAddRemoveListener()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () {; });
$tdispatcher->addListener('foo', $listener = function () {});
$listeners = $dispatcher->getListeners('foo');
$this->assertCount(1, $listeners);
$this->assertSame($listener, $listeners[0]);
@ -38,7 +40,7 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () {; });
$tdispatcher->addListener('foo', $listener = function () {});
$this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo'));
}
@ -50,11 +52,42 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($dispatcher->hasListeners('foo'));
$this->assertFalse($tdispatcher->hasListeners('foo'));
$tdispatcher->addListener('foo', $listener = function () {; });
$tdispatcher->addListener('foo', $listener = function () {});
$this->assertTrue($dispatcher->hasListeners('foo'));
$this->assertTrue($tdispatcher->hasListeners('foo'));
}
public function testGetListenerPriority()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', function () {}, 123);
$listeners = $dispatcher->getListeners('foo');
$this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0]));
// Verify that priority is preserved when listener is removed and re-added
// in preProcess() and postProcess().
$tdispatcher->dispatch('foo', new Event());
$listeners = $dispatcher->getListeners('foo');
$this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0]));
}
public function testGetListenerPriorityWhileDispatching()
{
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$priorityWhileDispatching = null;
$listener = function () use ($tdispatcher, &$priorityWhileDispatching, &$listener) {
$priorityWhileDispatching = $tdispatcher->getListenerPriority('bar', $listener);
};
$tdispatcher->addListener('bar', $listener, 5);
$tdispatcher->dispatch('bar');
$this->assertSame(5, $priorityWhileDispatching);
}
public function testAddRemoveSubscriber()
{
$dispatcher = new EventDispatcher();
@ -73,16 +106,21 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
public function testGetCalledListeners()
{
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener = function () {; });
$tdispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$tdispatcher->addListener('foo', function () {}, 5);
$listeners = $tdispatcher->getNotCalledListeners();
$this->assertArrayHasKey('stub', $listeners['foo.closure']);
unset($listeners['foo.closure']['stub']);
$this->assertEquals(array(), $tdispatcher->getCalledListeners());
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getNotCalledListeners());
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'pretty' => 'closure', 'priority' => 5)), $listeners);
$tdispatcher->dispatch('foo');
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getCalledListeners());
$listeners = $tdispatcher->getCalledListeners();
$this->assertArrayHasKey('stub', $listeners['foo.closure']);
unset($listeners['foo.closure']['stub']);
$this->assertEquals(array('foo.closure' => array('event' => 'foo', 'pretty' => 'closure', 'priority' => 5)), $listeners);
$this->assertEquals(array(), $tdispatcher->getNotCalledListeners());
}
@ -102,31 +140,31 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
public function testLogger()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
$tdispatcher->addListener('foo', $listener1 = function () {; });
$tdispatcher->addListener('foo', $listener2 = function () {; });
$tdispatcher->addListener('foo', $listener1 = function () {});
$tdispatcher->addListener('foo', $listener2 = function () {});
$logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$logger->expects($this->at(1))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$logger->expects($this->at(0))->method('debug')->with('Notified event "{event}" to listener "{listener}".', array('event' => 'foo', 'listener' => 'closure'));
$logger->expects($this->at(1))->method('debug')->with('Notified event "{event}" to listener "{listener}".', array('event' => 'foo', 'listener' => 'closure'));
$tdispatcher->dispatch('foo');
}
public function testLoggerWithStoppedEvent()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
$tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); });
$tdispatcher->addListener('foo', $listener2 = function () {; });
$tdispatcher->addListener('foo', $listener2 = function () {});
$logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
$logger->expects($this->at(1))->method('debug')->with("Listener \"closure\" stopped propagation of the event \"foo\".");
$logger->expects($this->at(2))->method('debug')->with("Listener \"closure\" was not called for event \"foo\".");
$logger->expects($this->at(0))->method('debug')->with('Notified event "{event}" to listener "{listener}".', array('event' => 'foo', 'listener' => 'closure'));
$logger->expects($this->at(1))->method('debug')->with('Listener "{listener}" stopped propagation of the event "{event}".', array('event' => 'foo', 'listener' => 'closure'));
$logger->expects($this->at(2))->method('debug')->with('Listener "{listener}" was not called for event "{event}".', array('event' => 'foo', 'listener' => 'closure'));
$tdispatcher->dispatch('foo');
}
@ -137,26 +175,32 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
$dispatcher = new EventDispatcher();
$tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
$tdispatcher->addListener('foo', $listener1 = function () use (&$called) { $called[] = 'foo1'; });
$tdispatcher->addListener('foo', $listener2 = function () use (&$called) { $called[] = 'foo2'; });
$tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo1'; }, 10);
$tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo2'; }, 20);
$tdispatcher->dispatch('foo');
$this->assertEquals(array('foo1', 'foo2'), $called);
$this->assertSame(array('foo2', 'foo1'), $called);
}
public function testDispatchNested()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$loop = 1;
$dispatchedEvents = 0;
$dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) {
++$loop;
if (2 == $loop) {
$dispatcher->dispatch('foo');
}
});
$dispatcher->addListener('foo', function () use (&$dispatchedEvents) {
++$dispatchedEvents;
});
$dispatcher->dispatch('foo');
$this->assertSame(2, $dispatchedEvents);
}
public function testDispatchReusedEventNested()
@ -174,6 +218,19 @@ class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
$dispatcher->dispatch('foo');
$this->assertTrue($nestedCall);
}
public function testListenerCanRemoveItselfWhenExecuted()
{
$eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$listener1 = function ($event, $eventName, EventDispatcherInterface $dispatcher) use (&$listener1) {
$dispatcher->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');
}
}
class EventSubscriber implements EventSubscriberInterface

View file

@ -11,10 +11,13 @@
namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
class RegisterListenersPassTest extends TestCase
{
/**
* Tests that event subscribers not implementing EventSubscriberInterface
@ -29,18 +32,12 @@ class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('isPublic')
->will($this->returnValue(true));
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('stdClass'));
$builder = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition')
);
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
@ -64,18 +61,12 @@ class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
'my_event_subscriber' => array(0 => array()),
);
$definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
$definition->expects($this->atLeastOnce())
->method('isPublic')
->will($this->returnValue(true));
$definition = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')->getMock();
$definition->expects($this->atLeastOnce())
->method('getClass')
->will($this->returnValue('Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'));
$builder = $this->getMock(
'Symfony\Component\DependencyInjection\ContainerBuilder',
array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'findDefinition')
);
$builder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->setMethods(array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'findDefinition'))->getMock();
$builder->expects($this->any())
->method('hasDefinition')
->will($this->returnValue(true));
@ -99,35 +90,7 @@ class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded.
*/
public function testPrivateEventListener()
{
$container = new ContainerBuilder();
$container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array());
$container->register('event_dispatcher', 'stdClass');
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($container);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded.
*/
public function testPrivateEventSubscriber()
{
$container = new ContainerBuilder();
$container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array());
$container->register('event_dispatcher', 'stdClass');
$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($container);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded.
* @expectedExceptionMessage The service "foo" tagged "kernel.event_listener" must not be abstract.
*/
public function testAbstractEventListener()
{
@ -141,7 +104,7 @@ class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The service "foo" must not be abstract as event subscribers are lazy-loaded.
* @expectedExceptionMessage The service "foo" tagged "kernel.event_subscriber" must not be abstract.
*/
public function testAbstractEventSubscriber()
{
@ -165,16 +128,17 @@ class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
$registerListenersPass->process($container);
$definition = $container->getDefinition('event_dispatcher');
$expected_calls = array(
$expectedCalls = array(
array(
'addSubscriberService',
'addListener',
array(
'foo',
'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService',
'event',
array(new ServiceClosureArgument(new Reference('foo')), 'onEvent'),
0,
),
),
);
$this->assertSame($expected_calls, $definition->getMethodCalls());
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}
/**
@ -196,5 +160,8 @@ class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubsc
{
public static function getSubscribedEvents()
{
return array(
'event' => 'onEvent',
);
}
}

View file

@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\EventDispatcher\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
/**
* Test class for Event.
*/
class EventTest extends TestCase
{
/**
* @var \Symfony\Component\EventDispatcher\Event
*/
protected $event;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->event = new Event();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->event = null;
}
public function testIsPropagationStopped()
{
$this->assertFalse($this->event->isPropagationStopped());
}
public function testStopPropagationAndIsPropagationStopped()
{
$this->event->stopPropagation();
$this->assertTrue($this->event->isPropagationStopped());
}
}

View file

@ -11,12 +11,13 @@
namespace Symfony\Component\EventDispatcher\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\GenericEvent;
/**
* Test class for Event.
*/
class GenericEventTest extends \PHPUnit_Framework_TestCase
class GenericEventTest extends TestCase
{
/**
* @var GenericEvent
@ -95,7 +96,7 @@ class GenericEventTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('Event', $this->event['name']);
// test getting invalid arg
$this->setExpectedException('InvalidArgumentException');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
$this->assertFalse($this->event['nameNotExist']);
}

View file

@ -11,13 +11,14 @@
namespace Symfony\Component\EventDispatcher\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\ImmutableEventDispatcher;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase
class ImmutableEventDispatcherTest extends TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
@ -31,7 +32,7 @@ class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
$this->innerDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$this->innerDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher);
}
@ -80,7 +81,7 @@ class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase
*/
public function testAddSubscriberDisallowed()
{
$subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface');
$subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock();
$this->dispatcher->addSubscriber($subscriber);
}
@ -98,7 +99,7 @@ class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase
*/
public function testRemoveSubscriberDisallowed()
{
$subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface');
$subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock();
$this->dispatcher->removeSubscriber($subscriber);
}

View file

@ -3,7 +3,7 @@
"type": "library",
"description": "Symfony EventDispatcher Component",
"keywords": [],
"homepage": "http://symfony.com",
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
@ -12,32 +12,36 @@
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=5.3.3"
"php": ">=5.5.9"
},
"require-dev": {
"symfony/phpunit-bridge": "~2.7",
"symfony/dependency-injection": "~2.6",
"symfony/expression-language": "~2.6",
"symfony/config": "~2.0,>=2.0.5",
"symfony/stopwatch": "~2.3",
"symfony/dependency-injection": "~3.3",
"symfony/expression-language": "~2.8|~3.0",
"symfony/config": "~2.8|~3.0",
"symfony/stopwatch": "~2.8|~3.0",
"psr/log": "~1.0"
},
"conflict": {
"symfony/dependency-injection": "<3.3"
},
"suggest": {
"symfony/dependency-injection": "",
"symfony/http-kernel": ""
},
"autoload": {
"psr-0": { "Symfony\\Component\\EventDispatcher\\": "" }
"psr-4": { "Symfony\\Component\\EventDispatcher\\": "" },
"exclude-from-classmap": [
"/Tests/"
]
},
"target-dir": "Symfony/Component/EventDispatcher",
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.6-dev"
"dev-master": "3.3-dev"
}
}
}

View file

@ -5,10 +5,13 @@
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />
</php>
<testsuites>
<testsuite name="Symfony EventDispatcher Component Test Suite">
<directory>./Tests/</directory>