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

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 $traceReflector;
  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.         $this->traceReflector = new \ReflectionProperty('Exception''trace');
  173.         $this->traceReflector->setAccessible(true);
  174.         $this->debug $debug;
  175.     }
  176.     /**
  177.      * Sets a logger to non assigned errors levels.
  178.      *
  179.      * @param LoggerInterface $logger  A PSR-3 logger to put as default for the given levels
  180.      * @param array|int       $levels  An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  181.      * @param bool            $replace Whether to replace or not any existing logger
  182.      */
  183.     public function setDefaultLogger(LoggerInterface $logger$levels E_ALLbool $replace false): void
  184.     {
  185.         $loggers = [];
  186.         if (\is_array($levels)) {
  187.             foreach ($levels as $type => $logLevel) {
  188.                 if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  189.                     $loggers[$type] = [$logger$logLevel];
  190.                 }
  191.             }
  192.         } else {
  193.             if (null === $levels) {
  194.                 $levels E_ALL;
  195.             }
  196.             foreach ($this->loggers as $type => $log) {
  197.                 if (($type $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  198.                     $log[0] = $logger;
  199.                     $loggers[$type] = $log;
  200.                 }
  201.             }
  202.         }
  203.         $this->setLoggers($loggers);
  204.     }
  205.     /**
  206.      * Sets a logger for each error level.
  207.      *
  208.      * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  209.      *
  210.      * @return array The previous map
  211.      *
  212.      * @throws \InvalidArgumentException
  213.      */
  214.     public function setLoggers(array $loggers): array
  215.     {
  216.         $prevLogged $this->loggedErrors;
  217.         $prev $this->loggers;
  218.         $flush = [];
  219.         foreach ($loggers as $type => $log) {
  220.             if (!isset($prev[$type])) {
  221.                 throw new \InvalidArgumentException('Unknown error type: '.$type);
  222.             }
  223.             if (!\is_array($log)) {
  224.                 $log = [$log];
  225.             } elseif (!\array_key_exists(0$log)) {
  226.                 throw new \InvalidArgumentException('No logger provided.');
  227.             }
  228.             if (null === $log[0]) {
  229.                 $this->loggedErrors &= ~$type;
  230.             } elseif ($log[0] instanceof LoggerInterface) {
  231.                 $this->loggedErrors |= $type;
  232.             } else {
  233.                 throw new \InvalidArgumentException('Invalid logger provided.');
  234.             }
  235.             $this->loggers[$type] = $log $prev[$type];
  236.             if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  237.                 $flush[$type] = $type;
  238.             }
  239.         }
  240.         $this->reRegister($prevLogged $this->thrownErrors);
  241.         if ($flush) {
  242.             foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  243.                 $type ThrowableUtils::getSeverity($log[2]['exception']);
  244.                 if (!isset($flush[$type])) {
  245.                     $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  246.                 } elseif ($this->loggers[$type][0]) {
  247.                     $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  248.                 }
  249.             }
  250.         }
  251.         return $prev;
  252.     }
  253.     /**
  254.      * Sets a user exception handler.
  255.      *
  256.      * @param callable(\Throwable $e)|null $handler
  257.      *
  258.      * @return callable|null The previous exception handler
  259.      */
  260.     public function setExceptionHandler(?callable $handler): ?callable
  261.     {
  262.         $prev $this->exceptionHandler;
  263.         $this->exceptionHandler $handler;
  264.         return $prev;
  265.     }
  266.     /**
  267.      * Sets the PHP error levels that throw an exception when a PHP error occurs.
  268.      *
  269.      * @param int  $levels  A bit field of E_* constants for thrown errors
  270.      * @param bool $replace Replace or amend the previous value
  271.      *
  272.      * @return int The previous value
  273.      */
  274.     public function throwAt(int $levelsbool $replace false): int
  275.     {
  276.         $prev $this->thrownErrors;
  277.         $this->thrownErrors = ($levels E_RECOVERABLE_ERROR E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
  278.         if (!$replace) {
  279.             $this->thrownErrors |= $prev;
  280.         }
  281.         $this->reRegister($prev $this->loggedErrors);
  282.         return $prev;
  283.     }
  284.     /**
  285.      * Sets the PHP error levels for which local variables are preserved.
  286.      *
  287.      * @param int  $levels  A bit field of E_* constants for scoped errors
  288.      * @param bool $replace Replace or amend the previous value
  289.      *
  290.      * @return int The previous value
  291.      */
  292.     public function scopeAt(int $levelsbool $replace false): int
  293.     {
  294.         $prev $this->scopedErrors;
  295.         $this->scopedErrors $levels;
  296.         if (!$replace) {
  297.             $this->scopedErrors |= $prev;
  298.         }
  299.         return $prev;
  300.     }
  301.     /**
  302.      * Sets the PHP error levels for which the stack trace is preserved.
  303.      *
  304.      * @param int  $levels  A bit field of E_* constants for traced errors
  305.      * @param bool $replace Replace or amend the previous value
  306.      *
  307.      * @return int The previous value
  308.      */
  309.     public function traceAt(int $levelsbool $replace false): int
  310.     {
  311.         $prev $this->tracedErrors;
  312.         $this->tracedErrors = (int) $levels;
  313.         if (!$replace) {
  314.             $this->tracedErrors |= $prev;
  315.         }
  316.         return $prev;
  317.     }
  318.     /**
  319.      * Sets the error levels where the @-operator is ignored.
  320.      *
  321.      * @param int  $levels  A bit field of E_* constants for screamed errors
  322.      * @param bool $replace Replace or amend the previous value
  323.      *
  324.      * @return int The previous value
  325.      */
  326.     public function screamAt(int $levelsbool $replace false): int
  327.     {
  328.         $prev $this->screamedErrors;
  329.         $this->screamedErrors $levels;
  330.         if (!$replace) {
  331.             $this->screamedErrors |= $prev;
  332.         }
  333.         return $prev;
  334.     }
  335.     /**
  336.      * Re-registers as a PHP error handler if levels changed.
  337.      */
  338.     private function reRegister(int $prev): void
  339.     {
  340.         if ($prev !== $this->thrownErrors $this->loggedErrors) {
  341.             $handler set_error_handler('var_dump');
  342.             $handler = \is_array($handler) ? $handler[0] : null;
  343.             restore_error_handler();
  344.             if ($handler === $this) {
  345.                 restore_error_handler();
  346.                 if ($this->isRoot) {
  347.                     set_error_handler([$this'handleError'], $this->thrownErrors $this->loggedErrors);
  348.                 } else {
  349.                     set_error_handler([$this'handleError']);
  350.                 }
  351.             }
  352.         }
  353.     }
  354.     /**
  355.      * Handles errors by filtering then logging them according to the configured bit fields.
  356.      *
  357.      * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  358.      *
  359.      * @throws \ErrorException When $this->thrownErrors requests so
  360.      *
  361.      * @internal
  362.      */
  363.     public function handleError(int $typestring $messagestring $fileint $line): bool
  364.     {
  365.         if (\PHP_VERSION_ID >= 70300 && E_WARNING === $type && '"' === $message[0] && false !== strpos($message'" targeting switch is equivalent to "break')) {
  366.             $type E_DEPRECATED;
  367.         }
  368.         // Level is the current error reporting level to manage silent error.
  369.         $level error_reporting();
  370.         $silenced === ($level $type);
  371.         // Strong errors are not authorized to be silenced.
  372.         $level |= E_RECOVERABLE_ERROR E_USER_ERROR E_DEPRECATED E_USER_DEPRECATED;
  373.         $log $this->loggedErrors $type;
  374.         $throw $this->thrownErrors $type $level;
  375.         $type &= $level $this->screamedErrors;
  376.         // Never throw on warnings triggered by assert()
  377.         if (E_WARNING === $type && 'a' === $message[0] && === strncmp($message'assert(): '10)) {
  378.             $throw 0;
  379.         }
  380.         if (!$type || (!$log && !$throw)) {
  381.             return !$silenced && $type && $log;
  382.         }
  383.         $scope $this->scopedErrors $type;
  384.         if (false !== strpos($message"@anonymous\0")) {
  385.             $logMessage $this->parseAnonymousClass($message);
  386.         } else {
  387.             $logMessage $this->levels[$type].': '.$message;
  388.         }
  389.         if (null !== self::$toStringException) {
  390.             $errorAsException self::$toStringException;
  391.             self::$toStringException null;
  392.         } elseif (!$throw && !($type $level)) {
  393.             if (!isset(self::$silencedErrorCache[$id $file.':'.$line])) {
  394.                 $lightTrace $this->tracedErrors $type $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS5), $type$file$linefalse) : [];
  395.                 $errorAsException = new SilencedErrorContext($type$file$line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  396.             } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  397.                 $lightTrace null;
  398.                 $errorAsException self::$silencedErrorCache[$id][$message];
  399.                 ++$errorAsException->count;
  400.             } else {
  401.                 $lightTrace = [];
  402.                 $errorAsException null;
  403.             }
  404.             if (100 < ++self::$silencedErrorCount) {
  405.                 self::$silencedErrorCache $lightTrace = [];
  406.                 self::$silencedErrorCount 1;
  407.             }
  408.             if ($errorAsException) {
  409.                 self::$silencedErrorCache[$id][$message] = $errorAsException;
  410.             }
  411.             if (null === $lightTrace) {
  412.                 return true;
  413.             }
  414.         } else {
  415.             $errorAsException = new \ErrorException($logMessage0$type$file$line);
  416.             if ($throw || $this->tracedErrors $type) {
  417.                 $backtrace $errorAsException->getTrace();
  418.                 $lightTrace $this->cleanTrace($backtrace$type$file$line$throw);
  419.                 $this->traceReflector->setValue($errorAsException$lightTrace);
  420.             } else {
  421.                 $this->traceReflector->setValue($errorAsException, []);
  422.                 $backtrace = [];
  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.                         // PHP triggers a fatal error when throwing from __toString().
  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.                         $context < \func_num_args() ? (func_get_arg(4) ?: []) : [];
  441.                         foreach ($context as $e) {
  442.                             if ($e instanceof \Throwable && $e->__toString() === $message) {
  443.                                 self::$toStringException $e;
  444.                                 return true;
  445.                             }
  446.                         }
  447.                         // Display the original error message instead of the default one.
  448.                         $this->handleException($errorAsException);
  449.                         // Stop the process by giving back the error to the native handler.
  450.                         return false;
  451.                     }
  452.                 }
  453.             }
  454.             throw $errorAsException;
  455.         }
  456.         if ($this->isRecursive) {
  457.             $log 0;
  458.         } else {
  459.             if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404)) {
  460.                 $currentErrorHandler set_error_handler('var_dump');
  461.                 restore_error_handler();
  462.             }
  463.             try {
  464.                 $this->isRecursive true;
  465.                 $level = ($type $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  466.                 $this->loggers[$type][0]->log($level$logMessage$errorAsException ? ['exception' => $errorAsException] : []);
  467.             } finally {
  468.                 $this->isRecursive false;
  469.                 if (\PHP_VERSION_ID < (\PHP_VERSION_ID 70400 70316 70404)) {
  470.                     set_error_handler($currentErrorHandler);
  471.                 }
  472.             }
  473.         }
  474.         return !$silenced && $type && $log;
  475.     }
  476.     /**
  477.      * Handles an exception by logging then forwarding it to another handler.
  478.      *
  479.      * @internal
  480.      */
  481.     public function handleException(\Throwable $exception)
  482.     {
  483.         $handlerException null;
  484.         if (!$exception instanceof FatalError) {
  485.             self::$exitCode 255;
  486.             $type ThrowableUtils::getSeverity($exception);
  487.         } else {
  488.             $type $exception->getError()['type'];
  489.         }
  490.         if ($this->loggedErrors $type) {
  491.             if (false !== strpos($message $exception->getMessage(), "@anonymous\0")) {
  492.                 $message $this->parseAnonymousClass($message);
  493.             }
  494.             if ($exception instanceof FatalError) {
  495.                 $message 'Fatal '.$message;
  496.             } elseif ($exception instanceof \Error) {
  497.                 $message 'Uncaught Error: '.$message;
  498.             } elseif ($exception instanceof \ErrorException) {
  499.                 $message 'Uncaught '.$message;
  500.             } else {
  501.                 $message 'Uncaught Exception: '.$message;
  502.             }
  503.             try {
  504.                 $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  505.             } catch (\Throwable $handlerException) {
  506.             }
  507.         }
  508.         if (!$exception instanceof OutOfMemoryError) {
  509.             foreach ($this->getErrorEnhancers() as $errorEnhancer) {
  510.                 if ($e $errorEnhancer->enhance($exception)) {
  511.                     $exception $e;
  512.                     break;
  513.                 }
  514.             }
  515.         }
  516.         $exceptionHandler $this->exceptionHandler;
  517.         $this->exceptionHandler = [$this'renderException'];
  518.         if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) {
  519.             $this->exceptionHandler null;
  520.         }
  521.         try {
  522.             if (null !== $exceptionHandler) {
  523.                 return $exceptionHandler($exception);
  524.             }
  525.             $handlerException $handlerException ?: $exception;
  526.         } catch (\Throwable $handlerException) {
  527.         }
  528.         if ($exception === $handlerException && null === $this->exceptionHandler) {
  529.             self::$reservedMemory null// Disable the fatal error handler
  530.             throw $exception// Give back $exception to the native handler
  531.         }
  532.         $loggedErrors $this->loggedErrors;
  533.         $this->loggedErrors $exception === $handlerException $this->loggedErrors;
  534.         try {
  535.             $this->handleException($handlerException);
  536.         } finally {
  537.             $this->loggedErrors $loggedErrors;
  538.         }
  539.     }
  540.     /**
  541.      * Shutdown registered function for handling PHP fatal errors.
  542.      *
  543.      * @param array|null $error An array as returned by error_get_last()
  544.      *
  545.      * @internal
  546.      */
  547.     public static function handleFatalError(array $error null): void
  548.     {
  549.         if (null === self::$reservedMemory) {
  550.             return;
  551.         }
  552.         $handler self::$reservedMemory null;
  553.         $handlers = [];
  554.         $previousHandler null;
  555.         $sameHandlerLimit 10;
  556.         while (!\is_array($handler) || !$handler[0] instanceof self) {
  557.             $handler set_exception_handler('var_dump');
  558.             restore_exception_handler();
  559.             if (!$handler) {
  560.                 break;
  561.             }
  562.             restore_exception_handler();
  563.             if ($handler !== $previousHandler) {
  564.                 array_unshift($handlers$handler);
  565.                 $previousHandler $handler;
  566.             } elseif (=== --$sameHandlerLimit) {
  567.                 $handler null;
  568.                 break;
  569.             }
  570.         }
  571.         foreach ($handlers as $h) {
  572.             set_exception_handler($h);
  573.         }
  574.         if (!$handler) {
  575.             return;
  576.         }
  577.         if ($handler !== $h) {
  578.             $handler[0]->setExceptionHandler($h);
  579.         }
  580.         $handler $handler[0];
  581.         $handlers = [];
  582.         if ($exit null === $error) {
  583.             $error error_get_last();
  584.         }
  585.         if ($error && $error['type'] &= E_PARSE E_ERROR E_CORE_ERROR E_COMPILE_ERROR) {
  586.             // Let's not throw anymore but keep logging
  587.             $handler->throwAt(0true);
  588.             $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  589.             if (=== strpos($error['message'], 'Allowed memory') || === strpos($error['message'], 'Out of memory')) {
  590.                 $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0$error2false$trace);
  591.             } else {
  592.                 $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0$error2true$trace);
  593.             }
  594.         } else {
  595.             $fatalError null;
  596.         }
  597.         try {
  598.             if (null !== $fatalError) {
  599.                 self::$exitCode 255;
  600.                 $handler->handleException($fatalError);
  601.             }
  602.         } catch (FatalError $e) {
  603.             // Ignore this re-throw
  604.         }
  605.         if ($exit && self::$exitCode) {
  606.             $exitCode self::$exitCode;
  607.             register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  608.         }
  609.     }
  610.     /**
  611.      * Renders the given exception.
  612.      *
  613.      * As this method is mainly called during boot where nothing is yet available,
  614.      * the output is always either HTML or CLI depending where PHP runs.
  615.      */
  616.     private function renderException(\Throwable $exception): void
  617.     {
  618.         $renderer = \in_array(\PHP_SAPI, ['cli''phpdbg'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug);
  619.         $exception $renderer->render($exception);
  620.         if (!headers_sent()) {
  621.             http_response_code($exception->getStatusCode());
  622.             foreach ($exception->getHeaders() as $name => $value) {
  623.                 header($name.': '.$valuefalse);
  624.             }
  625.         }
  626.         echo $exception->getAsString();
  627.     }
  628.     /**
  629.      * Override this method if you want to define more error enhancers.
  630.      *
  631.      * @return ErrorEnhancerInterface[]
  632.      */
  633.     protected function getErrorEnhancers(): iterable
  634.     {
  635.         return [
  636.             new UndefinedFunctionErrorEnhancer(),
  637.             new UndefinedMethodErrorEnhancer(),
  638.             new ClassNotFoundErrorEnhancer(),
  639.         ];
  640.     }
  641.     /**
  642.      * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  643.      */
  644.     private function cleanTrace(array $backtraceint $typestring $fileint $linebool $throw): array
  645.     {
  646.         $lightTrace $backtrace;
  647.         for ($i 0; isset($backtrace[$i]); ++$i) {
  648.             if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  649.                 $lightTrace = \array_slice($lightTrace$i);
  650.                 break;
  651.             }
  652.         }
  653.         if (class_exists(DebugClassLoader::class, false)) {
  654.             for ($i = \count($lightTrace) - 2$i; --$i) {
  655.                 if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  656.                     array_splice($lightTrace, --$i2);
  657.                 }
  658.             }
  659.         }
  660.         if (!($throw || $this->scopedErrors $type)) {
  661.             for ($i 0; isset($lightTrace[$i]); ++$i) {
  662.                 unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  663.             }
  664.         }
  665.         return $lightTrace;
  666.     }
  667.     /**
  668.      * Parse the error message by removing the anonymous class notation
  669.      * and using the parent class instead if possible.
  670.      */
  671.     private function parseAnonymousClass(string $message): string
  672.     {
  673.         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) {
  674.             return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' $m[0];
  675.         }, $message);
  676.     }
  677. }