ErrorHandler.php 26 KB

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