ErrorHandler.php 27 KB

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