vendor/symfony/symfony/src/Symfony/Component/Debug/ErrorHandler.php line 601

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Debug;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\LogLevel;
  13. use Symfony\Component\Debug\Exception\ContextErrorException;
  14. use Symfony\Component\Debug\Exception\FatalErrorException;
  15. use Symfony\Component\Debug\Exception\FatalThrowableError;
  16. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  17. use Symfony\Component\Debug\Exception\SilencedErrorContext;
  18. use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
  19. use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
  20. use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
  21. use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
  22. /**
  23.  * A generic ErrorHandler for the PHP engine.
  24.  *
  25.  * Provides five bit fields that control how errors are handled:
  26.  * - thrownErrors: errors thrown as \ErrorException
  27.  * - loggedErrors: logged errors, when not @-silenced
  28.  * - scopedErrors: errors thrown or logged with their local context
  29.  * - tracedErrors: errors logged with their stack trace
  30.  * - screamedErrors: never @-silenced errors
  31.  *
  32.  * Each error level can be logged by a dedicated PSR-3 logger object.
  33.  * Screaming only applies to logging.
  34.  * Throwing takes precedence over logging.
  35.  * Uncaught exceptions are logged as E_ERROR.
  36.  * E_DEPRECATED and E_USER_DEPRECATED levels never throw.
  37.  * E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
  38.  * Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
  39.  * As errors have a performance cost, repeated errors are all logged, so that the developer
  40.  * can see them and weight them as more important to fix than others of the same level.
  41.  *
  42.  * @author Nicolas Grekas <p@tchwork.com>
  43.  * @author GrĂ©goire Pineau <lyrixx@lyrixx.info>
  44.  */
  45. class ErrorHandler
  46. {
  47.     private $levels = [
  48.         \E_DEPRECATED => 'Deprecated',
  49.         \E_USER_DEPRECATED => 'User Deprecated',
  50.         \E_NOTICE => 'Notice',
  51.         \E_USER_NOTICE => 'User Notice',
  52.         \E_STRICT => 'Runtime Notice',
  53.         \E_WARNING => 'Warning',
  54.         \E_USER_WARNING => 'User Warning',
  55.         \E_COMPILE_WARNING => 'Compile Warning',
  56.         \E_CORE_WARNING => 'Core Warning',
  57.         \E_USER_ERROR => 'User Error',
  58.         \E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  59.         \E_COMPILE_ERROR => 'Compile Error',
  60.         \E_PARSE => 'Parse Error',
  61.         \E_ERROR => 'Error',
  62.         \E_CORE_ERROR => 'Core Error',
  63.     ];
  64.     private $loggers = [
  65.         \E_DEPRECATED => [nullLogLevel::INFO],
  66.         \E_USER_DEPRECATED => [nullLogLevel::INFO],
  67.         \E_NOTICE => [nullLogLevel::WARNING],
  68.         \E_USER_NOTICE => [nullLogLevel::WARNING],
  69.         \E_STRICT => [nullLogLevel::WARNING],
  70.         \E_WARNING => [nullLogLevel::WARNING],
  71.         \E_USER_WARNING => [nullLogLevel::WARNING],
  72.         \E_COMPILE_WARNING => [nullLogLevel::WARNING],
  73.         \E_CORE_WARNING => [nullLogLevel::WARNING],
  74.         \E_USER_ERROR => [nullLogLevel::CRITICAL],
  75.         \E_RECOVERABLE_ERROR => [nullLogLevel::CRITICAL],
  76.         \E_COMPILE_ERROR => [nullLogLevel::CRITICAL],
  77.         \E_PARSE => [nullLogLevel::CRITICAL],
  78.         \E_ERROR => [nullLogLevel::CRITICAL],
  79.         \E_CORE_ERROR => [nullLogLevel::CRITICAL],
  80.     ];
  81.     private $thrownErrors 0x1FFF// E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  82.     private $scopedErrors 0x1FFF// E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  83.     private $tracedErrors 0x77FB// E_ALL - E_STRICT - E_PARSE
  84.     private $screamedErrors 0x55// E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
  85.     private $loggedErrors 0;
  86.     private $traceReflector;
  87.     private $isRecursive 0;
  88.     private $isRoot false;
  89.     private $exceptionHandler;
  90.     private $bootstrappingLogger;
  91.     private static $reservedMemory;
  92.     private static $stackedErrors = [];
  93.     private static $stackedErrorLevels = [];
  94.     private static $toStringException null;
  95.     private static $silencedErrorCache = [];
  96.     private static $silencedErrorCount 0;
  97.     private static $exitCode 0;
  98.     /**
  99.      * Registers the error handler.
  100.      *
  101.      * @param self|null $handler The handler to register
  102.      * @param bool      $replace Whether to replace or not any existing handler
  103.      *
  104.      * @return self The registered error handler
  105.      */
  106.     public static function register(self $handler null$replace true)
  107.     {
  108.         if (null === self::$reservedMemory) {
  109.             self::$reservedMemory str_repeat('x'10240);
  110.             register_shutdown_function(__CLASS__.'::handleFatalError');
  111.         }
  112.         if ($handlerIsNew null === $handler) {
  113.             $handler = new static();
  114.         }
  115.         if (null === $prev set_error_handler([$handler'handleError'])) {
  116.             restore_error_handler();
  117.             // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  118.             set_error_handler([$handler'handleError'], $handler->thrownErrors $handler->loggedErrors);
  119.             $handler->isRoot true;
  120.         }
  121.         if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
  122.             $handler $prev[0];
  123.             $replace false;
  124.         }
  125.         if (!$replace && $prev) {
  126.             restore_error_handler();
  127.             $handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
  128.         } else {
  129.             $handlerIsRegistered true;
  130.         }
  131.         if (\is_array($prev set_exception_handler([$handler'handleException'])) && $prev[0] instanceof self) {
  132.             restore_exception_handler();
  133.             if (!$handlerIsRegistered) {
  134.                 $handler $prev[0];
  135.             } elseif ($handler !== $prev[0] && $replace) {
  136.                 set_exception_handler([$handler'handleException']);
  137.                 $p $prev[0]->setExceptionHandler(null);
  138.                 $handler->setExceptionHandler($p);
  139.                 $prev[0]->setExceptionHandler($p);
  140.             }
  141.         } else {
  142.             $handler->setExceptionHandler($prev);
  143.         }
  144.         $handler->throwAt(\E_ALL $handler->thrownErrorstrue);
  145.         return $handler;
  146.     }
  147.     public function __construct(BufferingLogger $bootstrappingLogger null)
  148.     {
  149.         if ($bootstrappingLogger) {
  150.             $this->bootstrappingLogger $bootstrappingLogger;
  151.             $this->setDefaultLogger($bootstrappingLogger);
  152.         }
  153.         $this->traceReflector = new \ReflectionProperty('Exception''trace');
  154.         $this->traceReflector->setAccessible(true);
  155.     }
  156.     /**
  157.      * Sets a logger to non assigned errors levels.
  158.      *
  159.      * @param LoggerInterface $logger  A PSR-3 logger to put as default for the given levels
  160.      * @param array|int       $levels  An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  161.      * @param bool            $replace Whether to replace or not any existing logger
  162.      */
  163.     public function setDefaultLogger(LoggerInterface $logger$levels = \E_ALL$replace false)
  164.     {
  165.         $loggers = [];
  166.         if (\is_array($levels)) {
  167.             foreach ($levels as $type => $logLevel) {
  168.                 if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  169.                     $loggers[$type] = [$logger$logLevel];
  170.                 }
  171.             }
  172.         } else {
  173.             if (null === $levels) {
  174.                 $levels = \E_ALL;
  175.             }
  176.             foreach ($this->loggers as $type => $log) {
  177.                 if (($type $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  178.                     $log[0] = $logger;
  179.                     $loggers[$type] = $log;
  180.                 }
  181.             }
  182.         }
  183.         $this->setLoggers($loggers);
  184.     }
  185.     /**
  186.      * Sets a logger for each error level.
  187.      *
  188.      * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  189.      *
  190.      * @return array The previous map
  191.      *
  192.      * @throws \InvalidArgumentException
  193.      */
  194.     public function setLoggers(array $loggers)
  195.     {
  196.         $prevLogged $this->loggedErrors;
  197.         $prev $this->loggers;
  198.         $flush = [];
  199.         foreach ($loggers as $type => $log) {
  200.             if (!isset($prev[$type])) {
  201.                 throw new \InvalidArgumentException('Unknown error type: '.$type);
  202.             }
  203.             if (!\is_array($log)) {
  204.                 $log = [$log];
  205.             } elseif (!\array_key_exists(0$log)) {
  206.                 throw new \InvalidArgumentException('No logger provided.');
  207.             }
  208.             if (null === $log[0]) {
  209.                 $this->loggedErrors &= ~$type;
  210.             } elseif ($log[0] instanceof LoggerInterface) {
  211.                 $this->loggedErrors |= $type;
  212.             } else {
  213.                 throw new \InvalidArgumentException('Invalid logger provided.');
  214.             }
  215.             $this->loggers[$type] = $log $prev[$type];
  216.             if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  217.                 $flush[$type] = $type;
  218.             }
  219.         }
  220.         $this->reRegister($prevLogged $this->thrownErrors);
  221.         if ($flush) {
  222.             foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  223.                 $type $log[2]['exception'] instanceof \ErrorException $log[2]['exception']->getSeverity() : \E_ERROR;
  224.                 if (!isset($flush[$type])) {
  225.                     $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  226.                 } elseif ($this->loggers[$type][0]) {
  227.                     $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  228.                 }
  229.             }
  230.         }
  231.         return $prev;
  232.     }
  233.     /**
  234.      * Sets a user exception handler.
  235.      *
  236.      * @param callable $handler A handler that will be called on Exception
  237.      *
  238.      * @return callable|null The previous exception handler
  239.      */
  240.     public function setExceptionHandler(callable $handler null)
  241.     {
  242.         $prev $this->exceptionHandler;
  243.         $this->exceptionHandler $handler;
  244.         return $prev;
  245.     }
  246.     /**
  247.      * Sets the PHP error levels that throw an exception when a PHP error occurs.
  248.      *
  249.      * @param int  $levels  A bit field of E_* constants for thrown errors
  250.      * @param bool $replace Replace or amend the previous value
  251.      *
  252.      * @return int The previous value
  253.      */
  254.     public function throwAt($levels$replace false)
  255.     {
  256.         $prev $this->thrownErrors;
  257.         $this->thrownErrors = ($levels | \E_RECOVERABLE_ERROR | \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED;
  258.         if (!$replace) {
  259.             $this->thrownErrors |= $prev;
  260.         }
  261.         $this->reRegister($prev $this->loggedErrors);
  262.         return $prev;
  263.     }
  264.     /**
  265.      * Sets the PHP error levels for which local variables are preserved.
  266.      *
  267.      * @param int  $levels  A bit field of E_* constants for scoped errors
  268.      * @param bool $replace Replace or amend the previous value
  269.      *
  270.      * @return int The previous value
  271.      */
  272.     public function scopeAt($levels$replace false)
  273.     {
  274.         $prev $this->scopedErrors;
  275.         $this->scopedErrors = (int) $levels;
  276.         if (!$replace) {
  277.             $this->scopedErrors |= $prev;
  278.         }
  279.         return $prev;
  280.     }
  281.     /**
  282.      * Sets the PHP error levels for which the stack trace is preserved.
  283.      *
  284.      * @param int  $levels  A bit field of E_* constants for traced errors
  285.      * @param bool $replace Replace or amend the previous value
  286.      *
  287.      * @return int The previous value
  288.      */
  289.     public function traceAt($levels$replace false)
  290.     {
  291.         $prev $this->tracedErrors;
  292.         $this->tracedErrors = (int) $levels;
  293.         if (!$replace) {
  294.             $this->tracedErrors |= $prev;
  295.         }
  296.         return $prev;
  297.     }
  298.     /**
  299.      * Sets the error levels where the @-operator is ignored.
  300.      *
  301.      * @param int  $levels  A bit field of E_* constants for screamed errors
  302.      * @param bool $replace Replace or amend the previous value
  303.      *
  304.      * @return int The previous value
  305.      */
  306.     public function screamAt($levels$replace false)
  307.     {
  308.         $prev $this->screamedErrors;
  309.         $this->screamedErrors = (int) $levels;
  310.         if (!$replace) {
  311.             $this->screamedErrors |= $prev;
  312.         }
  313.         return $prev;
  314.     }
  315.     /**
  316.      * Re-registers as a PHP error handler if levels changed.
  317.      */
  318.     private function reRegister($prev)
  319.     {
  320.         if ($prev !== $this->thrownErrors $this->loggedErrors) {
  321.             $handler set_error_handler('var_dump');
  322.             $handler = \is_array($handler) ? $handler[0] : null;
  323.             restore_error_handler();
  324.             if ($handler === $this) {
  325.                 restore_error_handler();
  326.                 if ($this->isRoot) {
  327.                     set_error_handler([$this'handleError'], $this->thrownErrors $this->loggedErrors);
  328.                 } else {
  329.                     set_error_handler([$this'handleError']);
  330.                 }
  331.             }
  332.         }
  333.     }
  334.     /**
  335.      * Handles errors by filtering then logging them according to the configured bit fields.
  336.      *
  337.      * @param int    $type    One of the E_* constants
  338.      * @param string $message
  339.      * @param string $file
  340.      * @param int    $line
  341.      *
  342.      * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  343.      *
  344.      * @throws \ErrorException When $this->thrownErrors requests so
  345.      *
  346.      * @internal
  347.      */
  348.     public function handleError($type$message$file$line)
  349.     {
  350.         if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message'" targeting switch is equivalent to "break')) {
  351.             $type = \E_DEPRECATED;
  352.         }
  353.         // Level is the current error reporting level to manage silent error.
  354.         $level error_reporting();
  355.         $silenced === ($level $type);
  356.         // Strong errors are not authorized to be silenced.
  357.         $level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED;
  358.         $log $this->loggedErrors $type;
  359.         $throw $this->thrownErrors $type $level;
  360.         $type &= $level $this->screamedErrors;
  361.         if (!$type || (!$log && !$throw)) {
  362.             return !$silenced && $type && $log;
  363.         }
  364.         $scope $this->scopedErrors $type;
  365.         if ($numArgs = \func_num_args()) {
  366.             $context func_get_arg(4) ?: [];
  367.             $backtrace $numArgs func_get_arg(5) : null// defined on HHVM
  368.         } else {
  369.             $context = [];
  370.             $backtrace null;
  371.         }
  372.         if (isset($context['GLOBALS']) && $scope) {
  373.             $e $context;                  // Whatever the signature of the method,
  374.             unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
  375.             $context $e;
  376.         }
  377.         if (null !== $backtrace && $type & \E_ERROR) {
  378.             // E_ERROR fatal errors are triggered on HHVM when
  379.             // hhvm.error_handling.call_user_handler_on_fatals=1
  380.             // which is the way to get their backtrace.
  381.             $this->handleFatalError(compact('type''message''file''line''backtrace'));
  382.             return true;
  383.         }
  384.         $logMessage $this->levels[$type].': '.$message;
  385.         if (null !== self::$toStringException) {
  386.             $errorAsException self::$toStringException;
  387.             self::$toStringException null;
  388.         } elseif (!$throw && !($type $level)) {
  389.             if (!isset(self::$silencedErrorCache[$id $file.':'.$line])) {
  390.                 $lightTrace $this->tracedErrors $type $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS3), $type$file$linefalse) : [];
  391.                 $errorAsException = new SilencedErrorContext($type$file$line$lightTrace);
  392.             } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  393.                 $lightTrace null;
  394.                 $errorAsException self::$silencedErrorCache[$id][$message];
  395.                 ++$errorAsException->count;
  396.             } else {
  397.                 $lightTrace = [];
  398.                 $errorAsException null;
  399.             }
  400.             if (100 < ++self::$silencedErrorCount) {
  401.                 self::$silencedErrorCache $lightTrace = [];
  402.                 self::$silencedErrorCount 1;
  403.             }
  404.             if ($errorAsException) {
  405.                 self::$silencedErrorCache[$id][$message] = $errorAsException;
  406.             }
  407.             if (null === $lightTrace) {
  408.                 return true;
  409.             }
  410.         } else {
  411.             if ($scope) {
  412.                 $errorAsException = new ContextErrorException($logMessage0$type$file$line$context);
  413.             } else {
  414.                 $errorAsException = new \ErrorException($logMessage0$type$file$line);
  415.             }
  416.             // Clean the trace by removing function arguments and the first frames added by the error handler itself.
  417.             if ($throw || $this->tracedErrors $type) {
  418.                 $backtrace $backtrace ?: $errorAsException->getTrace();
  419.                 $lightTrace $this->cleanTrace($backtrace$type$file$line$throw);
  420.                 $this->traceReflector->setValue($errorAsException$lightTrace);
  421.             } else {
  422.                 $this->traceReflector->setValue($errorAsException, []);
  423.             }
  424.         }
  425.         if ($throw) {
  426.             if (\PHP_VERSION_ID 70400 && \E_USER_ERROR $type) {
  427.                 for ($i 1; isset($backtrace[$i]); ++$i) {
  428.                     if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i 1]['function'])
  429.                         && '__toString' === $backtrace[$i]['function']
  430.                         && '->' === $backtrace[$i]['type']
  431.                         && !isset($backtrace[$i 1]['class'])
  432.                         && ('trigger_error' === $backtrace[$i 1]['function'] || 'user_error' === $backtrace[$i 1]['function'])
  433.                     ) {
  434.                         // Here, we know trigger_error() has been called from __toString().
  435.                         // HHVM is fine with throwing from __toString() but PHP triggers a fatal error instead.
  436.                         // A small convention allows working around the limitation:
  437.                         // given a caught $e exception in __toString(), quitting the method with
  438.                         // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  439.                         // to make $e get through the __toString() barrier.
  440.                         foreach ($context as $e) {
  441.                             if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
  442.                                 if (=== $i) {
  443.                                     // On HHVM
  444.                                     $errorAsException $e;
  445.                                     break;
  446.                                 }
  447.                                 self::$toStringException $e;
  448.                                 return true;
  449.                             }
  450.                         }
  451.                         if ($i) {
  452.                             // On PHP (not on HHVM), display the original error message instead of the default one.
  453.                             $this->handleException($errorAsException);
  454.                             // Stop the process by giving back the error to the native handler.
  455.                             return false;
  456.                         }
  457.                     }
  458.                 }
  459.             }
  460.             throw $errorAsException;
  461.         }
  462.         if ($this->isRecursive) {
  463.             $log 0;
  464.         } elseif (self::$stackedErrorLevels) {
  465.             self::$stackedErrors[] = [
  466.                 $this->loggers[$type][0],
  467.                 ($type $level) ? $this->loggers[$type][1] : LogLevel::DEBUG,
  468.                 $logMessage,
  469.                 $errorAsException ? ['exception' => $errorAsException] : [],
  470.             ];
  471.         } else {
  472.             if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404) && !\defined('HHVM_VERSION')) {
  473.                 $currentErrorHandler set_error_handler('var_dump');
  474.                 restore_error_handler();
  475.             }
  476.             try {
  477.                 $this->isRecursive true;
  478.                 $level = ($type $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  479.                 $this->loggers[$type][0]->log($level$logMessage$errorAsException ? ['exception' => $errorAsException] : []);
  480.             } finally {
  481.                 $this->isRecursive false;
  482.                 if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404) && !\defined('HHVM_VERSION')) {
  483.                     set_error_handler($currentErrorHandler);
  484.                 }
  485.             }
  486.         }
  487.         return !$silenced && $type && $log;
  488.     }
  489.     /**
  490.      * Handles an exception by logging then forwarding it to another handler.
  491.      *
  492.      * @param \Exception|\Throwable $exception An exception to handle
  493.      * @param array                 $error     An array as returned by error_get_last()
  494.      *
  495.      * @internal
  496.      */
  497.     public function handleException($exception, array $error null)
  498.     {
  499.         if (null === $error) {
  500.             self::$exitCode 255;
  501.         }
  502.         if (!$exception instanceof \Exception) {
  503.             $exception = new FatalThrowableError($exception);
  504.         }
  505.         $type $exception instanceof FatalErrorException $exception->getSeverity() : \E_ERROR;
  506.         $handlerException null;
  507.         if (($this->loggedErrors $type) || $exception instanceof FatalThrowableError) {
  508.             if ($exception instanceof FatalErrorException) {
  509.                 if ($exception instanceof FatalThrowableError) {
  510.                     $error = [
  511.                         'type' => $type,
  512.                         'message' => $message $exception->getMessage(),
  513.                         'file' => $exception->getFile(),
  514.                         'line' => $exception->getLine(),
  515.                     ];
  516.                 } else {
  517.                     $message 'Fatal '.$exception->getMessage();
  518.                 }
  519.             } elseif ($exception instanceof \ErrorException) {
  520.                 $message 'Uncaught '.$exception->getMessage();
  521.             } else {
  522.                 $message 'Uncaught Exception: '.$exception->getMessage();
  523.             }
  524.         }
  525.         if ($this->loggedErrors $type) {
  526.             try {
  527.                 $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  528.             } catch (\Exception $handlerException) {
  529.             } catch (\Throwable $handlerException) {
  530.             }
  531.         }
  532.         if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
  533.             foreach ($this->getFatalErrorHandlers() as $handler) {
  534.                 if ($e $handler->handleError($error$exception)) {
  535.                     $exception $e;
  536.                     break;
  537.                 }
  538.             }
  539.         }
  540.         $exceptionHandler $this->exceptionHandler;
  541.         $this->exceptionHandler null;
  542.         try {
  543.             if (null !== $exceptionHandler) {
  544.                 $exceptionHandler($exception);
  545.                 return;
  546.             }
  547.             $handlerException $handlerException ?: $exception;
  548.         } catch (\Exception $handlerException) {
  549.         } catch (\Throwable $handlerException) {
  550.         }
  551.         if ($exception === $handlerException) {
  552.             self::$reservedMemory null// Disable the fatal error handler
  553.             throw $exception// Give back $exception to the native handler
  554.         }
  555.         $this->handleException($handlerException);
  556.     }
  557.     /**
  558.      * Shutdown registered function for handling PHP fatal errors.
  559.      *
  560.      * @param array $error An array as returned by error_get_last()
  561.      *
  562.      * @internal
  563.      */
  564.     public static function handleFatalError(array $error null)
  565.     {
  566.         if (null === self::$reservedMemory) {
  567.             return;
  568.         }
  569.         $handler self::$reservedMemory null;
  570.         $handlers = [];
  571.         $previousHandler null;
  572.         $sameHandlerLimit 10;
  573.         while (!\is_array($handler) || !$handler[0] instanceof self) {
  574.             $handler set_exception_handler('var_dump');
  575.             restore_exception_handler();
  576.             if (!$handler) {
  577.                 break;
  578.             }
  579.             restore_exception_handler();
  580.             if ($handler !== $previousHandler) {
  581.                 array_unshift($handlers$handler);
  582.                 $previousHandler $handler;
  583.             } elseif (=== --$sameHandlerLimit) {
  584.                 $handler null;
  585.                 break;
  586.             }
  587.         }
  588.         foreach ($handlers as $h) {
  589.             set_exception_handler($h);
  590.         }
  591.         if (!$handler) {
  592.             return;
  593.         }
  594.         if ($handler !== $h) {
  595.             $handler[0]->setExceptionHandler($h);
  596.         }
  597.         $handler $handler[0];
  598.         $handlers = [];
  599.         if ($exit null === $error) {
  600.             $error error_get_last();
  601.         }
  602.         try {
  603.             while (self::$stackedErrorLevels) {
  604.                 static::unstackErrors();
  605.             }
  606.         } catch (\Exception $exception) {
  607.             // Handled below
  608.         } catch (\Throwable $exception) {
  609.             // Handled below
  610.         }
  611.         if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) {
  612.             // Let's not throw anymore but keep logging
  613.             $handler->throwAt(0true);
  614.             $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  615.             if (=== strpos($error['message'], 'Allowed memory') || === strpos($error['message'], 'Out of memory')) {
  616.                 $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0$error['type'], $error['file'], $error['line'], 2false$trace);
  617.             } else {
  618.                 $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0$error['type'], $error['file'], $error['line'], 2true$trace);
  619.             }
  620.         }
  621.         try {
  622.             if (isset($exception)) {
  623.                 self::$exitCode 255;
  624.                 $handler->handleException($exception$error);
  625.             }
  626.         } catch (FatalErrorException $e) {
  627.             // Ignore this re-throw
  628.         }
  629.         if ($exit && self::$exitCode) {
  630.             $exitCode self::$exitCode;
  631.             register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  632.         }
  633.     }
  634.     /**
  635.      * Configures the error handler for delayed handling.
  636.      * Ensures also that non-catchable fatal errors are never silenced.
  637.      *
  638.      * As shown by http://bugs.php.net/42098 and http://bugs.php.net/60724
  639.      * PHP has a compile stage where it behaves unusually. To workaround it,
  640.      * we plug an error handler that only stacks errors for later.
  641.      *
  642.      * The most important feature of this is to prevent
  643.      * autoloading until unstackErrors() is called.
  644.      *
  645.      * @deprecated since version 3.4, to be removed in 4.0.
  646.      */
  647.     public static function stackErrors()
  648.     {
  649.         @trigger_error('Support for stacking errors is deprecated since Symfony 3.4 and will be removed in 4.0.', \E_USER_DEPRECATED);
  650.         self::$stackedErrorLevels[] = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
  651.     }
  652.     /**
  653.      * Unstacks stacked errors and forwards to the logger.
  654.      *
  655.      * @deprecated since version 3.4, to be removed in 4.0.
  656.      */
  657.     public static function unstackErrors()
  658.     {
  659.         @trigger_error('Support for unstacking errors is deprecated since Symfony 3.4 and will be removed in 4.0.', \E_USER_DEPRECATED);
  660.         $level array_pop(self::$stackedErrorLevels);
  661.         if (null !== $level) {
  662.             $errorReportingLevel error_reporting($level);
  663.             if ($errorReportingLevel !== ($level | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR)) {
  664.                 // If the user changed the error level, do not overwrite it
  665.                 error_reporting($errorReportingLevel);
  666.             }
  667.         }
  668.         if (empty(self::$stackedErrorLevels)) {
  669.             $errors self::$stackedErrors;
  670.             self::$stackedErrors = [];
  671.             foreach ($errors as $error) {
  672.                 $error[0]->log($error[1], $error[2], $error[3]);
  673.             }
  674.         }
  675.     }
  676.     /**
  677.      * Gets the fatal error handlers.
  678.      *
  679.      * Override this method if you want to define more fatal error handlers.
  680.      *
  681.      * @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
  682.      */
  683.     protected function getFatalErrorHandlers()
  684.     {
  685.         return [
  686.             new UndefinedFunctionFatalErrorHandler(),
  687.             new UndefinedMethodFatalErrorHandler(),
  688.             new ClassNotFoundFatalErrorHandler(),
  689.         ];
  690.     }
  691.     private function cleanTrace($backtrace$type$file$line$throw)
  692.     {
  693.         $lightTrace $backtrace;
  694.         for ($i 0; isset($backtrace[$i]); ++$i) {
  695.             if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  696.                 $lightTrace = \array_slice($lightTrace$i);
  697.                 break;
  698.             }
  699.         }
  700.         if (!($throw || $this->scopedErrors $type)) {
  701.             for ($i 0; isset($lightTrace[$i]); ++$i) {
  702.                 unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  703.             }
  704.         }
  705.         return $lightTrace;
  706.     }
  707. }