Nav apraksta

ErrorHandler.php 28KB

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