vendor/se7enxweb/symfony-error-handler/ErrorHandler.php line 409

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