ErrorHandler.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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_WARNING => 'Warning',
  55. \E_USER_WARNING => 'User Warning',
  56. \E_COMPILE_WARNING => 'Compile Warning',
  57. \E_CORE_WARNING => 'Core Warning',
  58. \E_USER_ERROR => 'User Error',
  59. \E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  60. \E_COMPILE_ERROR => 'Compile Error',
  61. \E_PARSE => 'Parse Error',
  62. \E_ERROR => 'Error',
  63. \E_CORE_ERROR => 'Core Error',
  64. ];
  65. private array $loggers = [
  66. \E_DEPRECATED => [null, LogLevel::INFO],
  67. \E_USER_DEPRECATED => [null, LogLevel::INFO],
  68. \E_NOTICE => [null, LogLevel::ERROR],
  69. \E_USER_NOTICE => [null, LogLevel::ERROR],
  70. \E_WARNING => [null, LogLevel::ERROR],
  71. \E_USER_WARNING => [null, LogLevel::ERROR],
  72. \E_COMPILE_WARNING => [null, LogLevel::ERROR],
  73. \E_CORE_WARNING => [null, LogLevel::ERROR],
  74. \E_USER_ERROR => [null, LogLevel::CRITICAL],
  75. \E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL],
  76. \E_COMPILE_ERROR => [null, LogLevel::CRITICAL],
  77. \E_PARSE => [null, LogLevel::CRITICAL],
  78. \E_ERROR => [null, LogLevel::CRITICAL],
  79. \E_CORE_ERROR => [null, LogLevel::CRITICAL],
  80. ];
  81. private int $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  82. private int $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  83. private int $tracedErrors = 0x77FB; // E_ALL - E_STRICT - E_PARSE
  84. private int $screamedErrors = 0x55; // E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
  85. private int $loggedErrors = 0;
  86. private \Closure $configureException;
  87. private bool $isRecursive = false;
  88. private bool $isRoot = false;
  89. /** @var callable|null */
  90. private $exceptionHandler;
  91. private ?BufferingLogger $bootstrappingLogger = null;
  92. private static ?string $reservedMemory = null;
  93. private static array $silencedErrorCache = [];
  94. private static int $silencedErrorCount = 0;
  95. private static int $exitCode = 0;
  96. /**
  97. * Registers the error handler.
  98. */
  99. public static function register(?self $handler = null, bool $replace = true): self
  100. {
  101. if (null === self::$reservedMemory) {
  102. self::$reservedMemory = str_repeat('x', 32768);
  103. register_shutdown_function(self::handleFatalError(...));
  104. }
  105. if ($handlerIsNew = null === $handler) {
  106. $handler = new static();
  107. }
  108. if (null === $prev = get_error_handler()) {
  109. // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  110. set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors);
  111. $handler->isRoot = true;
  112. } else {
  113. set_error_handler([$handler, 'handleError']);
  114. }
  115. if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
  116. $handler = $prev[0];
  117. $replace = false;
  118. }
  119. if (!$replace && $prev) {
  120. restore_error_handler();
  121. $handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
  122. } else {
  123. $handlerIsRegistered = true;
  124. }
  125. if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) {
  126. restore_exception_handler();
  127. if (!$handlerIsRegistered) {
  128. $handler = $prev[0];
  129. } elseif ($handler !== $prev[0] && $replace) {
  130. set_exception_handler([$handler, 'handleException']);
  131. $p = $prev[0]->setExceptionHandler(null);
  132. $handler->setExceptionHandler($p);
  133. $prev[0]->setExceptionHandler($p);
  134. }
  135. } else {
  136. $handler->setExceptionHandler($prev ?? [$handler, 'renderException']);
  137. }
  138. $handler->throwAt(\E_ALL & $handler->thrownErrors, true);
  139. return $handler;
  140. }
  141. /**
  142. * Calls a function and turns any PHP error into \ErrorException.
  143. *
  144. * @throws \ErrorException When $function(...$arguments) triggers a PHP error
  145. */
  146. public static function call(callable $function, mixed ...$arguments): mixed
  147. {
  148. set_error_handler(static function (int $type, string $message, string $file, int $line) {
  149. if (__FILE__ === $file) {
  150. $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  151. $file = $trace[2]['file'] ?? $file;
  152. $line = $trace[2]['line'] ?? $line;
  153. }
  154. throw new \ErrorException($message, 0, $type, $file, $line);
  155. });
  156. try {
  157. return $function(...$arguments);
  158. } finally {
  159. restore_error_handler();
  160. }
  161. }
  162. public function __construct(
  163. ?BufferingLogger $bootstrappingLogger = null,
  164. private bool $debug = false,
  165. ) {
  166. if ($bootstrappingLogger) {
  167. $this->bootstrappingLogger = $bootstrappingLogger;
  168. $this->setDefaultLogger($bootstrappingLogger);
  169. }
  170. $traceReflector = new \ReflectionProperty(\Exception::class, 'trace');
  171. $this->configureException = \Closure::bind(static function ($e, $trace, $file = null, $line = null) use ($traceReflector) {
  172. $traceReflector->setValue($e, $trace);
  173. $e->file = $file ?? $e->file;
  174. $e->line = $line ?? $e->line;
  175. }, null, new class extends \Exception {
  176. });
  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_ALL, bool $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 $levels, bool $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 $levels, bool $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 $levels, bool $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 $levels, bool $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 = get_error_handler();
  325. $handler = \is_array($handler) ? $handler[0] : null;
  326. if ($handler === $this) {
  327. restore_error_handler();
  328. if ($this->isRoot) {
  329. set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors);
  330. } else {
  331. set_error_handler([$this, 'handleError']);
  332. }
  333. }
  334. }
  335. }
  336. /**
  337. * Handles errors by filtering then logging them according to the configured bit fields.
  338. *
  339. * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  340. *
  341. * @throws \ErrorException When $this->thrownErrors requests so
  342. *
  343. * @internal
  344. */
  345. public function handleError(int $type, string $message, string $file, int $line): bool
  346. {
  347. if (\E_WARNING === $type && '"' === $message[0] && str_contains($message, '" targeting switch is equivalent to "break')) {
  348. $type = \E_DEPRECATED;
  349. }
  350. // Level is the current error reporting level to manage silent error.
  351. $level = error_reporting();
  352. $silenced = 0 === ($level & $type);
  353. // Strong errors are not authorized to be silenced.
  354. $level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED;
  355. $log = $this->loggedErrors & $type;
  356. $throw = $this->thrownErrors & $type & $level;
  357. $type &= $level | $this->screamedErrors;
  358. // Never throw on warnings triggered by assert()
  359. if (\E_WARNING === $type && 'a' === $message[0] && 0 === strncmp($message, 'assert(): ', 10)) {
  360. $throw = 0;
  361. }
  362. if (!$type || (!$log && !$throw)) {
  363. return false;
  364. }
  365. $logMessage = $this->levels[$type].': '.$message;
  366. if (!$throw && !($type & $level)) {
  367. if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) {
  368. $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : [];
  369. $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  370. } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  371. $lightTrace = null;
  372. $errorAsException = self::$silencedErrorCache[$id][$message];
  373. ++$errorAsException->count;
  374. } else {
  375. $lightTrace = [];
  376. $errorAsException = null;
  377. }
  378. if (100 < ++self::$silencedErrorCount) {
  379. self::$silencedErrorCache = $lightTrace = [];
  380. self::$silencedErrorCount = 1;
  381. }
  382. if ($errorAsException) {
  383. self::$silencedErrorCache[$id][$message] = $errorAsException;
  384. }
  385. if (null === $lightTrace) {
  386. return true;
  387. }
  388. } else {
  389. if (str_contains($message, "@anonymous\0")) {
  390. $message = $this->parseAnonymousClass($message);
  391. $logMessage = $this->levels[$type].': '.$message;
  392. }
  393. $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
  394. if ($throw || $this->tracedErrors & $type) {
  395. $backtrace = $errorAsException->getTrace();
  396. $backtrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
  397. ($this->configureException)($errorAsException, $backtrace, $file, $line);
  398. } else {
  399. ($this->configureException)($errorAsException, []);
  400. }
  401. }
  402. if ($throw) {
  403. throw $errorAsException;
  404. }
  405. if ($this->isRecursive) {
  406. $log = 0;
  407. } else {
  408. try {
  409. $this->isRecursive = true;
  410. $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  411. $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []);
  412. } finally {
  413. $this->isRecursive = false;
  414. }
  415. }
  416. return !$silenced && $type && $log;
  417. }
  418. /**
  419. * Handles an exception by logging then forwarding it to another handler.
  420. *
  421. * @internal
  422. */
  423. public function handleException(\Throwable $exception): void
  424. {
  425. $handlerException = null;
  426. if (!$exception instanceof FatalError) {
  427. self::$exitCode = 255;
  428. $type = ThrowableUtils::getSeverity($exception);
  429. } else {
  430. $type = $exception->getError()['type'];
  431. }
  432. if ($this->loggedErrors & $type) {
  433. if (str_contains($message = $exception->getMessage(), "@anonymous\0")) {
  434. $message = $this->parseAnonymousClass($message);
  435. }
  436. if ($exception instanceof FatalError) {
  437. $message = 'Fatal '.$message;
  438. } elseif ($exception instanceof \Error) {
  439. $message = 'Uncaught Error: '.$message;
  440. } elseif ($exception instanceof \ErrorException) {
  441. $message = 'Uncaught '.$message;
  442. } else {
  443. $message = 'Uncaught Exception: '.$message;
  444. }
  445. try {
  446. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  447. } catch (\Throwable $handlerException) {
  448. }
  449. }
  450. $exception = $this->enhanceError($exception);
  451. $exceptionHandler = $this->exceptionHandler;
  452. $this->exceptionHandler = [$this, 'renderException'];
  453. if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) {
  454. $this->exceptionHandler = null;
  455. }
  456. try {
  457. if (null !== $exceptionHandler) {
  458. $exceptionHandler($exception);
  459. return;
  460. }
  461. $handlerException ??= $exception;
  462. } catch (\Throwable $handlerException) {
  463. }
  464. if ($exception === $handlerException && null === $this->exceptionHandler) {
  465. self::$reservedMemory = null; // Disable the fatal error handler
  466. throw $exception; // Give back $exception to the native handler
  467. }
  468. $loggedErrors = $this->loggedErrors;
  469. if ($exception === $handlerException) {
  470. $this->loggedErrors &= ~$type;
  471. }
  472. try {
  473. $this->handleException($handlerException);
  474. } finally {
  475. $this->loggedErrors = $loggedErrors;
  476. }
  477. }
  478. /**
  479. * Shutdown registered function for handling PHP fatal errors.
  480. *
  481. * @param array|null $error An array as returned by error_get_last()
  482. *
  483. * @internal
  484. */
  485. public static function handleFatalError(?array $error = null): void
  486. {
  487. if (null === self::$reservedMemory) {
  488. return;
  489. }
  490. $handler = self::$reservedMemory = null;
  491. $handlers = [];
  492. $previousHandler = null;
  493. $sameHandlerLimit = 10;
  494. while (!\is_array($handler) || !$handler[0] instanceof self) {
  495. $handler = set_exception_handler('is_int');
  496. restore_exception_handler();
  497. if (!$handler) {
  498. break;
  499. }
  500. restore_exception_handler();
  501. if ($handler !== $previousHandler) {
  502. array_unshift($handlers, $handler);
  503. $previousHandler = $handler;
  504. } elseif (0 === --$sameHandlerLimit) {
  505. $handler = null;
  506. break;
  507. }
  508. }
  509. foreach ($handlers as $h) {
  510. set_exception_handler($h);
  511. }
  512. if (!$handler) {
  513. if (null === $error && $exitCode = self::$exitCode) {
  514. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  515. }
  516. return;
  517. }
  518. if ($handler !== $h) {
  519. $handler[0]->setExceptionHandler($h);
  520. }
  521. $handler = $handler[0];
  522. $handlers = [];
  523. if ($exit = null === $error) {
  524. $error = error_get_last();
  525. }
  526. if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) {
  527. // Let's not throw anymore but keep logging
  528. $handler->throwAt(0, true);
  529. $trace = $error['backtrace'] ?? null;
  530. if (str_starts_with($error['message'], 'Allowed memory') || str_starts_with($error['message'], 'Out of memory')) {
  531. $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, false, $trace);
  532. } else {
  533. $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, true, $trace);
  534. }
  535. } else {
  536. $fatalError = null;
  537. }
  538. try {
  539. if (null !== $fatalError) {
  540. self::$exitCode = 255;
  541. $handler->handleException($fatalError);
  542. }
  543. } catch (FatalError) {
  544. // Ignore this re-throw
  545. }
  546. if ($exit && $exitCode = self::$exitCode) {
  547. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  548. }
  549. }
  550. /**
  551. * Renders the given exception.
  552. *
  553. * As this method is mainly called during boot where nothing is yet available,
  554. * the output is always either HTML or CLI depending where PHP runs.
  555. */
  556. private function renderException(\Throwable $exception): void
  557. {
  558. $renderer = \in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug);
  559. $exception = $renderer->render($exception);
  560. if (!headers_sent()) {
  561. http_response_code($exception->getStatusCode());
  562. foreach ($exception->getHeaders() as $name => $value) {
  563. header($name.': '.$value, false);
  564. }
  565. }
  566. echo $exception->getAsString();
  567. }
  568. public function enhanceError(\Throwable $exception): \Throwable
  569. {
  570. if ($exception instanceof OutOfMemoryError) {
  571. return $exception;
  572. }
  573. foreach ($this->getErrorEnhancers() as $errorEnhancer) {
  574. if ($e = $errorEnhancer->enhance($exception)) {
  575. return $e;
  576. }
  577. }
  578. return $exception;
  579. }
  580. /**
  581. * Override this method if you want to define more error enhancers.
  582. *
  583. * @return ErrorEnhancerInterface[]
  584. */
  585. protected function getErrorEnhancers(): iterable
  586. {
  587. return [
  588. new UndefinedFunctionErrorEnhancer(),
  589. new UndefinedMethodErrorEnhancer(),
  590. new ClassNotFoundErrorEnhancer(),
  591. ];
  592. }
  593. /**
  594. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  595. */
  596. private function cleanTrace(array $backtrace, int $type, string &$file, int &$line, bool $throw): array
  597. {
  598. $lightTrace = $backtrace;
  599. for ($i = 0; isset($backtrace[$i]); ++$i) {
  600. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  601. $lightTrace = \array_slice($lightTrace, 1 + $i);
  602. break;
  603. }
  604. }
  605. if (\E_USER_DEPRECATED === $type) {
  606. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  607. if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) {
  608. continue;
  609. }
  610. if (!isset($lightTrace[$i]['class']) && 'trigger_deprecation' === $lightTrace[$i]['function']) {
  611. $file = $lightTrace[$i]['file'];
  612. $line = $lightTrace[$i]['line'];
  613. $lightTrace = \array_slice($lightTrace, 1 + $i);
  614. break;
  615. }
  616. }
  617. }
  618. if (class_exists(DebugClassLoader::class, false)) {
  619. for ($i = \count($lightTrace) - 2; 0 < $i; --$i) {
  620. if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  621. array_splice($lightTrace, --$i, 2);
  622. }
  623. }
  624. }
  625. if (!($throw || $this->scopedErrors & $type)) {
  626. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  627. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  628. }
  629. }
  630. return $lightTrace;
  631. }
  632. /**
  633. * Parse the error message by removing the anonymous class notation
  634. * and using the parent class instead if possible.
  635. */
  636. private function parseAnonymousClass(string $message): string
  637. {
  638. 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 fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $message);
  639. }
  640. }