ErrorHandler.php 27 KB

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