8000 [FrameworkBundle][HttpKernel] Configure `ErrorHandler` on boot by HypeMC · Pull Request #49275 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[FrameworkBundle][HttpKernel] Configure ErrorHandler on boot #49275

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

Merged
merged 1 commit into from
Feb 21, 2023
Merged
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
[FrameworkBundle][HttpKernel] Configure ErrorHandler on boot
  • Loading branch information
HypeMC committed Feb 21, 2023
commit 26e6a56694293b9332b19b86dea177557fc548b3
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ CHANGELOG
* Deprecate the `notifier.logger_notification_listener` service, use the `notifier.notification_logger_listener` service instead
* Allow setting private services with the test container
* Register alias for argument for workflow services with workflow name only
* Configure the `ErrorHandler` on `FrameworkBundle::boot()`

6.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1095,12 +1095,12 @@ private function registerDebugConfiguration(array $config, ContainerBuilder $con
$loader->load('debug.php');
}

$definition = $container->findDefinition('debug.debug_handlers_listener');
$definition = $container->findDefinition('debug.error_handler_configurator');

if (false === $config['log']) {
$definition->replaceArgument(1, null);
$definition->replaceArgument(0, null);
} elseif (true !== $config['log']) {
$definition->replaceArgument(2, $config['log']);
$definition->replaceArgument(1, $config['log']);
}

if (!$config['throw']) {
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ class FrameworkBundle extends Bundle
*/
public function boot()
{
ErrorHandler::register(null, false)->throwAt($this->container->getParameter('debug.error_handler.throw_at'), true);
$handler = ErrorHandler::register(null, false);
$this->container->get('debug.error_handler_configurator')->configure($handler);

if ($this->container->getParameter('kernel.http_method_override')) {
Request::enableHttpMethodParameterOverride();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,29 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\HttpKernel\Debug\ErrorHandlerConfigurator;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;

return static function (ContainerConfigurator $container) {
$container->parameters()->set('debug.error_handler.throw_at', -1);

$container->services()
->set('debug.debug_handlers_listener', DebugHandlersListener::class)
->set('debug.error_handler_configurator', ErrorHandlerConfigurator::class)
->public()
->args([
null, // Exception handler
service('monolog.logger.php')->nullOnInvalid(),
null, // Log levels map for enabled error levels
param('debug.error_handler.throw_at'),
param('kernel.debug'),
param('kernel.debug'),
service('monolog.logger.deprecation')->nullOnInvalid(),
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'php'])

->set('debug.debug_handlers_listener', DebugHandlersListener::class)
->tag('kernel.event_subscriber')

->set('debug.file_link_formatter', FileLinkFormatter::class)
->args([param('debug.file_link_format')])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -541,41 +541,41 @@ public function testEnabledPhpErrorsConfig()
{
$container = $this->createContainerFromFile('php_errors_enabled');

$definition = $container->getDefinition('debug.debug_handlers_listener');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(1));
$this->assertNull($definition->getArgument(2));
$definition = $container->getDefinition('debug.error_handler_configurator');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(0));
$this->assertNull($definition->getArgument(1));
$this->assertSame(-1, $container->getParameter('debug.error_handler.throw_at'));
}

public function testDisabledPhpErrorsConfig()
{
$container = $this->createContainerFromFile('php_errors_disabled');

$definition = $container->getDefinition('debug.debug_handlers_listener');
$definition = $container->getDefinition('debug.error_handler_configurator');
$this->assertNull($definition->getArgument(0));
$this->assertNull($definition->getArgument(1));
$this->assertNull($definition->getArgument(2));
$this->assertSame(0, $container->getParameter('debug.error_handler.throw_at'));
}

public function testPhpErrorsWithLogLevel()
{
$container = $this->createContainerFromFile('php_errors_log_level');

$definition = $container->getDefinition('debug.debug_handlers_listener');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(1));
$this->assertSame(8, $definition->getArgument(2));
$definition = $container->getDefinition('debug.error_handler_configurator');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(0));
$this->assertSame(8, $definition->getArgument(1));
}

public function testPhpErrorsWithLogLevels()
{
$container = $this->createContainerFromFile('php_errors_log_levels');

$definition = $container->getDefinition('debug.debug_handlers_listener');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(1));
$definition = $container->getDefinition('debug.error_handler_configurator');
$this->assertEquals(new Reference('monolog.logger.php', ContainerInterface::NULL_ON_INVALID_REFERENCE), $definition->getArgument(0));
$this->assertSame([
\E_NOTICE => \Psr\Log\LogLevel::ERROR,
\E_WARNING => \Psr\Log\LogLevel::ERROR,
], $definition->getArgument(2));
], $definition->getArgument(1));
}

