Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[EventDispatcher] Freeze events #34988

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public function getConfigTreeBuilder()
->scalarNode('error_controller')
->defaultValue('error_controller')
->end()
->booleanNode('freeze_kernel_events')->defaultValue(false)->end()
->end()
;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Lock\Lock;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\LockInterface;
Expand Down Expand Up @@ -223,6 +224,19 @@ public function load(array $configs, ContainerBuilder $container)
$container->setParameter('kernel.trusted_hosts', $config['trusted_hosts']);
$container->setParameter('kernel.default_locale', $config['default_locale']);
$container->setParameter('kernel.error_controller', $config['error_controller']);
$container->setParameter(
'event_dispatcher.freeze_events',
$config['freeze_kernel_events'] ? [
KernelEvents::REQUEST,
KernelEvents::EXCEPTION,
KernelEvents::VIEW,
KernelEvents::CONTROLLER,
KernelEvents::CONTROLLER_ARGUMENTS,
KernelEvents::RESPONSE,
KernelEvents::TERMINATE,
KernelEvents::FINISH_REQUEST,
] : []
);

if (!$container->hasParameter('debug.file_link_format')) {
$links = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<xsd:attribute name="default-locale" type="xsd:string" />
<xsd:attribute name="test" type="xsd:boolean" />
<xsd:attribute name="error-controller" type="xsd:string" />
<xsd:attribute name="freeze-kernel-events" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="form">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'notification_on_failed_messages' => false,
],
'error_controller' => 'error_controller',
'freeze_kernel_events' => false,
'secrets' => [
'enabled' => true,
'vault_directory' => '%kernel.project_dir%/config/secrets/%kernel.environment%',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

$container->loadFromExtension('framework', [
'freeze_kernel_events' => true,
]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config freeze-kernel-events="true" />
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
framework:
freeze_kernel_events: true
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Component\HttpKernel\DependencyInjection\LoggerPass;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Messenger\Transport\TransportFactory;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
Expand Down Expand Up @@ -1384,6 +1385,32 @@ public function testMailerWithSpecificMessageBus(): void
$this->assertEquals(new Reference('app.another_bus'), $container->getDefinition('mailer.mailer')->getArgument(1));
}

public function testFreezeKernelEvents(): void
{
$container = $this->createContainerFromFile('freeze_events');

$this->assertSame(
[
KernelEvents::REQUEST,
KernelEvents::EXCEPTION,
KernelEvents::VIEW,
KernelEvents::CONTROLLER,
KernelEvents::CONTROLLER_ARGUMENTS,
KernelEvents::RESPONSE,
KernelEvents::TERMINATE,
KernelEvents::FINISH_REQUEST,
],
$container->getParameter('event_dispatcher.freeze_events')
);
}

public function testDontFreezeKernelEventsByDefault(): void
{
$container = $this->createContainerFromFile('full');

$this->assertSame([], $container->getParameter('event_dispatcher.freeze_events'));
}

protected function createContainer(array $data = [])
{
return new ContainerBuilder(new EnvPlaceholderParameterBag(array_merge([
Expand Down
1 change: 1 addition & 0 deletions 1 src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"symfony/console": "<4.4",
"symfony/dotenv": "<4.4",
"symfony/dom-crawler": "<4.4",
"symfony/event-dispatcher": "<5.1",
"symfony/http-client": "<4.4",
"symfony/form": "<4.4",
"symfony/lock": "<4.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@

namespace Symfony\Component\EventDispatcher\Debug;

use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\EventDispatcher\ListenerProviderAwareInterface;
use Symfony\Contracts\Service\ResetInterface;

/**
Expand All @@ -27,7 +29,7 @@
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TraceableEventDispatcher implements EventDispatcherInterface, ResetInterface
class TraceableEventDispatcher implements EventDispatcherInterface, ListenerProviderAwareInterface, ResetInterface
{
protected $logger;
protected $stopwatch;
Expand All @@ -47,6 +49,10 @@ public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $sto
$this->wrappedListeners = [];
$this->orphanedEvents = [];
$this->requestStack = $requestStack;

if (!$dispatcher instanceof ListenerProviderAwareInterface) {
@trigger_error(sprintf('Implementing %s without %s is deprecated since Symfony 5.1.', EventDispatcherInterface::class, ListenerProviderAwareInterface::class), E_USER_DEPRECATED);
}
}

/**
Expand Down Expand Up @@ -91,6 +97,14 @@ public function removeSubscriber(EventSubscriberInterface $subscriber)
return $this->dispatcher->removeSubscriber($subscriber);
}

/**
* {@inheritdoc}
*/
public function setListenerProvider(string $eventName, ListenerProviderInterface $listenerProvider): void
{
$this->dispatcher->setListenerProvider($eventName, $listenerProvider);
}

/**
* {@inheritdoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\Event as LegacyEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\ListenerProvider\LazyListenerProvider;
use Symfony\Component\EventDispatcher\ListenerProvider\SimpleListenerProvider;
use Symfony\Contracts\EventDispatcher\Event;

/**
Expand All @@ -30,16 +33,18 @@ class RegisterListenersPass implements CompilerPassInterface
protected $listenerTag;
protected $subscriberTag;
protected $eventAliasesParameter;
protected $freezeEventsParameter;

private $hotPathEvents = [];
private $hotPathTagName;

public function __construct(string $dispatcherService = 'event_dispatcher', string $listenerTag = 'kernel.event_listener', string $subscriberTag = 'kernel.event_subscriber', string $eventAliasesParameter = 'event_dispatcher.event_aliases')
public function __construct(string $dispatcherService = 'event_dispatcher', string $listenerTag = 'kernel.event_listener', string $subscriberTag = 'kernel.event_subscriber', string $eventAliasesParameter = 'event_dispatcher.event_aliases', string $freezeEventsParameter = 'event_dispatcher.freeze_events')
{
$this->dispatcherService = $dispatcherService;
$this->listenerTag = $listenerTag;
$this->subscriberTag = $subscriberTag;
$this->eventAliasesParameter = $eventAliasesParameter;
$this->freezeEventsParameter = $freezeEventsParameter;
}

public function setHotPathEvents(array $hotPathEvents, $tagName = 'container.hot_path')
Expand All @@ -64,6 +69,13 @@ public function process(ContainerBuilder $container)
}
$definition = $container->findDefinition($this->dispatcherService);

$frozenEvents = [];
if ($container->hasParameter($this->freezeEventsParameter)) {
foreach ($container->getParameter($this->freezeEventsParameter) as $event) {
$frozenEvents[$event] = [];
}
}

foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;
Expand Down Expand Up @@ -91,7 +103,11 @@ public function process(ContainerBuilder $container)
}
}

$definition->addMethodCall('addListener', [$event['event'], [new ServiceClosureArgument(new Reference($id)), $event['method']], $priority]);
if (isset($frozenEvents[$event['event']])) {
$frozenEvents[$event['event']][$priority][] = [new Reference($id), $event['method']];
} else {
$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);
Expand Down Expand Up @@ -119,8 +135,12 @@ public function process(ContainerBuilder $container)
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($frozenEvents[$args[0]])) {
$frozenEvents[$args[0]][$args[2]][] = [new Reference($id), $args[1]];
} else {
$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);
Expand All @@ -129,6 +149,15 @@ public function process(ContainerBuilder $container)
$extractingDispatcher->listeners = [];
ExtractingEventDispatcher::$aliases = [];
}

foreach ($frozenEvents as $event => $listeners) {
krsort($listeners, SORT_NUMERIC);
$providerId = sprintf('__%s.listener_provider.%s', $this->dispatcherService, $event);
$container->register($providerId, SimpleListenerProvider::class)
->setArguments([array_merge(...array_values($listeners))]);

$definition->addMethodCall('setListenerProvider', [$event, new Definition(LazyListenerProvider::class, [new ServiceClosureArgument(new Reference($providerId))])]);
}
}

private function getEventFromTypeDeclaration(ContainerBuilder $container, string $id, string $method): string
Expand Down
33 changes: 31 additions & 2 deletions 33 src/Symfony/Component/EventDispatcher/EventDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

namespace Symfony\Component\EventDispatcher;

use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;
use Symfony\Component\EventDispatcher\Debug\WrappedListener;
use Symfony\Component\EventDispatcher\Exception\RuntimeException;
use Symfony\Contracts\EventDispatcher\ListenerProviderAwareInterface;

/**
* The EventDispatcherInterface is the central point of Symfony's event listener system.
Expand All @@ -29,11 +32,15 @@
* @author Jordan Alliot <jordan.alliot@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class EventDispatcher implements EventDispatcherInterface
class EventDispatcher implements EventDispatcherInterface, ListenerProviderAwareInterface
{
private $listeners = [];
private $sorted = [];
private $optimized;
/**
* @var ListenerProviderInterface[]
*/
private $listenerProviders = [];

public function __construct()
{
Expand All @@ -49,7 +56,9 @@ public function dispatch(object $event, string $eventName = null): object
{
$eventName = $eventName ?? \get_class($event);

if (null !== $this->optimized && null !== $eventName) {
if (isset($this->listenerProviders[$eventName])) {
$listeners = $this->listenerProviders[$eventName]->getListenersForEvent($event);
} elseif (null !== $this->optimized && null !== $eventName) {
$listeners = $this->optimized[$eventName] ?? (empty($this->listeners[$eventName]) ? [] : $this->optimizeListeners($eventName));
} else {
$listeners = $this->getListeners($eventName);
Expand Down Expand Up @@ -140,6 +149,10 @@ public function hasListeners(string $eventName = null)
*/
public function addListener(string $eventName, $listener, int $priority = 0)
{
if (isset($this->listenerProviders[$eventName])) {
throw new RuntimeException(sprintf('The "%s" event is frozen. You cannot attache listeners to it.', $eventName));
}

$this->listeners[$eventName][$priority][] = $listener;
unset($this->sorted[$eventName], $this->optimized[$eventName]);
}
Expand All @@ -149,6 +162,10 @@ public function addListener(string $eventName, $listener, int $priority = 0)
*/
public function removeListener(string $eventName, $listener)
{
if (isset($this->listenerProviders[$eventName])) {
throw new RuntimeException(sprintf('The "%s" event is frozen. You cannot remove listeners from it.', $eventName));
}

if (empty($this->listeners[$eventName])) {
return;
}
Expand Down Expand Up @@ -209,6 +226,18 @@ public function removeSubscriber(EventSubscriberInterface $subscriber)
}
}

/**
* {@inheritdoc}
*/
public function setListenerProvider(string $eventName, ListenerProviderInterface $listenerProvider): void
{
if (isset($this->listeners[$eventName])) {
throw new RuntimeException(sprintf('There are already listeners attached to the "%s" event. You cannot set a listener provider for it.', $eventName));
}

$this->listenerProviders[$eventName] = $listenerProvider;
}

/**
* Triggers the listeners of an event.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

interface ExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

final class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.