annotate vendor/symfony/debug/ErrorHandler.php @ 0:4c8ae668cc8c

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