public function testExceptionsConfig()
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"symfony/error-handler": "^6.1",
"symfony/event-dispatcher": "^5.4|^ F438 6.0",
"symfony/http-foundation": "^6.2",
"symfony/http-kernel": "^6.2.1",
"symfony/http-kernel": "^6.3",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "^5.4|^6.0",
"symfony/finder": "^5.4|^6.0",
Expand Down
107 changes: 107 additions & 0 deletions src/Symfony/Component/HttpKernel/Debug/ErrorHandlerConfigurator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?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\HttpKernel\Debug;

use Psr\Log\LoggerInterface;
use Symfony\Component\ErrorHandler\ErrorHandler;

/**
* Configures the error handler.
*
* @final
*
* @internal
*/
class ErrorHandlerConfigurator
{
private ?LoggerInterface $logger;
private ?LoggerInterface $deprecationLogger;
private array|int|null $levels;
private ?int $throwAt;
private bool $scream;
private bool $scope;

/**
* @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value
* @param bool $scream Enables/disables screaming mode, where even silenced errors are logged
* @param bool $scope Enables/disables scoping mode
*/
public function __construct(LoggerInterface $logger = null, array|int|null $levels = \E_ALL, ?int $throwAt = \E_ALL, bool $scream = true, bool $scope = true, LoggerInterface $deprecationLogger = null)
{
$this->logger = $logger;
$this->levels = $levels ?? \E_ALL;
$this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null));
$this->scream = $scream;
$this->scope = $scope;
$this->deprecationLogger = $deprecationLogger;
}

/**
* Configures the error handler.
*/
public function configure(ErrorHandler $handler): void
{
if ($this->logger || $this->deprecationLogger) {
$this->setDefaultLoggers($handler);
if (\is_array($this->levels)) {
$levels = 0;
foreach ($this->levels as $type => $log) {
$levels |= $type;
}
} else {
$levels = $this->levels;
}

if ($this->scream) {
$handler->screamAt($levels);
}
if ($this->scope) {
$handler->scopeAt($levels & ~\E_USER_DEPRECATED & ~\E_DEPRECATED);
} else {
$handler->scopeAt(0, true);
}
$this->logger = $this->deprecationLogger = $this->levels = null;
}
if (null !== $this->throwAt) {
$handler->throwAt($this->throwAt, true);
}
}

