菜谱项目

ErrorHandler.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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\LogLevel;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\Debug\Exception\ContextErrorException;
  14. use Symfony\Component\Debug\Exception\FatalErrorException;
  15. use Symfony\Component\Debug\Exception\FatalThrowableError;
  16. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  17. use Symfony\Component\Debug\Exception\SilencedErrorContext;
  18. use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
  19. use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
  20. use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
  21. use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
  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. class ErrorHandler
  46. {
  47. private $levels = array(
  48. E_DEPRECATED => 'Deprecated',
  49. E_USER_DEPRECATED => 'User Deprecated',
  50. E_NOTICE => 'Notice',
  51. E_USER_NOTICE => 'User Notice',
  52. E_STRICT => 'Runtime Notice',
  53. E_WARNING => 'Warning',
  54. E_USER_WARNING => 'User Warning',
  55. E_COMPILE_WARNING => 'Compile Warning',
  56. E_CORE_WARNING => 'Core Warning',
  57. E_USER_ERROR => 'User Error',
  58. E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  59. E_COMPILE_ERROR => 'Compile Error',
  60. E_PARSE => 'Parse Error',
  61. E_ERROR => 'Error',
  62. E_CORE_ERROR => 'Core Error',
  63. );
  64. private $loggers = array(
  65. E_DEPRECATED => array(null, LogLevel::INFO),
  66. E_USER_DEPRECATED => array(null, LogLevel::INFO),
  67. E_NOTICE => array(null, LogLevel::WARNING),
  68. E_USER_NOTICE => array(null, LogLevel::WARNING),
  69. E_STRICT => array(null, LogLevel::WARNING),
  70. E_WARNING => array(null, LogLevel::WARNING),
  71. E_USER_WARNING => array(null, LogLevel::WARNING),
  72. E_COMPILE_WARNING => array(null, LogLevel::WARNING),
  73. E_CORE_WARNING => array(null, LogLevel::WARNING),
  74. E_USER_ERROR => array(null, LogLevel::CRITICAL),
  75. E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
  76. E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
  77. E_PARSE => array(null, LogLevel::CRITICAL),
  78. E_ERROR => array(null, LogLevel::CRITICAL),
  79. E_CORE_ERROR => array(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 $traceReflector;
  87. private $isRecursive = 0;
  88. private $isRoot = false;
  89. private $exceptionHandler;
  90. private $bootstrappingLogger;
  91. private static $reservedMemory;
  92. private static $stackedErrors = array();
  93. private static $stackedErrorLevels = array();
  94. private static $toStringException = null;
  95. private static $silencedErrorCache = array();
  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(array($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(array($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. $handler->setExceptionHandler(set_exception_handler(array($handler, 'handleException')));
  127. } else {
  128. restore_error_handler();
  129. }
  130. $handler->throwAt(E_ALL & $handler->thrownErrors, true);
  131. return $handler;
  132. }
  133. public function __construct(BufferingLogger $bootstrappingLogger = null)
  134. {
  135. if ($bootstrappingLogger) {
  136. $this->bootstrappingLogger = $bootstrappingLogger;
  137. $this->setDefaultLogger($bootstrappingLogger);
  138. }
  139. $this->traceReflector = new \ReflectionProperty('Exception', 'trace');
  140. $this->traceReflector->setAccessible(true);
  141. }
  142. /**
  143. * Sets a logger to non assigned errors levels.
  144. *
  145. * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
  146. * @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  147. * @param bool $replace Whether to replace or not any existing logger
  148. */
  149. public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, $replace = false)
  150. {
  151. $loggers = array();
  152. if (is_array($levels)) {
  153. foreach ($levels as $type => $logLevel) {
  154. if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  155. $loggers[$type] = array($logger, $logLevel);
  156. }
  157. }
  158. } else {
  159. if (null === $levels) {
  160. $levels = E_ALL;
  161. }
  162. foreach ($this->loggers as $type => $log) {
  163. if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  164. $log[0] = $logger;
  165. $loggers[$type] = $log;
  166. }
  167. }
  168. }
  169. $this->setLoggers($loggers);
  170. }
  171. /**
  172. * Sets a logger for each error level.
  173. *
  174. * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  175. *
  176. * @return array The previous map
  177. *
  178. * @throws \InvalidArgumentException
  179. */
  180. public function setLoggers(array $loggers)
  181. {
  182. $prevLogged = $this->loggedErrors;
  183. $prev = $this->loggers;
  184. $flush = array();
  185. foreach ($loggers as $type => $log) {
  186. if (!isset($prev[$type])) {
  187. throw new \InvalidArgumentException('Unknown error type: '.$type);
  188. }
  189. if (!is_array($log)) {
  190. $log = array($log);
  191. } elseif (!array_key_exists(0, $log)) {
  192. throw new \InvalidArgumentException('No logger provided');
  193. }
  194. if (null === $log[0]) {
  195. $this->loggedErrors &= ~$type;
  196. } elseif ($log[0] instanceof LoggerInterface) {
  197. $this->loggedErrors |= $type;
  198. } else {
  199. throw new \InvalidArgumentException('Invalid logger provided');
  200. }
  201. $this->loggers[$type] = $log + $prev[$type];
  202. if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  203. $flush[$type] = $type;
  204. }
  205. }
  206. $this->reRegister($prevLogged | $this->thrownErrors);
  207. if ($flush) {
  208. foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  209. $type = $log[2]['exception'] instanceof \ErrorException ? $log[2]['exception']->getSeverity() : E_ERROR;
  210. if (!isset($flush[$type])) {
  211. $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  212. } elseif ($this->loggers[$type][0]) {
  213. $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  214. }
  215. }
  216. }
  217. return $prev;
  218. }
  219. /**
  220. * Sets a user exception handler.
  221. *
  222. * @param callable $handler A handler that will be called on Exception
  223. *
  224. * @return callable|null The previous exception handler
  225. */
  226. public function setExceptionHandler(callable $handler = null)
  227. {
  228. $prev = $this->exceptionHandler;
  229. $this->exceptionHandler = $handler;
  230. return $prev;
  231. }
  232. /**
  233. * Sets the PHP error levels that throw an exception when a PHP error occurs.
  234. *
  235. * @param int $levels A bit field of E_* constants for thrown errors
  236. * @param bool $replace Replace or amend the previous value
  237. *
  238. * @return int The previous value
  239. */
  240. public function throwAt($levels, $replace = false)
  241. {
  242. $prev = $this->thrownErrors;
  243. $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
  244. if (!$replace) {
  245. $this->thrownErrors |= $prev;
  246. }
  247. $this->reRegister($prev | $this->loggedErrors);
  248. return $prev;
  249. }
  250. /**
  251. * Sets the PHP error levels for which local variables are preserved.
  252. *
  253. * @param int $levels A bit field of E_* constants for scoped errors
  254. * @param bool $replace Replace or amend the previous value
  255. *
  256. * @return int The previous value
  257. */
  258. public function scopeAt($levels, $replace = false)
  259. {
  260. $prev = $this->scopedErrors;
  261. $this->scopedErrors = (int) $levels;
  262. if (!$replace) {
  263. $this->scopedErrors |= $prev;
  264. }
  265. return $prev;
  266. }
  267. /**
  268. * Sets the PHP error levels for which the stack trace is preserved.
  269. *
  270. * @param int $levels A bit field of E_* constants for traced errors
  271. * @param bool $replace Replace or amend the previous value
  272. *
  273. * @return int The previous value
  274. */
  275. public function traceAt($levels, $replace = false)
  276. {
  277. $prev = $this->tracedErrors;
  278. $this->tracedErrors = (int) $levels;
  279. if (!$replace) {
  280. $this->tracedErrors |= $prev;
  281. }
  282. return $prev;
  283. }
  284. /**
  285. * Sets the error levels where the @-operator is ignored.
  286. *
  287. * @param int $levels A bit field of E_* constants for screamed errors
  288. * @param bool $replace Replace or amend the previous value
  289. *
  290. * @return int The previous value
  291. */
  292. public function screamAt($levels, $replace = false)
  293. {
  294. $prev = $this->screamedErrors;
  295. $this->screamedErrors = (int) $levels;
  296. if (!$replace) {
  297. $this->screamedErrors |= $prev;
  298. }
  299. return $prev;
  300. }
  301. /**
  302. * Re-registers as a PHP error handler if levels changed.
  303. */
  304. private function reRegister($prev)
  305. {
  306. if ($prev !== $this->thrownErrors | $this->loggedErrors) {
  307. $handler = set_error_handler('var_dump');
  308. $handler = is_array($handler) ? $handler[0] : null;
  309. restore_error_handler();
  310. if ($handler === $this) {
  311. restore_error_handler();
  312. if ($this->isRoot) {
  313. set_error_handler(array($this, 'handleError'), $this->thrownErrors | $this->loggedErrors);
  314. } else {
  315. set_error_handler(array($this, 'handleError'));
  316. }
  317. }
  318. }
  319. }
  320. /**
  321. * Handles errors by filtering then logging them according to the configured bit fields.
  322. *
  323. * @param int $type One of the E_* constants
  324. * @param string $message
  325. * @param string $file
  326. * @param int $line
  327. *
  328. * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  329. *
  330. * @throws \ErrorException When $this->thrownErrors requests so
  331. *
  332. * @internal
  333. */
  334. public function handleError($type, $message, $file, $line)
  335. {
  336. // Level is the current error reporting level to manage silent error.
  337. // Strong errors are not authorized to be silenced.
  338. $level = error_reporting() | E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED;
  339. $log = $this->loggedErrors & $type;
  340. $throw = $this->thrownErrors & $type & $level;
  341. $type &= $level | $this->screamedErrors;
  342. if (!$type || (!$log && !$throw)) {
  343. return $type && $log;
  344. }
  345. $scope = $this->scopedErrors & $type;
  346. if (4 < $numArgs = func_num_args()) {
  347. $context = $scope ? (func_get_arg(4) ?: array()) : array();
  348. $backtrace = 5 < $numArgs ? func_get_arg(5) : null; // defined on HHVM
  349. } else {
  350. $context = array();
  351. $backtrace = null;
  352. }
  353. if (isset($context['GLOBALS']) && $scope) {
  354. $e = $context; // Whatever the signature of the method,
  355. unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
  356. $context = $e;
  357. }
  358. if (null !== $backtrace && $type & E_ERROR) {
  359. // E_ERROR fatal errors are triggered on HHVM when
  360. // hhvm.error_handling.call_user_handler_on_fatals=1
  361. // which is the way to get their backtrace.
  362. $this->handleFatalError(compact('type', 'message', 'file', 'line', 'backtrace'));
  363. return true;
  364. }
  365. $logMessage = $this->levels[$type].': '.$message;
  366. if (null !== self::$toStringException) {
  367. $errorAsException = self::$toStringException;
  368. self::$toStringException = null;
  369. } elseif (!$throw && !($type & $level)) {
  370. if (isset(self::$silencedErrorCache[$message])) {
  371. $lightTrace = null;
  372. $errorAsException = self::$silencedErrorCache[$message];
  373. ++$errorAsException->count;
  374. } else {
  375. $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3), $type, $file, $line, false) : array();
  376. $errorAsException = new SilencedErrorContext($type, $file, $line, $lightTrace);
  377. }
  378. if (100 < ++self::$silencedErrorCount) {
  379. self::$silencedErrorCache = $lightTrace = array();
  380. self::$silencedErrorCount = 1;
  381. }
  382. self::$silencedErrorCache[$message] = $errorAsException;
  383. if (null === $lightTrace) {
  384. return;
  385. }
  386. } else {
  387. if ($scope) {
  388. $errorAsException = new ContextErrorException($logMessage, 0, $type, $file, $line, $context);
  389. } else {
  390. $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
  391. }
  392. // Clean the trace by removing function arguments and the first frames added by the error handler itself.
  393. if ($throw || $this->tracedErrors & $type) {
  394. $backtrace = $backtrace ?: $errorAsException->getTrace();
  395. $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
  396. $this->traceReflector->setValue($errorAsException, $lightTrace);
  397. } else {
  398. $this->traceReflector->setValue($errorAsException, array());
  399. }
  400. }
  401. if ($throw) {
  402. if (E_USER_ERROR & $type) {
  403. for ($i = 1; isset($backtrace[$i]); ++$i) {
  404. if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
  405. && '__toString' === $backtrace[$i]['function']
  406. && '->' === $backtrace[$i]['type']
  407. && !isset($backtrace[$i - 1]['class'])
  408. && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
  409. ) {
  410. // Here, we know trigger_error() has been called from __toString().
  411. // HHVM is fine with throwing from __toString() but PHP triggers a fatal error instead.
  412. // A small convention allows working around the limitation:
  413. // given a caught $e exception in __toString(), quitting the method with
  414. // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  415. // to make $e get through the __toString() barrier.
  416. foreach ($context as $e) {
  417. if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
  418. if (1 === $i) {
  419. // On HHVM
  420. $errorAsException = $e;
  421. break;
  422. }
  423. self::$toStringException = $e;
  424. return true;
  425. }
  426. }
  427. if (1 < $i) {
  428. // On PHP (not on HHVM), display the original error message instead of the default one.
  429. $this->handleException($errorAsException);
  430. // Stop the process by giving back the error to the native handler.
  431. return false;
  432. }
  433. }
  434. }
  435. }
  436. throw $errorAsException;
  437. }
  438. if ($this->isRecursive) {
  439. $log = 0;
  440. } elseif (self::$stackedErrorLevels) {
  441. self::$stackedErrors[] = array(
  442. $this->loggers[$type][0],
  443. ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG,
  444. $logMessage,
  445. array('exception' => $errorAsException),
  446. );
  447. } else {
  448. try {
  449. $this->isRecursive = true;
  450. $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  451. $this->loggers[$type][0]->log($level, $logMessage, array('exception' => $errorAsException));
  452. } finally {
  453. $this->isRecursive = false;
  454. }
  455. }
  456. return $type && $log;
  457. }
  458. /**
  459. * Handles an exception by logging then forwarding it to another handler.
  460. *
  461. * @param \Exception|\Throwable $exception An exception to handle
  462. * @param array $error An array as returned by error_get_last()
  463. *
  464. * @internal
  465. */
  466. public function handleException($exception, array $error = null)
  467. {
  468. if (null === $error) {
  469. self::$exitCode = 255;
  470. }
  471. if (!$exception instanceof \Exception) {
  472. $exception = new FatalThrowableError($exception);
  473. }
  474. $type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
  475. if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
  476. if ($exception instanceof FatalErrorException) {
  477. if ($exception instanceof FatalThrowableError) {
  478. $error = array(
  479. 'type' => $type,
  480. 'message' => $message = $exception->getMessage(),
  481. 'file' => $exception->getFile(),
  482. 'line' => $exception->getLine(),
  483. );
  484. } else {
  485. $message = 'Fatal '.$exception->getMessage();
  486. }
  487. } elseif ($exception instanceof \ErrorException) {
  488. $message = 'Uncaught '.$exception->getMessage();
  489. } else {
  490. $message = 'Uncaught Exception: '.$exception->getMessage();
  491. }
  492. }
  493. if ($this->loggedErrors & $type) {
  494. try {
  495. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, array('exception' => $exception));
  496. } catch (\Exception $handlerException) {
  497. } catch (\Throwable $handlerException) {
  498. }
  499. }
  500. if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
  501. foreach ($this->getFatalErrorHandlers() as $handler) {
  502. if ($e = $handler->handleError($error, $exception)) {
  503. $exception = $e;
  504. break;
  505. }
  506. }
  507. }
  508. if (empty($this->exceptionHandler)) {
  509. throw $exception; // Give back $exception to the native handler
  510. }
  511. try {
  512. call_user_func($this->exceptionHandler, $exception);
  513. } catch (\Exception $handlerException) {
  514. } catch (\Throwable $handlerException) {
  515. }
  516. if (isset($handlerException)) {
  517. $this->exceptionHandler = null;
  518. $this->handleException($handlerException);
  519. }
  520. }
  521. /**
  522. * Shutdown registered function for handling PHP fatal errors.
  523. *
  524. * @param array $error An array as returned by error_get_last()
  525. *
  526. * @internal
  527. */
  528. public static function handleFatalError(array $error = null)
  529. {
  530. if (null === self::$reservedMemory) {
  531. return;
  532. }
  533. self::$reservedMemory = null;
  534. $handler = set_error_handler('var_dump');
  535. $handler = is_array($handler) ? $handler[0] : null;
  536. restore_error_handler();
  537. if (!$handler instanceof self) {
  538. return;
  539. }
  540. if ($exit = null === $error) {
  541. $error = error_get_last();
  542. }
  543. try {
  544. while (self::$stackedErrorLevels) {
  545. static::unstackErrors();
  546. }
  547. } catch (\Exception $exception) {
  548. // Handled below
  549. } catch (\Throwable $exception) {
  550. // Handled below
  551. }
  552. if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
  553. // Let's not throw anymore but keep logging
  554. $handler->throwAt(0, true);
  555. $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  556. if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
  557. $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
  558. } else {
  559. $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
  560. }
  561. }
  562. try {
  563. if (isset($exception)) {
  564. self::$exitCode = 255;
  565. $handler->handleException($exception, $error);
  566. }
  567. } catch (FatalErrorException $e) {
  568. // Ignore this re-throw
  569. }
  570. if ($exit && self::$exitCode) {
  571. $exitCode = self::$exitCode;
  572. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  573. }
  574. }
  575. /**
  576. * Configures the error handler for delayed handling.
  577. * Ensures also that non-catchable fatal errors are never silenced.
  578. *
  579. * As shown by http://bugs.php.net/42098 and http://bugs.php.net/60724
  580. * PHP has a compile stage where it behaves unusually. To workaround it,
  581. * we plug an error handler that only stacks errors for later.
  582. *
  583. * The most important feature of this is to prevent
  584. * autoloading until unstackErrors() is called.
  585. */
  586. public static function stackErrors()
  587. {
  588. self::$stackedErrorLevels[] = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
  589. }
  590. /**
  591. * Unstacks stacked errors and forwards to the logger.
  592. */
  593. public static function unstackErrors()
  594. {
  595. $level = array_pop(self::$stackedErrorLevels);
  596. if (null !== $level) {
  597. $errorReportingLevel = error_reporting($level);
  598. if ($errorReportingLevel !== ($level | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
  599. // If the user changed the error level, do not overwrite it
  600. error_reporting($errorReportingLevel);
  601. }
  602. }
  603. if (empty(self::$stackedErrorLevels)) {
  604. $errors = self::$stackedErrors;
  605. self::$stackedErrors = array();
  606. foreach ($errors as $error) {
  607. $error[0]->log($error[1], $error[2], $error[3]);
  608. }
  609. }
  610. }
  611. /**
  612. * Gets the fatal error handlers.
  613. *
  614. * Override this method if you want to define more fatal error handlers.
  615. *
  616. * @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
  617. */
  618. protected function getFatalErrorHandlers()
  619. {
  620. return array(
  621. new UndefinedFunctionFatalErrorHandler(),
  622. new UndefinedMethodFatalErrorHandler(),
  623. new ClassNotFoundFatalErrorHandler(),
  624. );
  625. }
  626. private function cleanTrace($backtrace, $type, $file, $line, $throw)
  627. {
  628. $lightTrace = $backtrace;
  629. for ($i = 0; isset($backtrace[$i]); ++$i) {
  630. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  631. $lightTrace = array_slice($lightTrace, 1 + $i);
  632. break;
  633. }
  634. }
  635. if (!($throw || $this->scopedErrors & $type)) {
  636. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  637. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  638. }
  639. }
  640. return $lightTrace;
  641. }
  642. }