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

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