This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Debug/ErrorHandler.php

895 lines
33 KiB
PHP
Raw Normal View History

<?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\Debug;
use Psr\Log\LoggerInterface;
2018-07-26 10:03:18 +01:00
use Psr\Log\LogLevel;
use Symfony\Component\Debug\Exception\ContextErrorException;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
2013-07-24 06:23:37 +01:00
use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
2018-07-26 10:03:18 +01:00
use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
/**
2014-05-26 11:29:25 +01:00
* A generic ErrorHandler for the PHP engine.
*
* Provides five bit fields that control how errors are handled:
* - thrownErrors: errors thrown as \ErrorException
* - loggedErrors: logged errors, when not @-silenced
* - scopedErrors: errors thrown or logged with their local context
* - tracedErrors: errors logged with their stack trace, only once for repeated errors
* - screamedErrors: never @-silenced errors
*
* Each error level can be logged by a dedicated PSR-3 logger object.
* Screaming only applies to logging.
* Throwing takes precedence over logging.
* Uncaught exceptions are logged as E_ERROR.
* E_DEPRECATED and E_USER_DEPRECATED levels never throw.
* E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
* Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
* As errors have a performance cost, repeated errors are all logged, so that the developer
* can see them and weight them as more important to fix than others of the same level.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class ErrorHandler
{
2014-05-26 11:29:25 +01:00
/**
* @deprecated since version 2.6, to be removed in 3.0.
2014-05-26 11:29:25 +01:00
*/
const TYPE_DEPRECATION = -100;
private $levels = array(
Merge branch '2.5' * 2.5: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.5.7 updated VERSION for 2.5.6 updated CHANGELOG for 2.5.6 bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/Debug/ExceptionHandler.php src/Symfony/Component/Form/Extension/Core/Type/BaseType.php src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php src/Symfony/Component/Form/Extension/Core/Type/DateTimeType.php src/Symfony/Component/Form/Extension/Core/Type/DateType.php src/Symfony/Component/Form/Extension/Core/Type/TimeType.php src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php src/Symfony/Component/HttpFoundation/Request.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/Security/Core/SecurityContextInterface.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php src/Symfony/Component/Serializer/Serializer.php src/Symfony/Component/Validator/Constraints/File.php
2014-10-26 07:46:28 +00:00
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User Deprecated',
2014-10-22 19:27:13 +01:00
E_NOTICE => 'Notice',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
Merge branch '2.5' * 2.5: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.5.7 updated VERSION for 2.5.6 updated CHANGELOG for 2.5.6 bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/Debug/ExceptionHandler.php src/Symfony/Component/Form/Extension/Core/Type/BaseType.php src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php src/Symfony/Component/Form/Extension/Core/Type/DateTimeType.php src/Symfony/Component/Form/Extension/Core/Type/DateType.php src/Symfony/Component/Form/Extension/Core/Type/TimeType.php src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php src/Symfony/Component/HttpFoundation/Request.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/Security/Core/SecurityContextInterface.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php src/Symfony/Component/Serializer/Serializer.php src/Symfony/Component/Validator/Constraints/File.php
2014-10-26 07:46:28 +00:00
E_WARNING => 'Warning',
E_USER_WARNING => 'User Warning',
E_COMPILE_WARNING => 'Compile Warning',
E_CORE_WARNING => 'Core Warning',
E_USER_ERROR => 'User Error',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
2014-10-22 19:27:13 +01:00
E_COMPILE_ERROR => 'Compile Error',
Merge branch '2.3' into 2.5 * 2.3: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bridge/Propel1/Form/ChoiceList/ModelChoiceList.php src/Symfony/Bridge/Propel1/Form/Type/ModelType.php src/Symfony/Bridge/Propel1/Logger/PropelLogger.php src/Symfony/Bridge/Propel1/Tests/Fixtures/ItemQuery.php src/Symfony/Bundle/FrameworkBundle/Command/RouterDebugCommand.php src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/FormLoginBundle/Controller/LocalizedController.php src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/FormLoginBundle/Controller/LoginController.php src/Symfony/Component/Console/Descriptor/JsonDescriptor.php src/Symfony/Component/Console/Formatter/OutputFormatterStyle.php src/Symfony/Component/Console/Helper/ProgressHelper.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/DependencyInjection/Container.php src/Symfony/Component/Finder/Shell/Command.php src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php src/Symfony/Component/Form/Extension/Core/Type/CollectionType.php src/Symfony/Component/Form/Extension/Core/Type/FormType.php src/Symfony/Component/Form/Extension/Core/Type/IntegerType.php src/Symfony/Component/Form/Extension/Core/Type/NumberType.php src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php src/Symfony/Component/HttpFoundation/File/UploadedFile.php src/Symfony/Component/HttpKernel/DataCollector/LoggerDataCollector.php src/Symfony/Component/HttpKernel/Debug/TraceableEventDispatcher.php src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.php src/Symfony/Component/HttpKernel/Tests/HttpCache/TestMultipleHttpKernel.php src/Symfony/Component/Intl/NumberFormatter/NumberFormatter.php src/Symfony/Component/Routing/Loader/AnnotationClassLoader.php src/Symfony/Component/Routing/Route.php src/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php src/Symfony/Component/Security/Tests/Core/Validator/Constraints/UserPasswordValidatorTest.php src/Symfony/Component/Templating/PhpEngine.php src/Symfony/Component/Validator/Constraints/ImageValidator.php src/Symfony/Component/Validator/Constraints/TypeValidator.php
2014-10-26 07:41:27 +00:00
E_PARSE => 'Parse Error',
Merge branch '2.5' * 2.5: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.5.7 updated VERSION for 2.5.6 updated CHANGELOG for 2.5.6 bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/Debug/ExceptionHandler.php src/Symfony/Component/Form/Extension/Core/Type/BaseType.php src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php src/Symfony/Component/Form/Extension/Core/Type/DateTimeType.php src/Symfony/Component/Form/Extension/Core/Type/DateType.php src/Symfony/Component/Form/Extension/Core/Type/TimeType.php src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php src/Symfony/Component/HttpFoundation/Request.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/Security/Core/SecurityContextInterface.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php src/Symfony/Component/Serializer/Serializer.php src/Symfony/Component/Validator/Constraints/File.php
2014-10-26 07:46:28 +00:00
E_ERROR => 'Error',
E_CORE_ERROR => 'Core Error',
);
2014-05-26 11:29:25 +01:00
private $loggers = array(
Merge branch '2.5' * 2.5: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.5.7 updated VERSION for 2.5.6 updated CHANGELOG for 2.5.6 bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/Debug/ExceptionHandler.php src/Symfony/Component/Form/Extension/Core/Type/BaseType.php src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php src/Symfony/Component/Form/Extension/Core/Type/DateTimeType.php src/Symfony/Component/Form/Extension/Core/Type/DateType.php src/Symfony/Component/Form/Extension/Core/Type/TimeType.php src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php src/Symfony/Component/HttpFoundation/Request.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/Security/Core/SecurityContextInterface.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php src/Symfony/Component/Serializer/Serializer.php src/Symfony/Component/Validator/Constraints/File.php
2014-10-26 07:46:28 +00:00
E_DEPRECATED => array(null, LogLevel::INFO),
E_USER_DEPRECATED => array(null, LogLevel::INFO),
E_NOTICE => array(null, LogLevel::WARNING),
E_USER_NOTICE => array(null, LogLevel::WARNING),
E_STRICT => array(null, LogLevel::WARNING),
Merge branch '2.5' * 2.5: Remove aligned '=>' and '=' Break infinite loop while resolving aliases [Security][listener] change priority of switchuser Improved the phpdoc for security token classes bumped Symfony version to 2.5.7 updated VERSION for 2.5.6 updated CHANGELOG for 2.5.6 bumped Symfony version to 2.3.22 updated VERSION for 2.3.21 update CONTRIBUTORS for 2.3.21 updated CHANGELOG for 2.3.21 Conflicts: src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/Debug/ExceptionHandler.php src/Symfony/Component/Form/Extension/Core/Type/BaseType.php src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php src/Symfony/Component/Form/Extension/Core/Type/DateTimeType.php src/Symfony/Component/Form/Extension/Core/Type/DateType.php src/Symfony/Component/Form/Extension/Core/Type/TimeType.php src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php src/Symfony/Component/HttpFoundation/Request.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php src/Symfony/Component/HttpKernel/Kernel.php src/Symfony/Component/Security/Core/SecurityContextInterface.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationFailureHandler.php src/Symfony/Component/Security/Http/Authentication/DefaultAuthenticationSuccessHandler.php src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php src/Symfony/Component/Serializer/Serializer.php src/Symfony/Component/Validator/Constraints/File.php
2014-10-26 07:46:28 +00:00
E_WARNING => array(null, LogLevel::WARNING),
E_USER_WARNING => array(null, LogLevel::WARNING),
E_COMPILE_WARNING => array(null, LogLevel::WARNING),
E_CORE_WARNING => array(null, LogLevel::WARNING),
E_USER_ERROR => array(null, LogLevel::CRITICAL),
E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
E_PARSE => array(null, LogLevel::CRITICAL),
E_ERROR => array(null, LogLevel::CRITICAL),
E_CORE_ERROR => array(null, LogLevel::CRITICAL),
2014-05-26 11:29:25 +01:00
);
2014-05-26 11:29:25 +01:00
private $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
private $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
private $tracedErrors = 0x77FB; // E_ALL - E_STRICT - E_PARSE
private $screamedErrors = 0x55; // E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
private $loggedErrors = 0;
2014-05-26 11:29:25 +01:00
private $loggedTraces = array();
private $isRecursive = 0;
private $isRoot = false;
2014-05-26 11:29:25 +01:00
private $exceptionHandler;
private $bootstrappingLogger;
2014-05-26 11:29:25 +01:00
private static $reservedMemory;
private static $stackedErrors = array();
private static $stackedErrorLevels = array();
private static $toStringException = null;
private static $exitCode = 0;
2014-05-26 11:29:25 +01:00
/**
* Same init value as thrownErrors.
2014-05-26 11:29:25 +01:00
*
* @deprecated since version 2.6, to be removed in 3.0.
2014-05-26 11:29:25 +01:00
*/
private $displayErrors = 0x1FFF;
/**
* Registers the error handler.
*
* @param self|int|null $handler The handler to register, or @deprecated (since version 2.6, to be removed in 3.0) bit field of thrown levels
* @param bool $replace Whether to replace or not any existing handler
*
* @return self The registered error handler
*/
public static function register($handler = null, $replace = true)
{
2014-05-26 11:29:25 +01:00
if (null === self::$reservedMemory) {
self::$reservedMemory = str_repeat('x', 10240);
register_shutdown_function(__CLASS__.'::handleFatalError');
}
$levels = -1;
if ($handlerIsNew = !$handler instanceof self) {
// @deprecated polymorphism, to be removed in 3.0
if (null !== $handler) {
$levels = $replace ? $handler : 0;
$replace = true;
}
$handler = new static();
}
if (null === $prev = set_error_handler(array($handler, 'handleError'))) {
restore_error_handler();
// Specifying the error types earlier would expose us to https://bugs.php.net/63206
set_error_handler(array($handler, 'handleError'), $handler->thrownErrors | $handler->loggedErrors);
$handler->isRoot = true;
}
if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
$handler = $prev[0];
$replace = false;
}
if (!$replace && $prev) {
restore_error_handler();
$handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
} else {
$handlerIsRegistered = true;
}
if (\is_array($prev = set_exception_handler(array($handler, 'handleException'))) && $prev[0] instanceof self) {
restore_exception_handler();
if (!$handlerIsRegistered) {
$handler = $prev[0];
} elseif ($handler !== $prev[0] && $replace) {
set_exception_handler(array($handler, 'handleException'));
$p = $prev[0]->setExceptionHandler(null);
$handler->setExceptionHandler($p);
$prev[0]->setExceptionHandler($p);
}
} else {
$handler->setExceptionHandler($prev);
}
$handler->throwAt($levels & $handler->thrownErrors, true);
return $handler;
}
public function __construct(BufferingLogger $bootstrappingLogger = null)
{
if ($bootstrappingLogger) {
$this->bootstrappingLogger = $bootstrappingLogger;
$this->setDefaultLogger($bootstrappingLogger);
}
}
2013-07-24 06:23:37 +01:00
/**
2014-05-26 11:29:25 +01:00
* Sets a logger to non assigned errors levels.
2013-07-24 06:23:37 +01:00
*
2014-05-26 11:29:25 +01:00
* @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
* @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param bool $replace Whether to replace or not any existing logger
2013-07-24 06:23:37 +01:00
*/
2014-05-26 11:29:25 +01:00
public function setDefaultLogger(LoggerInterface $logger, $levels = null, $replace = false)
{
2014-05-26 11:29:25 +01:00
$loggers = array();
if (\is_array($levels)) {
2014-05-26 11:29:25 +01:00
foreach ($levels as $type => $logLevel) {
if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
2014-05-26 11:29:25 +01:00
$loggers[$type] = array($logger, $logLevel);
}
}
} else {
if (null === $levels) {
$levels = E_ALL | E_STRICT;
}
foreach ($this->loggers as $type => $log) {
if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
2014-05-26 11:29:25 +01:00
$log[0] = $logger;
$loggers[$type] = $log;
}
}
}
$this->setLoggers($loggers);
}
2013-07-24 06:23:37 +01:00
/**
2014-05-26 11:29:25 +01:00
* Sets a logger for each error level.
2013-07-24 06:23:37 +01:00
*
2014-05-26 11:29:25 +01:00
* @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
*
* @return array The previous map
*
* @throws \InvalidArgumentException
2013-07-24 06:23:37 +01:00
*/
2014-05-26 11:29:25 +01:00
public function setLoggers(array $loggers)
{
2014-05-26 11:29:25 +01:00
$prevLogged = $this->loggedErrors;
$prev = $this->loggers;
$flush = array();
2014-05-26 11:29:25 +01:00
foreach ($loggers as $type => $log) {
if (!isset($prev[$type])) {
throw new \InvalidArgumentException('Unknown error type: '.$type);
}
if (!\is_array($log)) {
2014-05-26 11:29:25 +01:00
$log = array($log);
} elseif (!array_key_exists(0, $log)) {
throw new \InvalidArgumentException('No logger provided');
}
if (null === $log[0]) {
$this->loggedErrors &= ~$type;
} elseif ($log[0] instanceof LoggerInterface) {
$this->loggedErrors |= $type;
} else {
throw new \InvalidArgumentException('Invalid logger provided');
}
$this->loggers[$type] = $log + $prev[$type];
if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
$flush[$type] = $type;
}
2014-05-26 11:29:25 +01:00
}
$this->reRegister($prevLogged | $this->thrownErrors);
if ($flush) {
foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
$type = $log[2]['type'];
if (!isset($flush[$type])) {
$this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
} elseif ($this->loggers[$type][0]) {
$this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
}
}
}
2014-05-26 11:29:25 +01:00
return $prev;
}
2013-07-24 06:23:37 +01:00
/**
2014-05-26 11:29:25 +01:00
* Sets a user exception handler.
2013-07-24 06:23:37 +01:00
*
2014-05-26 11:29:25 +01:00
* @param callable $handler A handler that will be called on Exception
*
* @return callable|null The previous exception handler
*
* @throws \InvalidArgumentException
2013-07-24 06:23:37 +01:00
*/
2014-05-26 11:29:25 +01:00
public function setExceptionHandler($handler)
{
if (null !== $handler && !\is_callable($handler)) {
2014-05-26 11:29:25 +01:00
throw new \LogicException('The exception handler must be a valid PHP callable.');
}
$prev = $this->exceptionHandler;
$this->exceptionHandler = $handler;
return $prev;
}
2014-04-17 08:44:42 +01:00
/**
2015-04-03 08:48:36 +01:00
* Sets the PHP error levels that throw an exception when a PHP error occurs.
2014-05-26 11:29:25 +01:00
*
* @param int $levels A bit field of E_* constants for thrown errors
* @param bool $replace Replace or amend the previous value
*
* @return int The previous value
*/
2014-05-26 11:29:25 +01:00
public function throwAt($levels, $replace = false)
{
$prev = $this->thrownErrors;
$this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
2014-05-26 11:29:25 +01:00
if (!$replace) {
$this->thrownErrors |= $prev;
}
$this->reRegister($prev | $this->loggedErrors);
// $this->displayErrors is @deprecated since version 2.6
2014-05-26 11:29:25 +01:00
$this->displayErrors = $this->thrownErrors;
return $prev;
}
/**
2015-04-02 17:36:00 +01:00
* Sets the PHP error levels for which local variables are preserved.
2014-05-26 11:29:25 +01:00
*
* @param int $levels A bit field of E_* constants for scoped errors
* @param bool $replace Replace or amend the previous value
*
* @return int The previous value
*/
public function scopeAt($levels, $replace = false)
{
$prev = $this->scopedErrors;
$this->scopedErrors = (int) $levels;
if (!$replace) {
$this->scopedErrors |= $prev;
}
return $prev;
}
/**
2015-04-03 08:48:36 +01:00
* Sets the PHP error levels for which the stack trace is preserved.
2014-05-26 11:29:25 +01:00
*
* @param int $levels A bit field of E_* constants for traced errors
* @param bool $replace Replace or amend the previous value
*
* @return int The previous value
*/
public function traceAt($levels, $replace = false)
{
$prev = $this->tracedErrors;
$this->tracedErrors = (int) $levels;
if (!$replace) {
$this->tracedErrors |= $prev;
}
return $prev;
}
/**
* Sets the error levels where the @-operator is ignored.
*
* @param int $levels A bit field of E_* constants for screamed errors
* @param bool $replace Replace or amend the previous value
*
* @return int The previous value
*/
public function screamAt($levels, $replace = false)
{
$prev = $this->screamedErrors;
$this->screamedErrors = (int) $levels;
if (!$replace) {
$this->screamedErrors |= $prev;
}
return $prev;
}
/**
* Re-registers as a PHP error handler if levels changed.
*/
private function reRegister($prev)
{
if ($prev !== $this->thrownErrors | $this->loggedErrors) {
$handler = set_error_handler('var_dump');
$handler = \is_array($handler) ? $handler[0] : null;
2014-05-26 11:29:25 +01:00
restore_error_handler();
if ($handler === $this) {
restore_error_handler();
if ($this->isRoot) {
set_error_handler(array($this, 'handleError'), $this->thrownErrors | $this->loggedErrors);
} else {
set_error_handler(array($this, 'handleError'));
}
2014-05-26 11:29:25 +01:00
}
}
}
/**
* Handles errors by filtering then logging them according to the configured bit fields.
*
* @param int $type One of the E_* constants
2016-09-02 19:13:13 +01:00
* @param string $message
2014-05-26 11:29:25 +01:00
* @param string $file
* @param int $line
*
* @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
2014-05-26 11:29:25 +01:00
*
* @throws \ErrorException When $this->thrownErrors requests so
*
* @internal
*/
public function handleError($type, $message, $file, $line)
{
$level = error_reporting();
$silenced = 0 === ($level & $type);
$level |= E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED;
2014-05-26 11:29:25 +01:00
$log = $this->loggedErrors & $type;
$throw = $this->thrownErrors & $type & $level;
$type &= $level | $this->screamedErrors;
if (!$type || (!$log && !$throw)) {
return !$silenced && $type && $log;
}
$scope = $this->scopedErrors & $type;
2014-05-26 11:29:25 +01:00
if (4 < $numArgs = \func_num_args()) {
2017-01-25 12:11:45 +00:00
$context = $scope ? (func_get_arg(4) ?: array()) : array();
$backtrace = 5 < $numArgs ? func_get_arg(5) : null; // defined on HHVM
} else {
$context = array();
$backtrace = null;
}
if (isset($context['GLOBALS']) && $scope) {
$e = $context; // Whatever the signature of the method,
unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
$context = $e;
}
if (null !== $backtrace && $type & E_ERROR) {
// E_ERROR fatal errors are triggered on HHVM when
// hhvm.error_handling.call_user_handler_on_fatals=1
// which is the way to get their backtrace.
$this->handleFatalError(compact('type', 'message', 'file', 'line', 'backtrace'));
return true;
}
if ($throw) {
if (null !== self::$toStringException) {
$throw = self::$toStringException;
self::$toStringException = null;
} elseif ($scope && class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) {
// Checking for class existence is a work around for https://bugs.php.net/42098
$throw = new ContextErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line, $context);
} else {
$throw = new \ErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line);
}
2014-05-26 11:29:25 +01:00
2017-06-01 18:56:34 +01:00
if (\PHP_VERSION_ID <= 50407 && (\PHP_VERSION_ID >= 50400 || \PHP_VERSION_ID <= 50317)) {
// Exceptions thrown from error handlers are sometimes not caught by the exception
// handler and shutdown handlers are bypassed before 5.4.8/5.3.18.
// We temporarily re-enable display_errors to prevent any blank page related to this bug.
$throw->errorHandlerCanary = new ErrorHandlerCanary();
}
if (E_USER_ERROR & $type) {
$backtrace = $backtrace ?: $throw->getTrace();
for ($i = 1; isset($backtrace[$i]); ++$i) {
if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
&& '__toString' === $backtrace[$i]['function']
&& '->' === $backtrace[$i]['type']
&& !isset($backtrace[$i - 1]['class'])
&& ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
) {
// Here, we know trigger_error() has been called from __toString().
// HHVM is fine with throwing from __toString() but PHP triggers a fatal error instead.
// A small convention allows working around the limitation:
// given a caught $e exception in __toString(), quitting the method with
// `return trigger_error($e, E_USER_ERROR);` allows this error handler
// to make $e get through the __toString() barrier.
foreach ($context as $e) {
if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
if (1 === $i) {
// On HHVM
$throw = $e;
break;
}
self::$toStringException = $e;
return true;
}
}
if (1 < $i) {
// On PHP (not on HHVM), display the original error message instead of the default one.
$this->handleException($throw);
// Stop the process by giving back the error to the native handler.
return false;
}
}
}
}
throw $throw;
}
2014-05-26 11:29:25 +01:00
// For duplicated errors, log the trace only once
$e = md5("{$type}/{$line}/{$file}\x00{$message}", true);
$trace = true;
if (!($this->tracedErrors & $type) || isset($this->loggedTraces[$e])) {
$trace = false;
} else {
$this->loggedTraces[$e] = 1;
}
$e = compact('type', 'file', 'line', 'level');
if ($type & $level) {
if ($scope) {
$e['scope_vars'] = $context;
if ($trace) {
$e['stack'] = $backtrace ?: debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
2014-05-26 11:29:25 +01:00
}
} elseif ($trace) {
if (null === $backtrace) {
$e['stack'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
} else {
foreach ($backtrace as &$frame) {
unset($frame['args'], $frame);
}
$e['stack'] = $backtrace;
}
}
}
if ($this->isRecursive) {
$log = 0;
} elseif (self::$stackedErrorLevels) {
self::$stackedErrors[] = array($this->loggers[$type][0], ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG, $message, $e);
} else {
try {
$this->isRecursive = true;
$this->loggers[$type][0]->log(($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG, $message, $e);
$this->isRecursive = false;
} catch (\Exception $e) {
$this->isRecursive = false;
2016-05-12 16:11:08 +01:00
throw $e;
} catch (\Throwable $e) {
$this->isRecursive = false;
throw $e;
2014-05-26 11:29:25 +01:00
}
}
return !$silenced && $type && $log;
2014-05-26 11:29:25 +01:00
}
/**
2015-08-16 16:42:14 +01:00
* Handles an exception by logging then forwarding it to another handler.
2014-05-26 11:29:25 +01:00
*
* @param \Exception|\Throwable $exception An exception to handle
* @param array $error An array as returned by error_get_last()
2014-05-26 11:29:25 +01:00
*
* @internal
*/
public function handleException($exception, array $error = null)
2014-05-26 11:29:25 +01:00
{
if (null === $error) {
self::$exitCode = 255;
}
if (!$exception instanceof \Exception) {
$exception = new FatalThrowableError($exception);
}
$type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
$handlerException = null;
if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
2014-05-26 11:29:25 +01:00
$e = array(
'type' => $type,
2014-05-26 11:29:25 +01:00
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'level' => error_reporting(),
2014-05-26 11:29:25 +01:00
'stack' => $exception->getTrace(),
);
if ($exception instanceof FatalErrorException) {
if ($exception instanceof FatalThrowableError) {
$error = array(
'type' => $type,
'message' => $message = $exception->getMessage(),
'file' => $e['file'],
'line' => $e['line'],
);
} else {
$message = 'Fatal '.$exception->getMessage();
}
2014-05-26 11:29:25 +01:00
} elseif ($exception instanceof \ErrorException) {
$message = 'Uncaught '.$exception->getMessage();
if ($exception instanceof ContextErrorException) {
$e['context'] = $exception->getContext();
}
} else {
2014-05-26 11:29:25 +01:00
$message = 'Uncaught Exception: '.$exception->getMessage();
}
}
if ($this->loggedErrors & $type) {
try {
$this->loggers[$type][0]->log($this->loggers[$type][1], $message, $e);
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
2014-05-26 11:29:25 +01:00
}
if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
foreach ($this->getFatalErrorHandlers() as $handler) {
if ($e = $handler->handleError($error, $exception)) {
$exception = $e;
break;
}
}
}
$exceptionHandler = $this->exceptionHandler;
$this->exceptionHandler = null;
2014-05-26 11:29:25 +01:00
try {
if (null !== $exceptionHandler) {
return \call_user_func($exceptionHandler, $exception);
}
$handlerException = $handlerException ?: $exception;
2014-05-26 11:29:25 +01:00
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
if ($exception === $handlerException) {
self::$reservedMemory = null; // Disable the fatal error handler
throw $exception; // Give back $exception to the native handler
2014-05-26 11:29:25 +01:00
}
$this->handleException($handlerException);
2014-05-26 11:29:25 +01:00
}
/**
* Shutdown registered function for handling PHP fatal errors.
*
* @param array $error An array as returned by error_get_last()
*
* @internal
*/
public static function handleFatalError(array $error = null)
{
if (null === self::$reservedMemory) {
return;
}
$handler = self::$reservedMemory = null;
$handlers = array();
$previousHandler = null;
$sameHandlerLimit = 10;
while (!\is_array($handler) || !$handler[0] instanceof self) {
$handler = set_exception_handler('var_dump');
restore_exception_handler();
2014-05-26 11:29:25 +01:00
if (!$handler) {
break;
}
restore_exception_handler();
if ($handler !== $previousHandler) {
array_unshift($handlers, $handler);
$previousHandler = $handler;
} elseif (0 === --$sameHandlerLimit) {
$handler = null;
break;
}
}
foreach ($handlers as $h) {
set_exception_handler($h);
}
if (!$handler) {
return;
}
if ($handler !== $h) {
$handler[0]->setExceptionHandler($h);
}
$handler = $handler[0];
$handlers = array();
2014-05-26 11:29:25 +01:00
if ($exit = null === $error) {
$error = error_get_last();
}
try {
while (self::$stackedErrorLevels) {
static::unstackErrors();
2014-05-26 11:29:25 +01:00
}
} catch (\Exception $exception) {
// Handled below
2016-05-12 16:11:08 +01:00
} catch (\Throwable $exception) {
// Handled below
}
2014-05-26 11:29:25 +01:00
if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
// Let's not throw anymore but keep logging
$handler->throwAt(0, true);
$trace = isset($error['backtrace']) ? $error['backtrace'] : null;
if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
$exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
} else {
$exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
2014-05-26 11:29:25 +01:00
}
}
try {
if (isset($exception)) {
self::$exitCode = 255;
$handler->handleException($exception, $error);
}
} catch (FatalErrorException $e) {
// Ignore this re-throw
2014-05-26 11:29:25 +01:00
}
if ($exit && self::$exitCode) {
$exitCode = self::$exitCode;
register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
}
}
/**
2014-05-26 11:29:25 +01:00
* Configures the error handler for delayed handling.
* Ensures also that non-catchable fatal errors are never silenced.
*
* As shown by http://bugs.php.net/42098 and http://bugs.php.net/60724
* PHP has a compile stage where it behaves unusually. To workaround it,
* we plug an error handler that only stacks errors for later.
*
* The most important feature of this is to prevent
* autoloading until unstackErrors() is called.
*/
public static function stackErrors()
{
self::$stackedErrorLevels[] = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
}
/**
* Unstacks stacked errors and forwards to the logger.
*/
public static function unstackErrors()
{
$level = array_pop(self::$stackedErrorLevels);
if (null !== $level) {
2014-05-23 15:20:40 +01:00
$e = error_reporting($level);
if ($e !== ($level | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
// If the user changed the error level, do not overwrite it
error_reporting($e);
}
}
if (empty(self::$stackedErrorLevels)) {
$errors = self::$stackedErrors;
self::$stackedErrors = array();
2014-05-26 11:29:25 +01:00
foreach ($errors as $e) {
$e[0]->log($e[1], $e[2], $e[3]);
}
2013-07-24 05:59:37 +01:00
}
}
2013-07-24 06:23:37 +01:00
/**
* Gets the fatal error handlers.
*
* Override this method if you want to define more fatal error handlers.
*
* @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
*/
protected function getFatalErrorHandlers()
{
return array(
new UndefinedFunctionFatalErrorHandler(),
new UndefinedMethodFatalErrorHandler(),
new ClassNotFoundFatalErrorHandler(),
);
}
2014-05-26 11:29:25 +01:00
/**
* Sets the level at which the conversion to Exception is done.
*
* @param int|null $level The level (null to use the error_reporting() value and 0 to disable)
2014-05-26 11:29:25 +01:00
*
* @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
2014-05-26 11:29:25 +01:00
*/
public function setLevel($level)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
2014-05-26 11:29:25 +01:00
$level = null === $level ? error_reporting() : $level;
$this->throwAt($level, true);
}
2014-05-26 11:29:25 +01:00
/**
* Sets the display_errors flag value.
*
* @param int $displayErrors The display_errors flag value
2014-05-26 11:29:25 +01:00
*
* @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
2014-05-26 11:29:25 +01:00
*/
public function setDisplayErrors($displayErrors)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
2014-05-26 11:29:25 +01:00
if ($displayErrors) {
$this->throwAt($this->displayErrors, true);
} else {
2014-05-26 11:29:25 +01:00
$displayErrors = $this->displayErrors;
$this->throwAt(0, true);
$this->displayErrors = $displayErrors;
}
2014-05-26 11:29:25 +01:00
}
2013-07-24 05:59:37 +01:00
2014-05-26 11:29:25 +01:00
/**
* Sets a logger for the given channel.
*
* @param LoggerInterface $logger A logger interface
* @param string $channel The channel associated with the logger (deprecation, emergency or scream)
*
* @deprecated since version 2.6, to be removed in 3.0. Use setLoggers() or setDefaultLogger() instead.
2014-05-26 11:29:25 +01:00
*/
public static function setLogger(LoggerInterface $logger, $channel = 'deprecation')
{
@trigger_error('The '.__METHOD__.' static method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the setLoggers() or setDefaultLogger() methods instead.', E_USER_DEPRECATED);
$handler = set_error_handler('var_dump');
$handler = \is_array($handler) ? $handler[0] : null;
2014-05-26 11:29:25 +01:00
restore_error_handler();
if (!$handler instanceof self) {
return;
}
if ('deprecation' === $channel) {
$handler->setDefaultLogger($logger, E_DEPRECATED | E_USER_DEPRECATED, true);
$handler->screamAt(E_DEPRECATED | E_USER_DEPRECATED);
} elseif ('scream' === $channel) {
$handler->setDefaultLogger($logger, E_ALL | E_STRICT, false);
$handler->screamAt(E_ALL | E_STRICT);
} elseif ('emergency' === $channel) {
$handler->setDefaultLogger($logger, E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR, true);
$handler->screamAt(E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
}
}
2014-05-26 11:29:25 +01:00
/**
* @deprecated since version 2.6, to be removed in 3.0. Use handleError() instead.
2014-05-26 11:29:25 +01:00
*/
public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
{
$this->handleError(E_USER_DEPRECATED, 'The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the handleError() method instead.', __FILE__, __LINE__, array());
2014-05-26 11:29:25 +01:00
return $this->handleError($level, $message, $file, $line, (array) $context);
}
/**
* Handles PHP fatal errors.
*
* @deprecated since version 2.6, to be removed in 3.0. Use handleFatalError() instead.
2014-05-26 11:29:25 +01:00
*/
public function handleFatal()
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the handleFatalError() method instead.', E_USER_DEPRECATED);
2014-05-26 11:29:25 +01:00
static::handleFatalError();
}
}
/**
* Private class used to work around https://bugs.php.net/54275.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class ErrorHandlerCanary
{
private static $displayErrors = null;
public function __construct()
{
if (null === self::$displayErrors) {
self::$displayErrors = ini_set('display_errors', 1);
}
}
public function __destruct()
{
if (null !== self::$displayErrors) {
ini_set('display_errors', self::$displayErrors);
self::$displayErrors = null;
2014-04-17 08:44:42 +01:00
}
}
}