ErrorHandler.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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::WARNING],
  70. \E_USER_NOTICE => [null, LogLevel::WARNING],
  71. \E_STRICT => [null, LogLevel::WARNING],
  72. \E_WARNING => [null, LogLevel::WARNING],
  73. \E_USER_WARNING => [null, LogLevel::WARNING],
  74. \E_COMPILE_WARNING => [null, LogLevel::WARNING],
  75. \E_CORE_WARNING => [null, LogLevel::WARNING],
  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. private $exceptionHandler;
  93. private $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 = null, bool $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->thrownErrors, true);
  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 $function, mixed ...$arguments): mixed
  148. {
  149. set_error_handler(static function (int $type, string $message, string $file, int $line) {
  150. if (__FILE__ === $file) {
  151. $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  152. $file = $trace[2]['file'] ?? $file;
  153. $line = $trace[2]['line'] ?? $line;
  154. }
  155. throw new \ErrorException($message, 0, $type, $file, $line);
  156. });
  157. try {
  158. return $function(...$arguments);
  159. } finally {
  160. restore_error_handler();
  161. }
  162. }
  163. public function __construct(BufferingLogger $bootstrappingLogger = null, bool $debug = false)
  164. {
  165. if ($bootstrappingLogger) {
  166. $this->bootstrappingLogger = $bootstrappingLogger;
  167. $this->setDefaultLogger($bootstrappingLogger);
  168. }
  169. $traceReflector = new \ReflectionProperty(\Exception::class, 'trace');
  170. $traceReflector->setAccessible(true);
  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. if (null === $levels) {
  197. $levels = \E_ALL;
  198. }
  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('var_dump');
  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 (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 = $this->parseAnonymousClass($backtrace[$i]['args'][0]);
  401. $logMessage = $this->levels[$type].': '.$message;
  402. }
  403. break;
  404. }
  405. }
  406. }
  407. $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
  408. if ($throw || $this->tracedErrors & $type) {
  409. $backtrace = $errorAsException->getTrace();
  410. $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
  411. ($this->configureException)($errorAsException, $lightTrace, $file, $line);
  412. } else {
  413. ($this->configureException)($errorAsException, []);
  414. $backtrace = [];
  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)
  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. if (!$exception instanceof OutOfMemoryError) {
  466. foreach ($this->getErrorEnhancers() as $errorEnhancer) {
  467. if ($e = $errorEnhancer->enhance($exception)) {
  468. $exception = $e;
  469. break;
  470. }
  471. }
  472. }
  473. $exceptionHandler = $this->exceptionHandler;
  474. $this->exceptionHandler = [$this, 'renderException'];
  475. if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) {
  476. $this->exceptionHandler = null;
  477. }
  478. try {
  479. if (null !== $exceptionHandler) {
  480. return $exceptionHandler($exception);
  481. }
  482. $handlerException = $handlerException ?: $exception;
  483. } catch (\Throwable $handlerException) {
  484. }
  485. if ($exception === $handlerException && null === $this->exceptionHandler) {
  486. self::$reservedMemory = null; // Disable the fatal error handler
  487. throw $exception; // Give back $exception to the native handler
  488. }
  489. $loggedErrors = $this->loggedErrors;
  490. if ($exception === $handlerException) {
  491. $this->loggedErrors &= ~$type;
  492. }
  493. try {
  494. $this->handleException($handlerException);
  495. } finally {
  496. $this->loggedErrors = $loggedErrors;
  497. }
  498. }
  499. /**
  500. * Shutdown registered function for handling PHP fatal errors.
  501. *
  502. * @param array|null $error An array as returned by error_get_last()
  503. *
  504. * @internal
  505. */
  506. public static function handleFatalError(array $error = null): void
  507. {
  508. if (null === self::$reservedMemory) {
  509. return;
  510. }
  511. $handler = self::$reservedMemory = null;
  512. $handlers = [];
  513. $previousHandler = null;
  514. $sameHandlerLimit = 10;
  515. while (!\is_array($handler) || !$handler[0] instanceof self) {
  516. $handler = set_exception_handler('var_dump');
  517. restore_exception_handler();
  518. if (!$handler) {
  519. break;
  520. }
  521. restore_exception_handler();
  522. if ($handler !== $previousHandler) {
  523. array_unshift($handlers, $handler);
  524. $previousHandler = $handler;
  525. } elseif (0 === --$sameHandlerLimit) {
  526. $handler = null;
  527. break;
  528. }
  529. }
  530. foreach ($handlers as $h) {
  531. set_exception_handler($h);
  532. }
  533. if (!$handler) {
  534. return;
  535. }
  536. if ($handler !== $h) {
  537. $handler[0]->setExceptionHandler($h);
  538. }
  539. $handler = $handler[0];
  540. $handlers = [];
  541. if ($exit = null === $error) {
  542. $error = error_get_last();
  543. }
  544. if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) {
  545. // Let's not throw anymore but keep logging
  546. $handler->throwAt(0, true);
  547. $trace = $error['backtrace'] ?? null;
  548. if (str_starts_with($error['message'], 'Allowed memory') || str_starts_with($error['message'], 'Out of memory')) {
  549. $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, false, $trace);
  550. } else {
  551. $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, true, $trace);
  552. }
  553. } else {
  554. $fatalError = null;
  555. }
  556. try {
  557. if (null !== $fatalError) {
  558. self::$exitCode = 255;
  559. $handler->handleException($fatalError);
  560. }
  561. } catch (FatalError $e) {
  562. // Ignore this re-throw
  563. }
  564. if ($exit && self::$exitCode) {
  565. $exitCode = self::$exitCode;
  566. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  567. }
  568. }
  569. /**
  570. * Renders the given exception.
  571. *
  572. * As this method is mainly called during boot where nothing is yet available,
  573. * the output is always either HTML or CLI depending where PHP runs.
  574. */
  575. private function renderException(\Throwable $exception): void
  576. {
  577. $renderer = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug);
  578. $exception = $renderer->render($exception);
  579. if (!headers_sent()) {
  580. http_response_code($exception->getStatusCode());
  581. foreach ($exception->getHeaders() as $name => $value) {
  582. header($name.': '.$value, false);
  583. }
  584. }
  585. echo $exception->getAsString();
  586. }
  587. /**
  588. * Override this method if you want to define more error enhancers.
  589. *
  590. * @return ErrorEnhancerInterface[]
  591. */
  592. protected function getErrorEnhancers(): iterable
  593. {
  594. return [
  595. new UndefinedFunctionErrorEnhancer(),
  596. new UndefinedMethodErrorEnhancer(),
  597. new ClassNotFoundErrorEnhancer(),
  598. ];
  599. }
  600. /**
  601. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  602. */
  603. private function cleanTrace(array $backtrace, int $type, string &$file, int &$line, bool $throw): array
  604. {
  605. $lightTrace = $backtrace;
  606. for ($i = 0; isset($backtrace[$i]); ++$i) {
  607. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  608. $lightTrace = \array_slice($lightTrace, 1 + $i);
  609. break;
  610. }
  611. }
  612. if (\E_USER_DEPRECATED === $type) {
  613. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  614. if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) {
  615. continue;
  616. }
  617. if (!isset($lightTrace[$i]['class']) && 'trigger_deprecation' === $lightTrace[$i]['function']) {
  618. $file = $lightTrace[$i]['file'];
  619. $line = $lightTrace[$i]['line'];
  620. $lightTrace = \array_slice($lightTrace, 1 + $i);
  621. break;
  622. }
  623. }
  624. }
  625. if (class_exists(DebugClassLoader::class, false)) {
  626. for ($i = \count($lightTrace) - 2; 0 < $i; --$i) {
  627. if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  628. array_splice($lightTrace, --$i, 2);
  629. }
  630. }
  631. }
  632. if (!($throw || $this->scopedErrors & $type)) {
  633. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  634. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  635. }
  636. }
  637. return $lightTrace;
  638. }
  639. /**
  640. * Parse the error message by removing the anonymous class notation
  641. * and using the parent class instead if possible.
  642. */
  643. private function parseAnonymousClass(string $message): string
  644. {
  645. 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) {
  646. return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
  647. }, $message);
  648. }
  649. }