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