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

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ErrorHandler;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\LogLevel;
  13. use Symfony\Component\ErrorHandler\Error\FatalError;
  14. use Symfony\Component\ErrorHandler\Error\OutOfMemoryError;
  15. use Symfony\Component\ErrorHandler\ErrorEnhancer\ClassNotFoundErrorEnhancer;
  16. use Symfony\Component\ErrorHandler\ErrorEnhancer\ErrorEnhancerInterface;
  17. use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedFunctionErrorEnhancer;
  18. use Symfony\Component\ErrorHandler\ErrorEnhancer\UndefinedMethodErrorEnhancer;
  19. use Symfony\Component\ErrorHandler\ErrorRenderer\CliErrorRenderer;
  20. use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
  21. use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
  22. /**
  23. * A generic ErrorHandler for the PHP engine.
  24. *
  25. * Provides five bit fields that control how errors are handled:
  26. * - thrownErrors: errors thrown as \ErrorException
  27. * - loggedErrors: logged errors, when not @-silenced
  28. * - scopedErrors: errors thrown or logged with their local context
  29. * - tracedErrors: errors logged with their stack trace
  30. * - screamedErrors: never @-silenced errors
  31. *
  32. * Each error level can be logged by a dedicated PSR-3 logger object.
  33. * Screaming only applies to logging.
  34. * Throwing takes precedence over logging.
  35. * Uncaught exceptions are logged as E_ERROR.
  36. * E_DEPRECATED and E_USER_DEPRECATED levels never throw.
  37. * E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
  38. * Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
  39. * As errors have a performance cost, repeated errors are all logged, so that the developer
  40. * can see them and weight them as more important to fix than others of the same level.
  41. *
  42. * @author Nicolas Grekas <p@tchwork.com>
  43. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  44. *
  45. * @final
  46. */
  47. class ErrorHandler
  48. {
  49. private $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 $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 $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  82. private $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  83. private $tracedErrors = 0x77FB; // E_ALL - E_STRICT - E_PARSE
  84. private $screamedErrors = 0x55; // E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
  85. private $loggedErrors = 0;
  86. private $configureException;
  87. private $debug;
  88. private $isRecursive = 0;
  89. private $isRoot = false;
  90. private $exceptionHandler;
  91. private $bootstrappingLogger;
  92. private static $reservedMemory;
  93. private static $toStringException;
  94. private static $silencedErrorCache = [];
  95. private static $silencedErrorCount = 0;
  96. private static $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(__CLASS__.'::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. * @return mixed What $function(...$arguments) returns
  145. *
  146. * @throws \ErrorException When $function(...$arguments) triggers a PHP error
  147. */
  148. public static function call(callable $function, ...$arguments)
  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 (\PHP_VERSION_ID < 80400) {
  167. $this->levels[\E_STRICT] = 'Runtime Notice';
  168. $this->loggers[\E_STRICT] = [null, LogLevel::WARNING];
  169. }
  170. if ($bootstrappingLogger) {
  171. $this->bootstrappingLogger = $bootstrappingLogger;
  172. $this->setDefaultLogger($bootstrappingLogger);
  173. }
  174. $traceReflector = new \ReflectionProperty(\Exception::class, 'trace');
  175. $traceReflector->setAccessible(true);
  176. $this->configureException = \Closure::bind(static function ($e, $trace, $file = null, $line = null) use ($traceReflector) {
  177. $traceReflector->setValue($e, $trace);
  178. $e->file = $file ?? $e->file;
  179. $e->line = $line ?? $e->line;
  180. }, null, new class() extends \Exception {
  181. });
  182. $this->debug = $debug;
  183. }
  184. /**
  185. * Sets a logger to non assigned errors levels.
  186. *
  187. * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
  188. * @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  189. * @param bool $replace Whether to replace or not any existing logger
  190. */
  191. public function setDefaultLogger(LoggerInterface $logger, $levels = \E_ALL, bool $replace = false): void
  192. {
  193. $loggers = [];
  194. if (\is_array($levels)) {
  195. foreach ($levels as $type => $logLevel) {
  196. if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  197. $loggers[$type] = [$logger, $logLevel];
  198. }
  199. }
  200. } else {
  201. if (null === $levels) {
  202. $levels = \E_ALL;
  203. }
  204. foreach ($this->loggers as $type => $log) {
  205. if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  206. $log[0] = $logger;
  207. $loggers[$type] = $log;
  208. }
  209. }
  210. }
  211. $this->setLoggers($loggers);
  212. }
  213. /**
  214. * Sets a logger for each error level.
  215. *
  216. * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  217. *
  218. * @return array The previous map
  219. *
  220. * @throws \InvalidArgumentException
  221. */
  222. public function setLoggers(array $loggers): array
  223. {
  224. $prevLogged = $this->loggedErrors;
  225. $prev = $this->loggers;
  226. $flush = [];
  227. foreach ($loggers as $type => $log) {
  228. if (!isset($prev[$type])) {
  229. throw new \InvalidArgumentException('Unknown error type: '.$type);
  230. }
  231. if (!\is_array($log)) {
  232. $log = [$log];
  233. } elseif (!\array_key_exists(0, $log)) {
  234. throw new \InvalidArgumentException('No logger provided.');
  235. }
  236. if (null === $log[0]) {
  237. $this->loggedErrors &= ~$type;
  238. } elseif ($log[0] instanceof LoggerInterface) {
  239. $this->loggedErrors |= $type;
  240. } else {
  241. throw new \InvalidArgumentException('Invalid logger provided.');
  242. }
  243. $this->loggers[$type] = $log + $prev[$type];
  244. if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  245. $flush[$type] = $type;
  246. }
  247. }
  248. $this->reRegister($prevLogged | $this->thrownErrors);
  249. if ($flush) {
  250. foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  251. $type = ThrowableUtils::getSeverity($log[2]['exception']);
  252. if (!isset($flush[$type])) {
  253. $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  254. } elseif ($this->loggers[$type][0]) {
  255. $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  256. }
  257. }
  258. }
  259. return $prev;
  260. }
  261. /**
  262. * Sets a user exception handler.
  263. *
  264. * @param callable(\Throwable $e)|null $handler
  265. *
  266. * @return callable|null The previous exception handler
  267. */
  268. public function setExceptionHandler(?callable $handler): ?callable
  269. {
  270. $prev = $this->exceptionHandler;
  271. $this->exceptionHandler = $handler;
  272. return $prev;
  273. }
  274. /**
  275. * Sets the PHP error levels that throw an exception when a PHP error occurs.
  276. *
  277. * @param int $levels A bit field of E_* constants for thrown errors
  278. * @param bool $replace Replace or amend the previous value
  279. *
  280. * @return int The previous value
  281. */
  282. public function throwAt(int $levels, bool $replace = false): int
  283. {
  284. $prev = $this->thrownErrors;
  285. $this->thrownErrors = ($levels | \E_RECOVERABLE_ERROR | \E_USER_ERROR) & ~\E_USER_DEPRECATED & ~\E_DEPRECATED;
  286. if (!$replace) {
  287. $this->thrownErrors |= $prev;
  288. }
  289. $this->reRegister($prev | $this->loggedErrors);
  290. return $prev;
  291. }
  292. /**
  293. * Sets the PHP error levels for which local variables are preserved.
  294. *
  295. * @param int $levels A bit field of E_* constants for scoped errors
  296. * @param bool $replace Replace or amend the previous value
  297. *
  298. * @return int The previous value
  299. */
  300. public function scopeAt(int $levels, bool $replace = false): int
  301. {
  302. $prev = $this->scopedErrors;
  303. $this->scopedErrors = $levels;
  304. if (!$replace) {
  305. $this->scopedErrors |= $prev;
  306. }
  307. return $prev;
  308. }
  309. /**
  310. * Sets the PHP error levels for which the stack trace is preserved.
  311. *
  312. * @param int $levels A bit field of E_* constants for traced errors
  313. * @param bool $replace Replace or amend the previous value
  314. *
  315. * @return int The previous value
  316. */
  317. public function traceAt(int $levels, bool $replace = false): int
  318. {
  319. $prev = $this->tracedErrors;
  320. $this->tracedErrors = $levels;
  321. if (!$replace) {
  322. $this->tracedErrors |= $prev;
  323. }
  324. return $prev;
  325. }
  326. /**
  327. * Sets the error levels where the @-operator is ignored.
  328. *
  329. * @param int $levels A bit field of E_* constants for screamed errors
  330. * @param bool $replace Replace or amend the previous value
  331. *
  332. * @return int The previous value
  333. */
  334. public function screamAt(int $levels, bool $replace = false): int
  335. {
  336. $prev = $this->screamedErrors;
  337. $this->screamedErrors = $levels;
  338. if (!$replace) {
  339. $this->screamedErrors |= $prev;
  340. }
  341. return $prev;
  342. }
  343. /**
  344. * Re-registers as a PHP error handler if levels changed.
  345. */
  346. private function reRegister(int $prev): void
  347. {
  348. if ($prev !== ($this->thrownErrors | $this->loggedErrors)) {
  349. $handler = set_error_handler('is_int');
  350. $handler = \is_array($handler) ? $handler[0] : null;
  351. restore_error_handler();
  352. if ($handler === $this) {
  353. restore_error_handler();
  354. if ($this->isRoot) {
  355. set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors);
  356. } else {
  357. set_error_handler([$this, 'handleError']);
  358. }
  359. }
  360. }
  361. }
  362. /**
  363. * Handles errors by filtering then logging them according to the configured bit fields.
  364. *
  365. * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  366. *
  367. * @throws \ErrorException When $this->thrownErrors requests so
  368. *
  369. * @internal
  370. */
  371. public function handleError(int $type, string $message, string $file, int $line): bool
  372. {
  373. if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) {
  374. $type = \E_DEPRECATED;
  375. }
  376. // Level is the current error reporting level to manage silent error.
  377. $level = error_reporting();
  378. $silenced = 0 === ($level & $type);
  379. // Strong errors are not authorized to be silenced.
  380. $level |= \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED;
  381. $log = $this->loggedErrors & $type;
  382. $throw = $this->thrownErrors & $type & $level;
  383. $type &= $level | $this->screamedErrors;
  384. // Never throw on warnings triggered by assert()
  385. if (\E_WARNING === $type && 'a' === $message[0] && 0 === strncmp($message, 'assert(): ', 10)) {
  386. $throw = 0;
  387. }
  388. if (!$type || (!$log && !$throw)) {
  389. return false;
  390. }
  391. $logMessage = $this->levels[$type].': '.$message;
  392. if (null !== self::$toStringException) {
  393. $errorAsException = self::$toStringException;
  394. self::$toStringException = null;
  395. } elseif (!$throw && !($type & $level)) {
  396. if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) {
  397. $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : [];
  398. $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  399. } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  400. $lightTrace = null;
  401. $errorAsException = self::$silencedErrorCache[$id][$message];
  402. ++$errorAsException->count;
  403. } else {
  404. $lightTrace = [];
  405. $errorAsException = null;
  406. }
  407. if (100 < ++self::$silencedErrorCount) {
  408. self::$silencedErrorCache = $lightTrace = [];
  409. self::$silencedErrorCount = 1;
  410. }
  411. if ($errorAsException) {
  412. self::$silencedErrorCache[$id][$message] = $errorAsException;
  413. }
  414. if (null === $lightTrace) {
  415. return true;
  416. }
  417. } else {
  418. if (PHP_VERSION_ID < 80303 && false !== strpos($message, '@anonymous')) {
  419. $backtrace = debug_backtrace(false, 5);
  420. for ($i = 1; isset($backtrace[$i]); ++$i) {
  421. if (isset($backtrace[$i]['function'], $backtrace[$i]['args'][0])
  422. && ('trigger_error' === $backtrace[$i]['function'] || 'user_error' === $backtrace[$i]['function'])
  423. ) {
  424. if ($backtrace[$i]['args'][0] !== $message) {
  425. $message = $backtrace[$i]['args'][0];
  426. }
  427. break;
  428. }
  429. }
  430. }
  431. if (false !== strpos($message, "@anonymous\0")) {
  432. $message = $this->parseAnonymousClass($message);
  433. $logMessage = $this->levels[$type].': '.$message;
  434. }
  435. $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
  436. if ($throw || $this->tracedErrors & $type) {
  437. $backtrace = $errorAsException->getTrace();
  438. $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
  439. ($this->configureException)($errorAsException, $lightTrace, $file, $line);
  440. } else {
  441. ($this->configureException)($errorAsException, []);
  442. $backtrace = [];
  443. }
  444. }
  445. if ($throw) {
  446. if (\PHP_VERSION_ID < 70400 && \E_USER_ERROR & $type) {
  447. for ($i = 1; isset($backtrace[$i]); ++$i) {
  448. if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
  449. && '__toString' === $backtrace[$i]['function']
  450. && '->' === $backtrace[$i]['type']
  451. && !isset($backtrace[$i - 1]['class'])
  452. && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
  453. ) {
  454. // Here, we know trigger_error() has been called from __toString().
  455. // PHP triggers a fatal error when throwing from __toString().
  456. // A small convention allows working around the limitation:
  457. // given a caught $e exception in __toString(), quitting the method with
  458. // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  459. // to make $e get through the __toString() barrier.
  460. $context = 4 < \func_num_args() ? (func_get_arg(4) ?: []) : [];
  461. foreach ($context as $e) {
  462. if ($e instanceof \Throwable && $e->__toString() === $message) {
  463. self::$toStringException = $e;
  464. return true;
  465. }
  466. }
  467. // Display the original error message instead of the default one.
  468. $exitCode = self::$exitCode;
  469. try {
  470. $this->handleException($errorAsException);
  471. } finally {
  472. self::$exitCode = $exitCode;
  473. }
  474. // Stop the process by giving back the error to the native handler.
  475. return false;
  476. }
  477. }
  478. }
  479. throw $errorAsException;
  480. }
  481. if ($this->isRecursive) {
  482. $log = 0;
  483. } else {
  484. if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404)) {
  485. $currentErrorHandler = set_error_handler('is_int');
  486. restore_error_handler();
  487. }
  488. try {
  489. $this->isRecursive = true;
  490. $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  491. $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []);
  492. } finally {
  493. $this->isRecursive = false;
  494. if (\PHP_VERSION_ID < (\PHP_VERSION_ID < 70400 ? 70316 : 70404)) {
  495. set_error_handler($currentErrorHandler);
  496. }
  497. }
  498. }
  499. return !$silenced && $type && $log;
  500. }
  501. /**
  502. * Handles an exception by logging then forwarding it to another handler.
  503. *
  504. * @internal
  505. */
  506. public function handleException(\Throwable $exception)
  507. {
  508. $handlerException = null;
  509. if (!$exception instanceof FatalError) {
  510. self::$exitCode = 255;
  511. $type = ThrowableUtils::getSeverity($exception);
  512. } else {
  513. $type = $exception->getError()['type'];
  514. }
  515. if ($this->loggedErrors & $type) {
  516. if (false !== strpos($message = $exception->getMessage(), "@anonymous\0")) {
  517. $message = $this->parseAnonymousClass($message);
  518. }
  519. if ($exception instanceof FatalError) {
  520. $message = 'Fatal '.$message;
  521. } elseif ($exception instanceof \Error) {
  522. $message = 'Uncaught Error: '.$message;
  523. } elseif ($exception instanceof \ErrorException) {
  524. $message = 'Uncaught '.$message;
  525. } else {
  526. $message = 'Uncaught Exception: '.$message;
  527. }
  528. try {
  529. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  530. } catch (\Throwable $handlerException) {
  531. }
  532. }
  533. if (!$exception instanceof OutOfMemoryError) {
  534. foreach ($this->getErrorEnhancers() as $errorEnhancer) {
  535. if ($e = $errorEnhancer->enhance($exception)) {
  536. $exception = $e;
  537. break;
  538. }
  539. }
  540. }
  541. $exceptionHandler = $this->exceptionHandler;
  542. $this->exceptionHandler = [$this, 'renderException'];
  543. if (null === $exceptionHandler || $exceptionHandler === $this->exceptionHandler) {
  544. $this->exceptionHandler = null;
  545. }
  546. try {
  547. if (null !== $exceptionHandler) {
  548. return $exceptionHandler($exception);
  549. }
  550. $handlerException = $handlerException ?: $exception;
  551. } catch (\Throwable $handlerException) {
  552. }
  553. if ($exception === $handlerException && null === $this->exceptionHandler) {
  554. self::$reservedMemory = null; // Disable the fatal error handler
  555. throw $exception; // Give back $exception to the native handler
  556. }
  557. $loggedErrors = $this->loggedErrors;
  558. if ($exception === $handlerException) {
  559. $this->loggedErrors &= ~$type;
  560. }
  561. try {
  562. $this->handleException($handlerException);
  563. } finally {
  564. $this->loggedErrors = $loggedErrors;
  565. }
  566. }
  567. /**
  568. * Shutdown registered function for handling PHP fatal errors.
  569. *
  570. * @param array|null $error An array as returned by error_get_last()
  571. *
  572. * @internal
  573. */
  574. public static function handleFatalError(?array $error = null): void
  575. {
  576. if (null === self::$reservedMemory) {
  577. return;
  578. }
  579. $handler = self::$reservedMemory = null;
  580. $handlers = [];
  581. $previousHandler = null;
  582. $sameHandlerLimit = 10;
  583. while (!\is_array($handler) || !$handler[0] instanceof self) {
  584. $handler = set_exception_handler('is_int');
  585. restore_exception_handler();
  586. if (!$handler) {
  587. break;
  588. }
  589. restore_exception_handler();
  590. if ($handler !== $previousHandler) {
  591. array_unshift($handlers, $handler);
  592. $previousHandler = $handler;
  593. } elseif (0 === --$sameHandlerLimit) {
  594. $handler = null;
  595. break;
  596. }
  597. }
  598. foreach ($handlers as $h) {
  599. set_exception_handler($h);
  600. }
  601. if (!$handler) {
  602. if (null === $error && $exitCode = self::$exitCode) {
  603. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  604. }
  605. return;
  606. }
  607. if ($handler !== $h) {
  608. $handler[0]->setExceptionHandler($h);
  609. }
  610. $handler = $handler[0];
  611. $handlers = [];
  612. if ($exit = null === $error) {
  613. $error = error_get_last();
  614. }
  615. if ($error && $error['type'] &= \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR) {
  616. // Let's not throw anymore but keep logging
  617. $handler->throwAt(0, true);
  618. $trace = $error['backtrace'] ?? null;
  619. if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
  620. $fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, false, $trace);
  621. } else {
  622. $fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, true, $trace);
  623. }
  624. } else {
  625. $fatalError = null;
  626. }
  627. try {
  628. if (null !== $fatalError) {
  629. self::$exitCode = 255;
  630. $handler->handleException($fatalError);
  631. }
  632. } catch (FatalError $e) {
  633. // Ignore this re-throw
  634. }
  635. if ($exit && $exitCode = self::$exitCode) {
  636. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  637. }
  638. }
  639. /**
  640. * Renders the given exception.
  641. *
  642. * As this method is mainly called during boot where nothing is yet available,
  643. * the output is always either HTML or CLI depending where PHP runs.
  644. */
  645. private function renderException(\Throwable $exception): void
  646. {
  647. $renderer = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliErrorRenderer() : new HtmlErrorRenderer($this->debug);
  648. $exception = $renderer->render($exception);
  649. if (!headers_sent()) {
  650. http_response_code($exception->getStatusCode());
  651. foreach ($exception->getHeaders() as $name => $value) {
  652. header($name.': '.$value, false);
  653. }
  654. }
  655. echo $exception->getAsString();
  656. }
  657. /**
  658. * Override this method if you want to define more error enhancers.
  659. *
  660. * @return ErrorEnhancerInterface[]
  661. */
  662. protected function getErrorEnhancers(): iterable
  663. {
  664. return [
  665. new UndefinedFunctionErrorEnhancer(),
  666. new UndefinedMethodErrorEnhancer(),
  667. new ClassNotFoundErrorEnhancer(),
  668. ];
  669. }
  670. /**
  671. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  672. */
  673. private function cleanTrace(array $backtrace, int $type, string &$file, int &$line, bool $throw): array
  674. {
  675. $lightTrace = $backtrace;
  676. for ($i = 0; isset($backtrace[$i]); ++$i) {
  677. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  678. $lightTrace = \array_slice($lightTrace, 1 + $i);
  679. break;
  680. }
  681. }
  682. if (\E_USER_DEPRECATED === $type) {
  683. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  684. if (!isset($lightTrace[$i]['file'], $lightTrace[$i]['line'], $lightTrace[$i]['function'])) {
  685. continue;
  686. }
  687. if (!isset($lightTrace[$i]['class']) && 'trigger_deprecation' === $lightTrace[$i]['function']) {
  688. $file = $lightTrace[$i]['file'];
  689. $line = $lightTrace[$i]['line'];
  690. $lightTrace = \array_slice($lightTrace, 1 + $i);
  691. break;
  692. }
  693. }
  694. }
  695. if (class_exists(DebugClassLoader::class, false)) {
  696. for ($i = \count($lightTrace) - 2; 0 < $i; --$i) {
  697. if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  698. array_splice($lightTrace, --$i, 2);
  699. }
  700. }
  701. }
  702. if (!($throw || $this->scopedErrors & $type)) {
  703. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  704. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  705. }
  706. }
  707. return $lightTrace;
  708. }
  709. /**
  710. * Parse the error message by removing the anonymous class notation
  711. * and using the parent class instead if possible.
  712. */
  713. private function parseAnonymousClass(string $message): string
  714. {
  715. 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) {
  716. return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
  717. }, $message);
  718. }
  719. }