Augmentation vers version 3.3.0

This commit is contained in:
Gauvain Boiché
2020-03-31 15:31:03 +02:00
parent d926806907
commit a1864c0414
2618 changed files with 406015 additions and 31377 deletions

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\EventDispatcher;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -20,6 +21,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
{
@@ -28,16 +31,24 @@ class ContainerAwareEventDispatcher extends EventDispatcher
/**
* The service IDs of the event listeners and subscribers.
*/
private $listenerIds = array();
private $listenerIds = [];
/**
* The services registered as listeners.
*/
private $listeners = array();
private $listeners = [];
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$class = \get_class($this);
if ($this instanceof \PHPUnit_Framework_MockObject_MockObject || $this instanceof MockObject || $this instanceof \Prophecy\Doubler\DoubleInterface) {
$class = get_parent_class($class);
}
if (__CLASS__ !== $class) {
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.3 and will be removed in 4.0. Use EventDispatcher with closure factories instead.', __CLASS__), E_USER_DEPRECATED);
}
}
/**
@@ -54,11 +65,13 @@ class ContainerAwareEventDispatcher extends EventDispatcher
*/
public function addListenerService($eventName, $callback, $priority = 0)
{
@trigger_error(sprintf('The %s class is deprecated since Symfony 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');
throw new \InvalidArgumentException('Expected an ["service", "method"] argument');
}
$this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority);
$this->listenerIds[$eventName][] = [$callback[0], $callback[1], $priority];
}
public function removeListener($eventName, $listener)
@@ -66,10 +79,9 @@ class ContainerAwareEventDispatcher extends EventDispatcher
$this->lazyLoad($eventName);
if (isset($this->listenerIds[$eventName])) {
foreach ($this->listenerIds[$eventName] as $i => $args) {
list($serviceId, $method) = $args;
foreach ($this->listenerIds[$eventName] as $i => list($serviceId, $method)) {
$key = $serviceId.'.'.$method;
if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) {
if (isset($this->listeners[$eventName][$key]) && $listener === [$this->listeners[$eventName][$key], $method]) {
unset($this->listeners[$eventName][$key]);
if (empty($this->listeners[$eventName])) {
unset($this->listeners[$eventName]);
@@ -135,14 +147,16 @@ class ContainerAwareEventDispatcher extends EventDispatcher
*/
public function addSubscriberService($serviceId, $class)
{
@trigger_error(sprintf('The %s class is deprecated since Symfony 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);
$this->listenerIds[$eventName][] = [$serviceId, $params, 0];
} elseif (\is_string($params[0])) {
$this->listenerIds[$eventName][] = array($serviceId, $params[0], isset($params[1]) ? $params[1] : 0);
$this->listenerIds[$eventName][] = [$serviceId, $params[0], isset($params[1]) ? $params[1] : 0];
} else {
foreach ($params as $listener) {
$this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0);
$this->listenerIds[$eventName][] = [$serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0];
}
}
}
@@ -150,6 +164,8 @@ class ContainerAwareEventDispatcher extends EventDispatcher
public function getContainer()
{
@trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 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;
}
@@ -164,16 +180,15 @@ 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;
if (!isset($this->listeners[$eventName][$key])) {
$this->addListener($eventName, array($listener, $method), $priority);
$this->addListener($eventName, [$listener, $method], $priority);
} elseif ($this->listeners[$eventName][$key] !== $listener) {
parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method));
$this->addListener($eventName, array($listener, $method), $priority);
parent::removeListener($eventName, [$this->listeners[$eventName][$key], $method]);
$this->addListener($eventName, [$listener, $method], $priority);
}
$this->listeners[$eventName][$key] = $listener;

View File

@@ -29,7 +29,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
protected $logger;
protected $stopwatch;
private $called;
private $callStack;
private $dispatcher;
private $wrappedListeners;
@@ -38,8 +38,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$this->dispatcher = $dispatcher;
$this->stopwatch = $stopwatch;
$this->logger = $logger;
$this->called = array();
$this->wrappedListeners = array();
$this->wrappedListeners = [];
}
/**
@@ -97,8 +96,14 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
*/
public function getListenerPriority($eventName, $listener)
{
if (!method_exists($this->dispatcher, 'getListenerPriority')) {
return 0;
// 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);
@@ -117,6 +122,10 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
*/
public function dispatch($eventName, Event $event = null)
{
if (null === $this->callStack) {
$this->callStack = new \SplObjectStorage();
}
if (null === $event) {
$event = new Event();
}
@@ -126,19 +135,24 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
}
$this->preProcess($eventName);
$this->preDispatch($eventName, $event);
$e = $this->stopwatch->start($eventName, 'section');
$this->dispatcher->dispatch($eventName, $event);
if ($e->isStarted()) {
$e->stop();
try {
$this->preDispatch($eventName, $event);
try {
$e = $this->stopwatch->start($eventName, 'section');
try {
$this->dispatcher->dispatch($eventName, $event);
} finally {
if ($e->isStarted()) {
$e->stop();
}
}
} finally {
$this->postDispatch($eventName, $event);
}
} finally {
$this->postProcess($eventName);
}
$this->postDispatch($eventName, $event);
$this->postProcess($eventName);
return $event;
}
@@ -147,12 +161,15 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
*/
public function getCalledListeners()
{
$called = array();
foreach ($this->called as $eventName => $listeners) {
foreach ($listeners as $listener) {
$info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
$called[$eventName.'.'.$info['pretty']] = $info;
}
if (null === $this->callStack) {
return [];
}
$called = [];
foreach ($this->callStack as $listener) {
list($eventName) = $this->callStack->getInfo();
$called[] = $listener->getInfo($eventName);
}
return $called;
@@ -167,39 +184,43 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$allListeners = $this->getListeners();
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e));
$this->logger->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
}
// unable to retrieve the uncalled listeners
return array();
return [];
}
$notCalled = array();
$calledListeners = [];
if (null !== $this->callStack) {
foreach ($this->callStack as $calledListener) {
$calledListeners[] = $calledListener->getWrappedListener();
}
}
$notCalled = [];
foreach ($allListeners as $eventName => $listeners) {
foreach ($listeners as $listener) {
$called = false;
if (isset($this->called[$eventName])) {
foreach ($this->called[$eventName] as $l) {
if ($l->getWrappedListener() === $listener) {
$called = true;
break;
}
if (!\in_array($listener, $calledListeners, true)) {
if (!$listener instanceof WrappedListener) {
$listener = new WrappedListener($listener, null, $this->stopwatch, $this);
}
}
if (!$called) {
$info = $this->getListenerInfo($listener, $eventName);
$notCalled[$eventName.'.'.$info['pretty']] = $info;
$notCalled[] = $listener->getInfo($eventName);
}
}
}
uasort($notCalled, array($this, 'sortListenersByPriority'));
uasort($notCalled, [$this, 'sortNotCalledListeners']);
return $notCalled;
}
public function reset()
{
$this->callStack = null;
}
/**
* Proxies all method calls to the original event dispatcher.
*
@@ -210,7 +231,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
*/
public function __call($method, $arguments)
{
return \call_user_func_array(array($this->dispatcher, $method), $arguments);
return \call_user_func_array([$this->dispatcher, $method], $arguments);
}
/**
@@ -236,12 +257,12 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
private function preProcess($eventName)
{
foreach ($this->dispatcher->getListeners($eventName) as $listener) {
$info = $this->getListenerInfo($listener, $eventName);
$name = isset($info['class']) ? $info['class'] : $info['type'];
$wrappedListener = new WrappedListener($listener, $name, $this->stopwatch, $this);
$priority = $this->getListenerPriority($eventName, $listener);
$wrappedListener = new WrappedListener($listener instanceof WrappedListener ? $listener->getWrappedListener() : $listener, null, $this->stopwatch, $this);
$this->wrappedListeners[$eventName][] = $wrappedListener;
$this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $wrappedListener, $info['priority']);
$this->dispatcher->addListener($eventName, $wrappedListener, $priority);
$this->callStack->attach($wrappedListener, [$eventName]);
}
}
@@ -258,26 +279,25 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface
$this->dispatcher->removeListener($eventName, $listener);
$this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority);
$info = $this->getListenerInfo($listener->getWrappedListener(), $eventName);
if (null !== $this->logger) {
$context = ['event' => $eventName, 'listener' => $listener->getPretty()];
}
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])) {
$this->called[$eventName] = new \SplObjectStorage();
}
$this->called[$eventName]->attach($listener);
} else {
$this->callStack->detach($listener);
}
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;
@@ -285,75 +305,12 @@ 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 sortNotCalledListeners(array $a, array $b)
{
$info = array(
'event' => $eventName,
'priority' => $this->getListenerPriority($eventName, $listener),
);
// unwrap for correct listener info
if ($listener instanceof WrappedListener) {
$listener = $listener->getWrappedListener();
if (0 !== $cmp = strcmp($a['event'], $b['event'])) {
return $cmp;
}
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],
);
}
return $info;
}
private function sortListenersByPriority($a, $b)
{
if (\is_int($a['priority']) && !\is_int($b['priority'])) {
return 1;
}

View File

@@ -15,6 +15,8 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @method reset() Resets the trace.
*/
interface TraceableEventDispatcherInterface extends EventDispatcherInterface
{

View File

@@ -14,6 +14,7 @@ namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\VarDumper\Caster\ClassStub;
/**
* @author Fabien Potencier <fabien@symfony.com>
@@ -26,15 +27,46 @@ class WrappedListener
private $stoppedPropagation;
private $stopwatch;
private $dispatcher;
private $pretty;
private $stub;
private $priority;
private static $hasClassStub;
public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null)
{
$this->listener = $listener;
$this->name = $name;
$this->stopwatch = $stopwatch;
$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) {
$r = new \ReflectionFunction($listener);
if (false !== strpos($r->name, '{closure}')) {
$this->pretty = $this->name = 'closure';
} elseif ($class = $r->getClosureScopeClass()) {
$this->name = $class->name;
$this->pretty = $this->name.'::'.$r->name;
} else {
$this->pretty = $this->name = $r->name;
}
} 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::$hasClassStub) {
self::$hasClassStub = class_exists(ClassStub::class);
}
}
public function getWrappedListener()
@@ -52,13 +84,35 @@ class WrappedListener
return $this->stoppedPropagation;
}
public function getPretty()
{
return $this->pretty;
}
public function getInfo($eventName)
{
if (null === $this->stub) {
$this->stub = self::$hasClassStub ? new ClassStub($this->pretty.'()', $this->listener) : $this->pretty.'()';
}
return [
'event' => $eventName,
'priority' => null !== $this->priority ? $this->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)
{
$dispatcher = $this->dispatcher ?: $dispatcher;
$this->called = true;
$this->priority = $dispatcher->getListenerPriority($eventName, $this->listener);
$e = $this->stopwatch->start($this->name, 'event_listener');
\call_user_func($this->listener, $event, $eventName, $this->dispatcher ?: $dispatcher);
\call_user_func($this->listener, $event, $eventName, $dispatcher);
if ($e->isStarted()) {
$e->stop();

View File

@@ -11,8 +11,13 @@
namespace Symfony\Component\EventDispatcher\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
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.
@@ -23,6 +28,9 @@ class RegisterListenersPass implements CompilerPassInterface
protected $listenerTag;
protected $subscriberTag;
private $hotPathEvents = [];
private $hotPathTagName;
/**
* @param string $dispatcherService Service name of the event dispatcher in processed container
* @param string $listenerTag Tag name used for listener
@@ -35,6 +43,14 @@ class RegisterListenersPass implements CompilerPassInterface
$this->subscriberTag = $subscriberTag;
}
public function setHotPathEvents(array $hotPathEvents, $tagName = 'container.hot_path')
{
$this->hotPathEvents = array_flip($hotPathEvents);
$this->hotPathTagName = $tagName;
return $this;
}
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) {
@@ -43,58 +59,79 @@ class RegisterListenersPass implements CompilerPassInterface
$definition = $container->findDefinition($this->dispatcherService);
foreach ($container->findTaggedServiceIds($this->listenerTag) 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 ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
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'])) {
$event['method'] = 'on'.preg_replace_callback(array(
$event['method'] = 'on'.preg_replace_callback([
'/(?<=\b)[a-z]/i',
'/[^a-z0-9]/i',
), function ($matches) { return strtoupper($matches[0]); }, $event['event']);
], function ($matches) { return strtoupper($matches[0]); }, $event['event']);
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);
}
$definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
$definition->addMethodCall('addListener', [$event['event'], [new ServiceClosureArgument(new Reference($id)), $event['method']], $priority]);
if (isset($this->hotPathEvents[$event['event']])) {
$container->getDefinition($id)->addTag($this->hotPathTagName);
}
}
}
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());
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
$class = $def->getClass();
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));
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(EventSubscriberInterface::class)) {
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EventSubscriberInterface::class));
}
$class = $r->name;
$definition->addMethodCall('addSubscriberService', array($id, $class));
ExtractingEventDispatcher::$subscriber = $class;
$extractingDispatcher->addSubscriber($extractingDispatcher);
foreach ($extractingDispatcher->listeners as $args) {
$args[1] = [new ServiceClosureArgument(new Reference($id)), $args[1]];
$definition->addMethodCall('addListener', $args);
if (isset($this->hotPathEvents[$args[0]])) {
$container->getDefinition($id)->addTag($this->hotPathTagName);
}
}
$extractingDispatcher->listeners = [];
}
}
}
/**
* @internal
*/
class ExtractingEventDispatcher extends EventDispatcher implements EventSubscriberInterface
{
public $listeners = [];
public static $subscriber;
public function addListener($eventName, $listener, $priority = 0)
{
$this->listeners[] = [$eventName, $listener[1], $priority];
}
public static function getSubscribedEvents()
{
$callback = [self::$subscriber, 'getSubscribedEvents'];
return $callback();
}
}

View File

@@ -32,16 +32,6 @@ class Event
*/
private $propagationStopped = false;
/**
* @var EventDispatcherInterface Dispatcher that dispatched this event
*/
private $dispatcher;
/**
* @var string This event's name
*/
private $name;
/**
* Returns whether further event listeners should be triggered.
*
@@ -65,56 +55,4 @@ class Event
{
$this->propagationStopped = true;
}
/**
* Stores the EventDispatcher that dispatches this Event.
*
* @param EventDispatcherInterface $dispatcher
*
* @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*/
public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Returns the EventDispatcher that dispatches this Event.
*
* @return EventDispatcherInterface
*
* @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call.
*/
public function getDispatcher()
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event dispatcher instance can be received in the listener call instead.', E_USER_DEPRECATED);
return $this->dispatcher;
}
/**
* Gets the event's name.
*
* @return string
*
* @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call.
*/
public function getName()
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event name can be received in the listener call instead.', E_USER_DEPRECATED);
return $this->name;
}
/**
* Sets the event's name property.
*
* @param string $name The event name
*
* @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call.
*/
public function setName($name)
{
$this->name = $name;
}
}

View File

@@ -24,11 +24,12 @@ namespace Symfony\Component\EventDispatcher;
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Jordan Alliot <jordan.alliot@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class EventDispatcher implements EventDispatcherInterface
{
private $listeners = array();
private $sorted = array();
private $listeners = [];
private $sorted = [];
/**
* {@inheritdoc}
@@ -39,9 +40,6 @@ class EventDispatcher implements EventDispatcherInterface
$event = new Event();
}
$event->setDispatcher($this);
$event->setName($eventName);
if ($listeners = $this->getListeners($eventName)) {
$this->doDispatch($listeners, $eventName, $event);
}
@@ -55,8 +53,8 @@ class EventDispatcher implements EventDispatcherInterface
public function getListeners($eventName = null)
{
if (null !== $eventName) {
if (!isset($this->listeners[$eventName])) {
return array();
if (empty($this->listeners[$eventName])) {
return [];
}
if (!isset($this->sorted[$eventName])) {
@@ -76,26 +74,31 @@ class EventDispatcher implements EventDispatcherInterface
}
/**
* 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
* {@inheritdoc}
*/
public function getListenerPriority($eventName, $listener)
{
if (!isset($this->listeners[$eventName])) {
return;
if (empty($this->listeners[$eventName])) {
return null;
}
if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) {
$listener[0] = $listener[0]();
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
if (false !== \in_array($listener, $listeners, true)) {
return $priority;
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;
}
}
}
return null;
}
/**
@@ -103,7 +106,17 @@ class EventDispatcher implements EventDispatcherInterface
*/
public function hasListeners($eventName = null)
{
return (bool) $this->getListeners($eventName);
if (null !== $eventName) {
return !empty($this->listeners[$eventName]);
}
foreach ($this->listeners as $eventListeners) {
if ($eventListeners) {
return true;
}
}
return false;
}
/**
@@ -120,13 +133,30 @@ class EventDispatcher implements EventDispatcherInterface
*/
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]);
}
}
}
@@ -138,12 +168,12 @@ class EventDispatcher implements EventDispatcherInterface
{
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$this->addListener($eventName, array($subscriber, $params));
$this->addListener($eventName, [$subscriber, $params]);
} elseif (\is_string($params[0])) {
$this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
$this->addListener($eventName, [$subscriber, $params[0]], isset($params[1]) ? $params[1] : 0);
} else {
foreach ($params as $listener) {
$this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
$this->addListener($eventName, [$subscriber, $listener[0]], isset($listener[1]) ? $listener[1] : 0);
}
}
}
@@ -157,10 +187,10 @@ class EventDispatcher implements EventDispatcherInterface
foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
if (\is_array($params) && \is_array($params[0])) {
foreach ($params as $listener) {
$this->removeListener($eventName, array($subscriber, $listener[0]));
$this->removeListener($eventName, [$subscriber, $listener[0]]);
}
} else {
$this->removeListener($eventName, array($subscriber, \is_string($params) ? $params : $params[0]));
$this->removeListener($eventName, [$subscriber, \is_string($params) ? $params : $params[0]]);
}
}
}
@@ -193,6 +223,16 @@ class EventDispatcher implements EventDispatcherInterface
private function sortListeners($eventName)
{
krsort($this->listeners[$eventName]);
$this->sorted[$eventName] = \call_user_func_array('array_merge', $this->listeners[$eventName]);
$this->sorted[$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

@@ -23,11 +23,11 @@ interface EventDispatcherInterface
/**
* Dispatches an event to all registered listeners.
*
* @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
* If not supplied, an empty Event instance is created
* @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|null $event The event to pass to the event handlers/listeners
* If not supplied, an empty Event instance is created
*
* @return Event
*/
@@ -46,7 +46,7 @@ interface EventDispatcherInterface
/**
* Adds an event subscriber.
*
* The subscriber is asked for all the events he is
* The subscriber is asked for all the events it is
* interested in and added as a listener for these events.
*/
public function addSubscriber(EventSubscriberInterface $subscriber);
@@ -64,16 +64,28 @@ interface EventDispatcherInterface
/**
* Gets the listeners of a specific event or all listeners sorted by descending priority.
*
* @param string $eventName The name of the event
* @param string|null $eventName The name of the event
*
* @return array The event listeners for the specified event, or all event listeners by event name
*/
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.
*
* @param string $eventName The name of the event
* @param string|null $eventName The name of the event
*
* @return bool true if the specified event has any listeners, false otherwise
*/

View File

@@ -12,7 +12,7 @@
namespace Symfony\Component\EventDispatcher;
/**
* An EventSubscriber knows himself what events he is interested in.
* An EventSubscriber knows itself what events it is interested in.
* If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes
* {@link getSubscribedEvents} and registers the subscriber as a listener for all
* returned events.
@@ -36,9 +36,9 @@ interface EventSubscriberInterface
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* @return array The event names to listen to
*/

View File

@@ -29,7 +29,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
* @param mixed $subject The subject of the event, usually an object or a callable
* @param array $arguments Arguments to store in the event
*/
public function __construct($subject = null, array $arguments = array())
public function __construct($subject = null, array $arguments = [])
{
$this->subject = $subject;
$this->arguments = $arguments;
@@ -95,7 +95,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
*
* @return $this
*/
public function setArguments(array $args = array())
public function setArguments(array $args = [])
{
$this->arguments = $args;
@@ -111,7 +111,7 @@ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate
*/
public function hasArgument($key)
{
return array_key_exists($key, $this->arguments);
return \array_key_exists($key, $this->arguments);
}
/**

View File

@@ -1,4 +1,4 @@
Copyright (c) 2004-2018 Fabien Potencier
Copyright (c) 2004-2019 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

@@ -16,15 +16,18 @@
}
],
"require": {
"php": ">=5.3.9"
"php": "^5.5.9|>=7.0.8"
},
"require-dev": {
"symfony/dependency-injection": "~2.6|~3.0.0",
"symfony/expression-language": "~2.6|~3.0.0",
"symfony/config": "^2.0.5|~3.0.0",
"symfony/stopwatch": "~2.3|~3.0.0",
"symfony/dependency-injection": "~3.3|~4.0",
"symfony/expression-language": "~2.8|~3.0|~4.0",
"symfony/config": "~2.8|~3.0|~4.0",
"symfony/stopwatch": "~2.8|~3.0|~4.0",
"psr/log": "~1.0"
},
"conflict": {
"symfony/dependency-injection": "<3.3"
},
"suggest": {
"symfony/dependency-injection": "",
"symfony/http-kernel": ""
@@ -38,7 +41,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "2.8-dev"
"dev-master": "3.4-dev"
}
}
}