vendor/symfony/error-handler/ErrorHandler.php line 407

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\ErrorHandler;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\LogLevel;
  13. use Symfony\Component\ErrorHandler\Error\FatalError;
  14. use Symfony\Component\ErrorHandler\Error\OutOfMemoryError;
  15. use Symfony\Component\ErrorHandler\ErrorEnhancer\ClassNotFoundErrorEnhancer;
  16. use Symfony\Component\ErrorHandler\ErrorEnhancer\ErrorEnhancerInterface;
  17. use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedFunctionErrorEnhancer;
  18. use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedMethodErrorEnhancer;
  19. use Symfony\Component\ErrorHandler\ErrorRenderer\CliErrorRenderer;
  20. use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
  21. use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
  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.  * @final
  46.  */
  47. class ErrorHandler
  48. {
  49.     private $levels = [
  50.         \E_DEPRECATED => 'Deprecated',
  51.         \E_USER_DEPRECATED => 'User Deprecated',
  52.         \E_NOTICE => 'Notice',
  53.         \E_USER_NOTICE => 'User Notice',
  54.         \E_STRICT => 'Runtime Notice',
  55.         \E_WARNING => 'Warning',
  56.         \E_USER_WARNING => 'User Warning',
  57.         \E_COMPILE_WARNING => 'Compile Warning',
  58.         \E_CORE_WARNING => 'Core Warning',
  59.         \E_USER_ERROR => 'User Error',
  60.         \E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  61.         \E_COMPILE_ERROR => 'Compile Error',
  62.         \E_PARSE => 'Parse Error',
  63.         \E_ERROR => 'Error',
  64.         \E_CORE_ERROR => 'Core Error',
  65.     ];
  66.     private $loggers = [
  67.         \E_DEPRECATED => [nullLogLevel::INFO],
  68.         \E_USER_DEPRECATED => [nullLogLevel::INFO],
  69.         \E_NOTICE => [nullLogLevel::WARNING],
  70.         \E_USER_NOTICE => [nullLogLevel::WARNING],
  71.         \E_STRICT => [nullLogLevel::WARNING],
  72.         \E_WARNING => [nullLogLevel::WARNING],
  73.         \E_USER_WARNING => [nullLogLevel::WARNING],
  74.         \E_COMPILE_WARNING => [nullLogLevel::WARNING],
  75.         \E_CORE_WARNING => [nullLogLevel::WARNING],
  76.         \E_USER_ERROR => [nullLogLevel::CRITICAL],
  77.         \E_RECOVERABLE_ERROR => [nullLogLevel::CRITICAL],
  78.         \E_COMPILE_ERROR => [nullLogLevel::CRITICAL],
  79.         \E_PARSE => [nullLogLevel::CRITICAL],
  80.         \E_ERROR => [nullLogLevel::CRITICAL],
  81.         \E_CORE_ERROR => [nullLogLevel::CRITICAL],
  82.     ];
  83.     private $thrownErrors 0x1FFF// E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  84.     private $scopedErrors 0x1FFF// E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  85.     private $tracedErrors 0x77FB// E_ALL - E_STRICT - E_PARSE
  86.     private $screamedErrors 0x55// E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
  87.     private $loggedErrors 0;
  88.     private $configureException;
  89.     private $debug;
  90.     private $isRecursive 0;
  91.     private $isRoot false;
  92.     private $exceptionHandler;
  93.     private $bootstrappingLogger;
  94.     private static $reservedMemory;
  95.     private static $toStringException;
  96.     private static $silencedErrorCache = [];
  97.     private static $silencedErrorCount 0;
  98.     private static $exitCode 0;
  99.     /**
  100.      * Registers the error handler.
  101.      */
  102.     public static function register(self $handler nullbool $replace true): self
  103.     {
  104.         if (null === self::$reservedMemory) {
  105.             self::$reservedMemory str_repeat('x'10240);
  106.             register_shutdown_function(__CLASS__.'::handleFatalError');
  107.         }
  108.         if ($handlerIsNew null === $handler) {
  109.             $handler = new static();
  110.         }
  111.         if (null === $prev set_error_handler([$handler'handleError'])) {
  112.             restore_error_handler();
  113.             // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  114.             set_error_handler([$handler'handleError'], $handler->thrownErrors $handler->loggedErrors);
  115.             $handler->isRoot true;
  116.         }
  117.         if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
  118.             $handler $prev[0];
  119.             $replace false;
  120.         }
  121.         if (!$replace && $prev) {
  122.             restore_error_handler();
  123.             $handlerIsRegistered \is_array($prev) && $handler === $prev[0];
  124.         } else {
  125.             $handlerIsRegistered true;
  126.         }
  127.         if (\is_array($prev set_exception_handler([$handler'handleException'])) && $prev[0] instanceof self) {
  128.             restore_exception_handler();
  129.             if (!$handlerIsRegistered) {
  130.                 $handler $prev[0];
  131.             } elseif ($handler !== $prev[0] && $replace) {
  132.                 set_exception_handler([$handler'handleException']);
  133.                 $p $prev[0]->setExceptionHandler(null);
  134.                 $handler->setExceptionHandler($p);
  135.                 $prev[0]->setExceptionHandler($p);
  136.             }
  137.         } else {
  138.             $handler->setExceptionHandler($prev ?? [$handler'renderException']);
  139.         }
  140.         $handler->throwAt(\E_ALL $handler->thrownErrorstrue);
  141.         return $handler;
  142.     }
  143.     /**
  144.      * Calls a function and turns any PHP error into \ErrorException.
  145.      *
  146.      * @return mixed What $function(...$arguments) returns
  147.      *
  148.      * @throws \ErrorException When $function(...$arguments) triggers a PHP error
  149.      */
  150.     public static function call(callable $function, ...$arguments)
  151.     {
  152.         set_error_handler(static function (int $typestring $messagestring $fileint $line) {
  153.             if (__FILE__ === $file) {
  154.                 $trace debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS3);
  155.                 $file $trace[2]['file'] ?? $file;
  156.                 $line $trace[2]['line'] ?? $line;
  157.             }
  158.             throw new \ErrorException($message0$type$file$line);
  159.         });
  160.         try {
  161.             return $function(...$arguments);
  162.         } finally {
  163.             restore_error_handler();
  164.         }
  165.     }
  166.     public function __construct(BufferingLogger $bootstrappingLogger nullbool $debug false)
  167.     {
  168.         if ($bootstrappingLogger) {
  169.             $this->bootstrappingLogger $bootstrappingLogger;
  170.             $this->setDefaultLogger($bootstrappingLogger);
  171.         }
  172.         $traceReflector = new \ReflectionProperty(\Exception::class, 'trace');
  173.         $traceReflector->setAccessible(true);
  174.         $this->configureException \Closure::bind(static function ($e$trace$file null$line null) use ($traceReflector) {
  175.             $traceReflector->setValue($e$trace);
  176.             $e->file $file ?? $e->file;
  177.             $e->line $line ?? $e->line;
  178.         }, null, new class() extends \Exception {
  179.         });
  180.         $this->debug $debug;
  181.     }
  182.     /**
  183.      * Sets a logger to non assigned errors levels.
  184.      *
  185.      * @param LoggerInterface $logger  A PSR-3 logger to put as default for the given levels
  186.      * @param array|int       $levels  An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  187.      * @param bool            $replace Whether to replace or not any existing logger
  188.      */
  189.     public function setDefaultLogger(LoggerInterface $logger$levels \E_ALLbool $replace false): void
  190.     {
  191.         $loggers = [];
  192.         if (\is_array($levels)) {
  193.             foreach ($levels as $type => $logLevel) {
  194.                 if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  195.                     $loggers[$type] = [$logger$logLevel];
  196.                 }
  197.             }
  198.         } else {
  199.             if (null === $levels) {
  200.                 $levels \E_ALL;
  201.             }
  202.             foreach ($this->loggers as $type => $log) {
  203.                 if (($type $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  204.                     $log[0] = $logger;
  205.                     $loggers[$type] = $log;
  206.                 }
  207.             }
  208.         }
  209.         $this->setLoggers($loggers);
  210.     }
  211.     /**
  212.      * Sets a logger for each error level.
  213.      *
  214.      * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  215.      *
  216.      * @return array The previous map
  217.      *
  218.      * @throws \InvalidArgumentException
  219.      */
  220.     public function setLoggers(array $loggers): array
  221.     {
  222.         $prevLogged $this->loggedErrors;
  223.         $prev $this->loggers;
  224.         $flush = [];
  225.         foreach ($loggers as $type => $log) {
  226.             if (!isset($prev[$type])) {
  227.                 throw new \InvalidArgumentException('Unknown error type: '.$type);
  228.             }
  229.             if (!\is_array($log)) {
  230.                 $log = [$log];
  231.             } elseif (!\array_key_exists(0$log)) {
  232.                 throw new \InvalidArgumentException('No logger provided.');
  233.             }
  234.             if (null === $log[0]) {
  235.                 $this->loggedErrors &= ~$type;
  236.             } elseif ($log[0] instanceof LoggerInterface) {
  237.                 $this->loggedErrors |= $type;
  238.             } else {
  239.                 throw new \InvalidArgumentException('Invalid logger provided.');
  240.             }
  241.             $this->loggers[$type] = $log $prev[$type];
  242.             if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  243.                 $flush[$type] = $type;
  244.             }
  245.         }
  246.         $this->reRegister($prevLogged $this->thrownErrors);
  247.         if ($flush) {
  248.             foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  249.                 $type ThrowableUtils::getSeverity($log[2]['exception']);
  250.                 if (!isset($flush[$type])) {
  251.                     $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  252.                 } elseif ($this->loggers[$type][0]) {
  253.                     $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  254.                 }
  255.             }
  256.         }
  257.         return $prev;
  258.     }
  259.     /**
  260.      * Sets a user exception handler.
  261.      *
  262.      * @param callable(\Throwable $e)|null $handler
  263.      *
  264.      * @return callable|null The previous exception handler
  265.      */
  266.     public function setExceptionHandler(?callable $handler): ?callable
  267.     {
  268.         $prev $this->exceptionHandler;
  269.         $this->exceptionHandler $handler;
  270.         return $prev;
  271.     }
  272.     /**
  273.      * Sets the PHP error levels that throw an exception when a PHP error occurs.
  274.      *
  275.      * @param int  $levels  A bit field of E_* constants for thrown errors
  276.      * @param bool $replace Replace or amend the previous value
  277.      *
  278.      * @return int The previous value
  279.      */
  280.     public function throwAt(int $levelsbool $replace false): int
  281.     {
  282.         $prev $this->thrownErrors;
  283.         $this->thrownErrors = ($levels \E_RECOVERABLE_ERROR \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED;
  284.         if (!$replace) {
  285.             $this->thrownErrors |= $prev;
  286.         }
  287.         $this->reRegister($prev $this->loggedErrors);
  288.         return $prev;
  289.     }
  290.     /**
  291.      * Sets the PHP error levels for which local variables are preserved.
  292.      *
  293.      * @param int  $levels  A bit field of E_* constants for scoped errors
  294.      * @param bool $replace Replace or amend the previous value
  295.      *
  296.      * @return int The previous value
  297.      */
  298.     public function scopeAt(int $levelsbool $replace false): int
  299.     {
  300.         $prev $this->scopedErrors;
  301.         $this->scopedErrors $levels;
  302.         if (!$replace) {
  303.             $this->scopedErrors |= $prev;
  304.         }
  305.         return $prev;
  306.     }
  307.     /**
  308.      * Sets the PHP error levels for which the stack trace is preserved.
  309.      *
  310.      * @param int  $levels  A bit field of E_* constants for traced errors
  311.      * @param bool $replace Replace or amend the previous value
  312.      *
  313.      * @return int The previous value
  314.      */
  315.     public function traceAt(int $levelsbool $replace false): int
  316.     {
  317.         $prev $this->tracedErrors;
  318.         $this->tracedErrors = (int) $levels;
  319.         if (!$replace) {
  320.             $this->tracedErrors |= $prev;
  321.         }
  322.         return $prev;
  323.     }
  324.     /**
  325.      * Sets the error levels where the @-operator is ignored.
  326.      *
  327.      * @param int  $levels  A bit field of E_* constants for screamed errors
  328.      * @param bool $replace Replace or amend the previous value
  329.      *
  330.      * @return int The previous value
  331.      */
  332.     public function screamAt(int $levelsbool $replace false): int
  333.     {
  334.         $prev $this->screamedErrors;
  335.         $this->screamedErrors $levels;
  336.         if (!$replace) {
  337.             $this->screamedErrors |= $prev;
  338.         }
  339.         return $prev;
  340.     }
  341.     /**
  342.      * Re-registers as a PHP error handler if levels changed.
  343.      */
  344.     private function reRegister(int $prev): void
  345.     {
  346.         if ($prev !== $this->thrownErrors $this->loggedErrors) {
  347.             $handler set_error_handler('var_dump');
  348.             $handler \is_array($handler) ? $handler[0] : null;
  349.             restore_error_handler();
  350.             if ($handler === $this) {
  351.                 restore_error_handler();
  352.                 if ($this->isRoot) {
  353.                     set_error_handler([$this'handleError'], $this->thrownErrors $this->loggedErrors);
  354.                 } else {
  355.                     set_error_handler([$this'handleError']);
  356.                 }
  357.             }
  358.         }
  359.     }
  360.     /**
  361.      * Handles errors by filtering then logging them according to the configured bit fields.
  362.      *
  363.      * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  364.      *
  365.      * @throws \ErrorException When $this->thrownErrors requests so
  366.      *
  367.      * @internal
  368.      */
  369.     public function handleError(int $typestring $messagestring $fileint $line): bool
  370.     {
  371.         if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message'" targeting switch is equivalent to "break')) {
  372.             $type \E_DEPRECATED;
  373.         }
  374.         // Level is the current error reporting level to manage silent error.
  375.         $level error_reporting();
  376.         $silenced === ($level $type);
  377.         // Strong errors are not authorized to be silenced.
  378.         $level |= \E_RECOVERABLE_ERROR \E_USER_ERROR \E_DEPRECATED \E_USER_DEPRECATED;
  379.         $log $this->loggedErrors $type;
  380.         $throw $this->thrownErrors $type $level;
  381.         $type &= $level $this->screamedErrors;
  382.         // Never throw on warnings triggered by assert()
  383.         if (\E_WARNING === $type && 'a' === $message[0] && === strncmp($message'assert(): '10)) {
  384.             $throw 0;
  385.         }
  386.         if (!$type || (!$log && !$throw)) {
  387.             return false;
  388.         }
  389.         if (false !== strpos($message"@anonymous\0")) {
  390.             $logMessage $this->parseAnonymousClass($message);
  391.         } else {
  392.             $logMessage $this->levels[$type].': '.$message;
  393.         }
  394.         if (null !== self::$toStringException) {
  395.             $errorAsException self::$toStringException;
  396.             self::$toStringException null;
  397.         } elseif (!$throw && !($type $level)) {
  398.             if (!isset(self::$silencedErrorCache[$id $file.':'.$line])) {
  399.                 $lightTrace $this->tracedErrors $type $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS5), $type$file$linefalse) : [];
  400.                 $errorAsException = new SilencedErrorContext($type$file$line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  401.             } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  402.                 $lightTrace null;
  403.                 $errorAsException self::$silencedErrorCache[$id][$message];
  404.                 ++$errorAsException->count;
  405.             } else {
  406.                 $lightTrace = [];
  407.                 $errorAsException null;
  408.             }
  409.             if (100 < ++self::$silencedErrorCount) {
  410.                 self::$silencedErrorCache $lightTrace = [];
  411.                 self::$silencedErrorCount 1;
  412.             }
  413.             if ($errorAsException) {
  414.                 self::$silencedErrorCache[$id][$message] = $errorAsException;
  415.             }
  416.             if (null === $lightTrace) {
  417.                 return true;
  418.             }
  419.         } else {
  420.             $errorAsException = new \ErrorException($logMessage0$type$file$line);
  421.             if ($throw || $this->tracedErrors $type) {
  422.                 $backtrace $errorAsException->getTrace();
  423.                 $lightTrace $this->cleanTrace($backtrace$type$file$line$throw);
  424.                 ($this->configureException)($errorAsException$lightTrace$file$line);
  425.             } else {
  426.                 ($this->configureException)($errorAsException, []);
  427.                 $backtrace = [];
  428.             }
  429.         }
  430.         if ($throw) {
  431.             if (\PHP_VERSION_ID 70400 && \E_USER_ERROR $type) {
  432.                 for ($i 1; isset($backtrace[$i]); ++$i) {
  433.                     if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i 1]['function'])
  434.                         && '__toString' === $backtrace[$i]['function']
  435.                         && '->' === $backtrace[$i]['type']
  436.                         && !isset($backtrace[$i 1]['class'])
  437.                         && ('trigger_error' === $backtrace[$i 1]['function'] || 'user_error' === $backtrace[$i 1]['function'])
  438.                     ) {
  439.                         // Here, we know trigger_error() has been called from __toString().
  440.                         // PHP triggers a fatal error when throwing from __toString().
  441.                         // A small convention allows working around the limitation:
  442.                         // given a caught $e exception in __toString(), quitting the method with
  443.                         // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  444.                         // to make $e get through the __toString() barrier.
  445.                         $context \func_num_args() ? (func_get_arg(4) ?: []) : [];
  446.                         foreach ($context as $e) {
  447.                             if ($e instanceof \Throwable && $e->__toString() === $message) {
  448.                                 self::$toStringException $e;
  449.                                 return true;
  450.                             }
  451.                         }
  452.                         // 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.             throw $errorAsException;
  460.         }
  461.         if ($this->isRecursive) {
  462.             $log 0;
  463.         } else {
  464.             if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404)) {
  465.                 $currentErrorHandler set_error_handler('var_dump');
  466.                 restore_error_handler();
  467.             }
  468.             try {
  469.                 $this->isRecursive true;
  470.                 $level = ($type $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  471.                 $this->loggers[$type][0]->log($level$logMessage$errorAsException ? ['exception' => $errorAsException] : []);
  472.             } finally {
  473.                 $this->isRecursive false;
  474.                 if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404)) {
  475.                     set_error_handler($currentErrorHandler);
  476.                 }
  477.             }
  478.         }
  479.         return !$silenced && $type && $log;
  480.     }
  481.     /**
  482.      * Handles an exception by logging then forwarding it to another handler.
  483.      *
  484.      * @internal
  485.      */
  486.     public function handleException(\Throwable $exception)
  487.     {
  488.         $handlerException null;
  489.         if (!$exception instanceof FatalError) {
  490.             self::$exitCode 255;
  491.             $type ThrowableUtils::getSeverity($exception);
  492.         } else {
  493.             $type $exception->getError()['type'];
  494.         }
  495.         if ($this->loggedErrors $type) {
  496.             if (false !== strpos($message $exception->getMessage(), "@anonymous\0")) {
  497.                 $message $this->parseAnonymousClass($message);
  498.             }
  499.             if ($exception instanceof FatalError) {
  500.                 $message 'Fatal '.$message;
  501.             } elseif ($exception instanceof \Error) {
  502.                 $message 'Uncaught Error: '.$message;
  503.             } elseif ($exception instanceof \ErrorException) {
  504.                 $message 'Uncaught '.$message;
  505.             } else {
  506.                 $message 'Uncaught Exception: '.$message;
  507.             }
  508.             try {
  509.                 $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  510.             } catch (\Throwable $handlerException) {
  511.             }
  512.         }
  513.         if (!$exception instanceof OutOfMemoryError) {
  514.             foreach ($this->getErrorEnhancers() as $errorEnhancer) {
  515.                 if ($e $errorEnhancer->enhance($exception)) {
  516.                     $exception $e;
  517.                     break;
  518.                 }
  519.             }
  520.         }
  521.         $exceptionHandler $this->exceptionHandler;
  522.         $this->exceptionHandler = [$this'renderException'];
  523.         if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) {
  524.             $this->exceptionHandler null;
  525.         }
  526.         try {
  527.             if (null !== $exceptionHandler) {
  528.                 return $exceptionHandler($exception);
  529.             }
  530.             $handlerException $handlerException ?: $exception;
  531.         } catch (\Throwable $handlerException) {
  532.         }
  533.         if ($exception === $handlerException && null === $this->exceptionHandler) {
  534.             self::$reservedMemory null// Disable the fatal error handler
  535.             throw $exception// Give back $exception to the native handler
  536.         }
  537.         $loggedErrors $this->loggedErrors;
  538.         $this->loggedErrors $exception === $handlerException $this->loggedErrors;
  539.         try {
  540.             $this->handleException($handlerException);
  541.         } finally {
  542.             $this->loggedErrors $loggedErrors;
  543.         }
  544.     }
  545.     /**
  546.      * Shutdown registered function for handling PHP fatal errors.
  547.      *
  548.      * @param array|null $error An array as returned by error_get_last()
  549.      *
  550.      * @internal
  551.      */
  552.     public static function handleFatalError(array $error null): void
  553.     {
  554.         if (null === self::$reservedMemory) {
  555.             return;
  556.         }
  557.         $handler self::$reservedMemory null;
  558.         $handlers = [];
  559.         $previousHandler null;
  560.         $sameHandlerLimit 10;
  561.         while (!\is_array($handler) || !$handler[0] instanceof self) {
  562.             $handler set_exception_handler('var_dump');
  563.             restore_exception_handler();
  564.             if (!$handler) {
  565.                 break;
  566.             }
  567.             restore_exception_handler();
  568.             if ($handler !== $previousHandler) {
  569.                 array_unshift($handlers$handler);
  570.                 $previousHandler $handler;
  571.             } elseif (=== --$sameHandlerLimit) {
  572.                 $handler null;
  573.                 break;
  574.             }
  575.         }
  576.         foreach ($handlers as $h) {
  577.             set_exception_handler($h);
  578.         }
  579.         if (!$handler) {
  580.             return;
  581.         }
  582.         if ($handler !== $h) {
  583.             $handler[0]->setExceptionHandler($h);
  584.         }
  585.         $handler $handler[0];
  586.         $handlers = [];
  587.         if ($exit null === $error) {
  588.             $error error_get_last();
  589.         }
  590.         if ($error && $error['type'] &= \E_PARSE \E_ERROR \E_CORE_ERROR \E_COMPILE_ERROR) {
  591.             // Let's not throw anymore but keep logging
  592.             $handler->throwAt(0true);
  593.             $trace $error['backtrace'] ?? null;
  594.             if (=== strpos($error['message'], 'Allowed memory') || === strpos($error['message'], 'Out of memory')) {
  595.                 $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0$error2false$trace);
  596.             } else {
  597.                 $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0$error2true$trace);
  598.             }
  599.         } else {
  600.             $fatalError null;
  601.         }
  602.         try {
  603.             if (null !== $fatalError) {
  604.                 self::$exitCode 255;
  605.                 $handler->handleException($fatalError);
  606.             }
  607.         } catch (FatalError $e) {
  608.             // Ignore this re-throw
  609.         }
  610.         if ($exit && self::$exitCode) {
  611.             $exitCode self::$exitCode;
  612.             register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  613.         }
  614.     }
  615.     /**
  616.      * Renders the given exception.
  617.      *
  618.      * As this method is mainly called during boot where nothing is yet available,
  619.      * the output is always either HTML or CLI depending where PHP runs.
  620.      */
  621.     private function renderException(\Throwable $exception): void
  622.     {
  623.         $renderer \in_array(\PHP_SAPI, ['cli''phpdbg'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug);
  624.         $exception $renderer->render($exception);
  625.         if (!headers_sent()) {
  626.             http_response_code($exception->getStatusCode());
  627.             foreach ($exception->getHeaders() as $name => $value) {
  628.                 header($name.': '.$valuefalse);
  629.             }
  630.         }
  631.         echo $exception->getAsString();
  632.     }
  633.     /**
  634.      * Override this method if you want to define more error enhancers.
  635.      *
  636.      * @return ErrorEnhancerInterface[]
  637.      */
  638.     protected function getErrorEnhancers(): iterable
  639.     {
  640.         return [
  641.             new UndefinedFunctionErrorEnhancer(),
  642.             new UndefinedMethodErrorEnhancer(),
  643.             new ClassNotFoundErrorEnhancer(),
  644.         ];
  645.     }
  646.     /**
  647.      * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  648.      */
  649.     private function cleanTrace(array $backtraceint $typestring &$fileint &$linebool $throw): array
  650.     {
  651.         $lightTrace $backtrace;
  652.         for ($i 0; isset($backtrace[$i]); ++$i) {
  653.             if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  654.                 $lightTrace \array_slice($lightTrace$i);
  655.                 break;
  656.             }
  657.         }
  658.         if (\E_USER_DEPRECATED === $type) {
  659.             for ($i 0; isset($lightTrace[$i]); ++$i) {
  660.                 if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) {
  661.                     continue;
  662.                 }
  663.                 if (!isset($lightTrace[$i]['class']) && 'trigger_deprecation' === $lightTrace[$i]['function']) {
  664.                     $file $lightTrace[$i]['file'];
  665.                     $line $lightTrace[$i]['line'];
  666.                     $lightTrace \array_slice($lightTrace$i);
  667.                     break;
  668.                 }
  669.             }
  670.         }
  671.         if (class_exists(DebugClassLoader::class, false)) {
  672.             for ($i \count($lightTrace) - 2$i; --$i) {
  673.                 if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  674.                     array_splice($lightTrace, --$i2);
  675.                 }
  676.             }
  677.         }
  678.         if (!($throw || $this->scopedErrors $type)) {
  679.             for ($i 0; isset($lightTrace[$i]); ++$i) {
  680.                 unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  681.             }
  682.         }
  683.         return $lightTrace;
  684.     }
  685.     /**
  686.      * Parse the error message by removing the anonymous class notation
  687.      * and using the parent class instead if possible.
  688.      */
  689.     private function parseAnonymousClass(string $message): string
  690.     {
  691.         return preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', static function ($m) {
  692.             return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' $m[0];
  693.         }, $message);
  694.     }
  695. }