private function setDefaultLoggers(ErrorHandler $handler): void
{
if (\is_array($this->levels)) {
$levelsDeprecatedOnly = [];
$levelsWithoutDeprecated = [];
foreach ($this->levels as $type => $log) {
if (\E_DEPRECATED == $type || \E_USER_DEPRECATED == $type) {
$levelsDeprecatedOnly[$type] = $log;
} else {
$levelsWithoutDeprecated[$type] = $log;
}
}
} else {
$levelsDeprecatedOnly = $this->levels & (\E_DEPRECATED | \E_USER_DEPRECATED);
$levelsWithoutDeprecated = $this->levels & ~\E_DEPRECATED & ~\E_USER_DEPRECATED;
}

$defaultLoggerLevels = $this->levels;
if ($this->deprecationLogger && $levelsDeprecatedOnly) {
$handler->setDefaultLogger($this->deprecationLogger, $levelsDeprecatedOnly);
$defaultLoggerLevels = $levelsWithoutDeprecated;
}

if ($this->logger && $defaultLoggerLevels) {
$handler->setDefaultLogger($this->logger, $defaultLoggerLevels);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

namespace Symfony\Component\HttpKernel\EventListener;

use Psr\Log\LoggerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
Expand All @@ -21,7 +20,7 @@
use Symfony\Component\HttpKernel\KernelEvents;

/**
* Configures errors and exceptions handlers.
* Sets an exception handler.
*
* @author Nicolas Grekas <p@tchwork.com>
*
Expand All @@ -33,35 +32,19 @@ class DebugHandlersListener implements EventSubscriberInterface
{
private string|object|null $earlyHandler;
private ?\Closure $exceptionHandler;
private ?LoggerInterface $logger;
private ?LoggerInterface $deprecationLogger;
private array|int|null $levels;
private ?int $throwAt;
private bool $scream;
private bool $scope;
private bool $firstCall = true;
private bool $hasTerminatedWithException = false;

/**
* @param callable|null $exceptionHandler A handler that must support \Throwable instances that will be called on Exception
* @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value
* @param bool $scream Enables/disables screaming mode, where even silenced errors are logged
* @param bool $scope Enables/disables scoping mode
* @param callable|null $exceptionHandler A handler that must support \Throwable instances that will be called on Exception
*/
public function __construct(callable $exceptionHandler = null, LoggerInterface $logger = null, array|int|null $levels = \E_ALL, ?int $throwAt = \E_ALL, bool $scream = true, bool $scope = true, LoggerInterface $deprecationLogger = null)
public function __construct(callable $exceptionHandler = null)
{
$handler = set_exception_handler('is_int');
$this->earlyHandler = \is_array($handler) ? $handler[0] : null;
restore_exception_handler();

$this->exceptionHandler = null === $exceptionHandler ? null : $exceptionHandler(...);
$this->logger = $logger;
$this->levels = $levels ?? \E_ALL;
$this->throwAt = \is_int($throwAt) ? $throwAt : (null === $throwAt ? null : ($throwAt ? \E_ALL : null));
$this->scream = $scream;
$this->scope = $scope;
$this->deprecationLogger = $deprecationLogger;
}

/**
Expand All @@ -77,40 +60,6 @@ public function configure(object $event = null): void
}
$this->firstCall = $this->hasTerminatedWithException = false;

$handler = set_exception_handler('is_int');
$handler = \is_array($handler) ? $handler[0] : null;
restore_exception_handler();

if (!$handler instanceof ErrorHandler) {
$handler = $this->earlyHandler;
}

if ($handler instanceof ErrorHandler) {
if ($this->logger || $this->deprecationLogger) {
$this->setDefaultLoggers($handler);
if (\is_array($this->levels)) {
$levels = 0;
foreach ($this->levels as $type => $log) {
$levels |= $type;
}
} else {
$levels = $this->levels;
}

if ($this->scream) {
$handler->screamAt($levels);
}
if ($this->scope) {
$handler->scopeAt($levels & ~\E_USER_DEPRECATED & ~\E_DEPRECATED);
} else {
$handler->scopeAt(0, true);
}
$this->logger = $this->deprecationLogger = $this->levels = null;
}
if (null !== $this->throwAt) {
$handler->throwAt($this->throwAt, true);
}
}
if (!$this->exceptionHandler) {
if ($event instanceof KernelEvent) {
if (method_exists($kernel = $event->getKernel(), 'terminateWithException')) {
Expand All @@ -136,41 +85,21 @@ public function configure(object $event = null): void
}
}
if ($this->exceptionHandler) {
$handler = set_exception_handler('is_int');
$handler = \is_array($handler) ? $handler[0] : null;
restore_exception_handler();

if (!$handler instanceof ErrorHandler) {
$handler = $this->earlyHandler;
}

if ($handler instanceof ErrorHandler) {
$handler->setExceptionHandler($this->exceptionHandler);
}
$this->exceptionHandler = null;
}
}

private function setDefaultLoggers(ErrorHandler $handler): void
{
if (\is_array($this->levels)) {
$levelsDeprecatedOnly = [];
$levelsWithoutDeprecated = [];
foreach ($this->levels as $type => $log) {
if (\E_DEPRECATED == $type || \E_USER_DEPRECATED == $type) {
$levelsDeprecatedOnly[$type] = $log;
} else {
$levelsWithoutDeprecated[$type] = $log;
}
}
} else {
$levelsDeprecatedOnly = $this->levels & (\E_DEPRECATED | \E_USER_DEPRECATED);
$levelsWithoutDeprecated = $this->levels & ~\E_DEPRECATED & ~\E_USER_DEPRECATED;
}

$defaultLoggerLevels = $this->levels;
if ($this->deprecationLogger && $levelsDeprecatedOnly) {
$handler->setDefaultLogger($this->deprecationLogger, $levelsDeprecatedOnly);
$defaultLoggerLevels = $levelsWithoutDeprecated;
}

if ($this->logger && $defaultLoggerLevels) {
$handler->setDefaultLogger($this->logger, $defaultLoggerLevels);
}
}

public static function getSubscribedEvents(): array
{
$events = [KernelEvents::REQUEST => ['configure', 2048]];
Expand Down
Loading
0