Dashboard sipadu mbip
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ErrorHandler.php 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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\Debug;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\LogLevel;
  13. use Symfony\Component\Debug\Exception\FatalErrorException;
  14. use Symfony\Component\Debug\Exception\FatalThrowableError;
  15. use Symfony\Component\Debug\Exception\FlattenException;
  16. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  17. use Symfony\Component\Debug\Exception\SilencedErrorContext;
  18. use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
  19. use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
  20. use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
  21. use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
  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 since Symfony 4.3
  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 $isRecursive = 0;
  90. private $isRoot = false;
  91. private $exceptionHandler;
  92. private $bootstrappingLogger;
  93. private static $reservedMemory;
  94. private static $toStringException = null;
  95. private static $silencedErrorCache = [];
  96. private static $silencedErrorCount = 0;
  97. private static $exitCode = 0;
  98. /**
  99. * Registers the error handler.
  100. *
  101. * @param self|null $handler The handler to register
  102. * @param bool $replace Whether to replace or not any existing handler
  103. *
  104. * @return self The registered error handler
  105. */
  106. public static function register(self $handler = null, $replace = true)
  107. {
  108. if (null === self::$reservedMemory) {
  109. self::$reservedMemory = str_repeat('x', 10240);
  110. register_shutdown_function(__CLASS__.'::handleFatalError');
  111. }
  112. if ($handlerIsNew = null === $handler) {
  113. $handler = new static();
  114. }
  115. if (null === $prev = set_error_handler([$handler, 'handleError'])) {
  116. restore_error_handler();
  117. // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  118. set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors);
  119. $handler->isRoot = true;
  120. }
  121. if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
  122. $handler = $prev[0];
  123. $replace = false;
  124. }
  125. if (!$replace && $prev) {
  126. restore_error_handler();
  127. $handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
  128. } else {
  129. $handlerIsRegistered = true;
  130. }
  131. if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) {
  132. restore_exception_handler();
  133. if (!$handlerIsRegistered) {
  134. $handler = $prev[0];
  135. } elseif ($handler !== $prev[0] && $replace) {
  136. set_exception_handler([$handler, 'handleException']);
  137. $p = $prev[0]->setExceptionHandler(null);
  138. $handler->setExceptionHandler($p);
  139. $prev[0]->setExceptionHandler($p);
  140. }
  141. } else {
  142. $handler->setExceptionHandler($prev);
  143. }
  144. $handler->throwAt(E_ALL & $handler->thrownErrors, true);
  145. return $handler;
  146. }
  147. public function __construct(BufferingLogger $bootstrappingLogger = null)
  148. {
  149. if ($bootstrappingLogger) {
  150. $this->bootstrappingLogger = $bootstrappingLogger;
  151. $this->setDefaultLogger($bootstrappingLogger);
  152. }
  153. $this->traceReflector = new \ReflectionProperty('Exception', 'trace');
  154. $this->traceReflector->setAccessible(true);
  155. }
  156. /**
  157. * Sets a logger to non assigned errors levels.
  158. *
  159. * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
  160. * @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  161. * @param bool $replace Whether to replace or not any existing logger
  162. */
  163. public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, $replace = false)
  164. {
  165. $loggers = [];
  166. if (\is_array($levels)) {
  167. foreach ($levels as $type => $logLevel) {
  168. if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  169. $loggers[$type] = [$logger, $logLevel];
  170. }
  171. }
  172. } else {
  173. if (null === $levels) {
  174. $levels = E_ALL;
  175. }
  176. foreach ($this->loggers as $type => $log) {
  177. if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  178. $log[0] = $logger;
  179. $loggers[$type] = $log;
  180. }
  181. }
  182. }
  183. $this->setLoggers($loggers);
  184. }
  185. /**
  186. * Sets a logger for each error level.
  187. *
  188. * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  189. *
  190. * @return array The previous map
  191. *
  192. * @throws \InvalidArgumentException
  193. */
  194. public function setLoggers(array $loggers)
  195. {
  196. $prevLogged = $this->loggedErrors;
  197. $prev = $this->loggers;
  198. $flush = [];
  199. foreach ($loggers as $type => $log) {
  200. if (!isset($prev[$type])) {
  201. throw new \InvalidArgumentException('Unknown error type: '.$type);
  202. }
  203. if (!\is_array($log)) {
  204. $log = [$log];
  205. } elseif (!\array_key_exists(0, $log)) {
  206. throw new \InvalidArgumentException('No logger provided');
  207. }
  208. if (null === $log[0]) {
  209. $this->loggedErrors &= ~$type;
  210. } elseif ($log[0] instanceof LoggerInterface) {
  211. $this->loggedErrors |= $type;
  212. } else {
  213. throw new \InvalidArgumentException('Invalid logger provided');
  214. }
  215. $this->loggers[$type] = $log + $prev[$type];
  216. if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  217. $flush[$type] = $type;
  218. }
  219. }
  220. $this->reRegister($prevLogged | $this->thrownErrors);
  221. if ($flush) {
  222. foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  223. $type = $log[2]['exception'] instanceof \ErrorException ? $log[2]['exception']->getSeverity() : E_ERROR;
  224. if (!isset($flush[$type])) {
  225. $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  226. } elseif ($this->loggers[$type][0]) {
  227. $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  228. }
  229. }
  230. }
  231. return $prev;
  232. }
  233. /**
  234. * Sets a user exception handler.
  235. *
  236. * @param callable $handler A handler that will be called on Exception
  237. *
  238. * @return callable|null The previous exception handler
  239. */
  240. public function setExceptionHandler(callable $handler = null)
  241. {
  242. $prev = $this->exceptionHandler;
  243. $this->exceptionHandler = $handler;
  244. return $prev;
  245. }
  246. /**
  247. * Sets the PHP error levels that throw an exception when a PHP error occurs.
  248. *
  249. * @param int $levels A bit field of E_* constants for thrown errors
  250. * @param bool $replace Replace or amend the previous value
  251. *
  252. * @return int The previous value
  253. */
  254. public function throwAt($levels, $replace = false)
  255. {
  256. $prev = $this->thrownErrors;
  257. $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
  258. if (!$replace) {
  259. $this->thrownErrors |= $prev;
  260. }
  261. $this->reRegister($prev | $this->loggedErrors);
  262. return $prev;
  263. }
  264. /**
  265. * Sets the PHP error levels for which local variables are preserved.
  266. *
  267. * @param int $levels A bit field of E_* constants for scoped errors
  268. * @param bool $replace Replace or amend the previous value
  269. *
  270. * @return int The previous value
  271. */
  272. public function scopeAt($levels, $replace = false)
  273. {
  274. $prev = $this->scopedErrors;
  275. $this->scopedErrors = (int) $levels;
  276. if (!$replace) {
  277. $this->scopedErrors |= $prev;
  278. }
  279. return $prev;
  280. }
  281. /**
  282. * Sets the PHP error levels for which the stack trace is preserved.
  283. *
  284. * @param int $levels A bit field of E_* constants for traced errors
  285. * @param bool $replace Replace or amend the previous value
  286. *
  287. * @return int The previous value
  288. */
  289. public function traceAt($levels, $replace = false)
  290. {
  291. $prev = $this->tracedErrors;
  292. $this->tracedErrors = (int) $levels;
  293. if (!$replace) {
  294. $this->tracedErrors |= $prev;
  295. }
  296. return $prev;
  297. }
  298. /**
  299. * Sets the error levels where the @-operator is ignored.
  300. *
  301. * @param int $levels A bit field of E_* constants for screamed errors
  302. * @param bool $replace Replace or amend the previous value
  303. *
  304. * @return int The previous value
  305. */
  306. public function screamAt($levels, $replace = false)
  307. {
  308. $prev = $this->screamedErrors;
  309. $this->screamedErrors = (int) $levels;
  310. if (!$replace) {
  311. $this->screamedErrors |= $prev;
  312. }
  313. return $prev;
  314. }
  315. /**
  316. * Re-registers as a PHP error handler if levels changed.
  317. */
  318. private function reRegister($prev)
  319. {
  320. if ($prev !== $this->thrownErrors | $this->loggedErrors) {
  321. $handler = set_error_handler('var_dump');
  322. $handler = \is_array($handler) ? $handler[0] : null;
  323. restore_error_handler();
  324. if ($handler === $this) {
  325. restore_error_handler();
  326. if ($this->isRoot) {
  327. set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors);
  328. } else {
  329. set_error_handler([$this, 'handleError']);
  330. }
  331. }
  332. }
  333. }
  334. /**
  335. * Handles errors by filtering then logging them according to the configured bit fields.
  336. *
  337. * @param int $type One of the E_* constants
  338. * @param string $message
  339. * @param string $file
  340. * @param int $line
  341. *
  342. * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  343. *
  344. * @throws \ErrorException When $this->thrownErrors requests so
  345. *
  346. * @internal
  347. */
  348. public function handleError($type, $message, $file, $line)
  349. {
  350. // @deprecated to be removed in Symfony 5.0
  351. if (\PHP_VERSION_ID >= 70300 && $message && '"' === $message[0] && 0 === strpos($message, '"continue') && preg_match('/^"continue(?: \d++)?" targeting switch is equivalent to "break(?: \d++)?"\. Did you mean to use "continue(?: \d++)?"\?$/', $message)) {
  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. if (!$type || (!$log && !$throw)) {
  363. return !$silenced && $type && $log;
  364. }
  365. $scope = $this->scopedErrors & $type;
  366. if (4 < $numArgs = \func_num_args()) {
  367. $context = $scope ? (func_get_arg(4) ?: []) : [];
  368. } else {
  369. $context = [];
  370. }
  371. if (isset($context['GLOBALS']) && $scope) {
  372. $e = $context; // Whatever the signature of the method,
  373. unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
  374. $context = $e;
  375. }
  376. if (false !== strpos($message, "class@anonymous\0")) {
  377. $logMessage = $this->levels[$type].': '.(new FlattenException())->setMessage($message)->getMessage();
  378. } else {
  379. $logMessage = $this->levels[$type].': '.$message;
  380. }
  381. if (null !== self::$toStringException) {
  382. $errorAsException = self::$toStringException;
  383. self::$toStringException = null;
  384. } elseif (!$throw && !($type & $level)) {
  385. if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) {
  386. $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : [];
  387. $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  388. } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  389. $lightTrace = null;
  390. $errorAsException = self::$silencedErrorCache[$id][$message];
  391. ++$errorAsException->count;
  392. } else {
  393. $lightTrace = [];
  394. $errorAsException = null;
  395. }
  396. if (100 < ++self::$silencedErrorCount) {
  397. self::$silencedErrorCache = $lightTrace = [];
  398. self::$silencedErrorCount = 1;
  399. }
  400. if ($errorAsException) {
  401. self::$silencedErrorCache[$id][$message] = $errorAsException;
  402. }
  403. if (null === $lightTrace) {
  404. return;
  405. }
  406. } else {
  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->traceReflector->setValue($errorAsException, $lightTrace);
  412. } else {
  413. $this->traceReflector->setValue($errorAsException, []);
  414. $backtrace = [];
  415. }
  416. }
  417. if ($throw) {
  418. if (E_USER_ERROR & $type) {
  419. for ($i = 1; isset($backtrace[$i]); ++$i) {
  420. if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
  421. && '__toString' === $backtrace[$i]['function']
  422. && '->' === $backtrace[$i]['type']
  423. && !isset($backtrace[$i - 1]['class'])
  424. && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
  425. ) {
  426. // Here, we know trigger_error() has been called from __toString().
  427. // PHP triggers a fatal error when throwing from __toString().
  428. // A small convention allows working around the limitation:
  429. // given a caught $e exception in __toString(), quitting the method with
  430. // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  431. // to make $e get through the __toString() barrier.
  432. foreach ($context as $e) {
  433. if ($e instanceof \Throwable && $e->__toString() === $message) {
  434. self::$toStringException = $e;
  435. return true;
  436. }
  437. }
  438. // Display the original error message instead of the default one.
  439. $this->handleException($errorAsException);
  440. // Stop the process by giving back the error to the native handler.
  441. return false;
  442. }
  443. }
  444. }
  445. throw $errorAsException;
  446. }
  447. if ($this->isRecursive) {
  448. $log = 0;
  449. } else {
  450. if (!\defined('HHVM_VERSION')) {
  451. $currentErrorHandler = set_error_handler('var_dump');
  452. restore_error_handler();
  453. }
  454. try {
  455. $this->isRecursive = true;
  456. $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  457. $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []);
  458. } finally {
  459. $this->isRecursive = false;
  460. if (!\defined('HHVM_VERSION')) {
  461. set_error_handler($currentErrorHandler);
  462. }
  463. }
  464. }
  465. return !$silenced && $type && $log;
  466. }
  467. /**
  468. * Handles an exception by logging then forwarding it to another handler.
  469. *
  470. * @param \Exception|\Throwable $exception An exception to handle
  471. * @param array $error An array as returned by error_get_last()
  472. *
  473. * @internal
  474. */
  475. public function handleException($exception, array $error = null)
  476. {
  477. if (null === $error) {
  478. self::$exitCode = 255;
  479. }
  480. if (!$exception instanceof \Exception) {
  481. $exception = new FatalThrowableError($exception);
  482. }
  483. $type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
  484. $handlerException = null;
  485. if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
  486. if (false !== strpos($message = $exception->getMessage(), "class@anonymous\0")) {
  487. $message = (new FlattenException())->setMessage($message)->getMessage();
  488. }
  489. if ($exception instanceof FatalErrorException) {
  490. if ($exception instanceof FatalThrowableError) {
  491. $error = [
  492. 'type' => $type,
  493. 'message' => $message,
  494. 'file' => $exception->getFile(),
  495. 'line' => $exception->getLine(),
  496. ];
  497. } else {
  498. $message = 'Fatal '.$message;
  499. }
  500. } elseif ($exception instanceof \ErrorException) {
  501. $message = 'Uncaught '.$message;
  502. } else {
  503. $message = 'Uncaught Exception: '.$message;
  504. }
  505. }
  506. if ($this->loggedErrors & $type) {
  507. try {
  508. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  509. } catch (\Throwable $handlerException) {
  510. }
  511. }
  512. if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
  513. foreach ($this->getFatalErrorHandlers() as $handler) {
  514. if ($e = $handler->handleError($error, $exception)) {
  515. $exception = $e;
  516. break;
  517. }
  518. }
  519. }
  520. $exceptionHandler = $this->exceptionHandler;
  521. $this->exceptionHandler = null;
  522. try {
  523. if (null !== $exceptionHandler) {
  524. return $exceptionHandler($exception);
  525. }
  526. $handlerException = $handlerException ?: $exception;
  527. } catch (\Throwable $handlerException) {
  528. }
  529. if ($exception === $handlerException) {
  530. self::$reservedMemory = null; // Disable the fatal error handler
  531. throw $exception; // Give back $exception to the native handler
  532. }
  533. $this->handleException($handlerException);
  534. }
  535. /**
  536. * Shutdown registered function for handling PHP fatal errors.
  537. *
  538. * @param array $error An array as returned by error_get_last()
  539. *
  540. * @internal
  541. */
  542. public static function handleFatalError(array $error = null)
  543. {
  544. if (null === self::$reservedMemory) {
  545. return;
  546. }
  547. $handler = self::$reservedMemory = null;
  548. $handlers = [];
  549. $previousHandler = null;
  550. $sameHandlerLimit = 10;
  551. while (!\is_array($handler) || !$handler[0] instanceof self) {
  552. $handler = set_exception_handler('var_dump');
  553. restore_exception_handler();
  554. if (!$handler) {
  555. break;
  556. }
  557. restore_exception_handler();
  558. if ($handler !== $previousHandler) {
  559. array_unshift($handlers, $handler);
  560. $previousHandler = $handler;
  561. } elseif (0 === --$sameHandlerLimit) {
  562. $handler = null;
  563. break;
  564. }
  565. }
  566. foreach ($handlers as $h) {
  567. set_exception_handler($h);
  568. }
  569. if (!$handler) {
  570. return;
  571. }
  572. if ($handler !== $h) {
  573. $handler[0]->setExceptionHandler($h);
  574. }
  575. $handler = $handler[0];
  576. $handlers = [];
  577. if ($exit = null === $error) {
  578. $error = error_get_last();
  579. }
  580. if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
  581. // Let's not throw anymore but keep logging
  582. $handler->throwAt(0, true);
  583. $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  584. if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
  585. $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
  586. } else {
  587. $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
  588. }
  589. } else {
  590. $exception = null;
  591. }
  592. try {
  593. if (null !== $exception) {
  594. self::$exitCode = 255;
  595. $handler->handleException($exception, $error);
  596. }
  597. } catch (FatalErrorException $e) {
  598. // Ignore this re-throw
  599. }
  600. if ($exit && self::$exitCode) {
  601. $exitCode = self::$exitCode;
  602. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  603. }
  604. }
  605. /**
  606. * Gets the fatal error handlers.
  607. *
  608. * Override this method if you want to define more fatal error handlers.
  609. *
  610. * @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
  611. */
  612. protected function getFatalErrorHandlers()
  613. {
  614. return [
  615. new UndefinedFunctionFatalErrorHandler(),
  616. new UndefinedMethodFatalErrorHandler(),
  617. new ClassNotFoundFatalErrorHandler(),
  618. ];
  619. }
  620. /**
  621. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  622. */
  623. private function cleanTrace($backtrace, $type, $file, $line, $throw)
  624. {
  625. $lightTrace = $backtrace;
  626. for ($i = 0; isset($backtrace[$i]); ++$i) {
  627. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  628. $lightTrace = \array_slice($lightTrace, 1 + $i);
  629. break;
  630. }
  631. }
  632. if (class_exists(DebugClassLoader::class, false)) {
  633. for ($i = \count($lightTrace) - 2; 0 < $i; --$i) {
  634. if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  635. array_splice($lightTrace, --$i, 2);
  636. }
  637. }
  638. }
  639. if (!($throw || $this->scopedErrors & $type)) {
  640. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  641. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  642. }
  643. }
  644. return $lightTrace;
  645. }
  646. }