annotate vendor/symfony/debug/ExceptionHandler.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 Symfony\Component\Debug\Exception\FlattenException;
Chris@0 15 use Symfony\Component\Debug\Exception\OutOfMemoryException;
Chris@0 16 use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
Chris@0 17
Chris@0 18 /**
Chris@0 19 * ExceptionHandler converts an exception to a Response object.
Chris@0 20 *
Chris@0 21 * It is mostly useful in debug mode to replace the default PHP/XDebug
Chris@0 22 * output with something prettier and more useful.
Chris@0 23 *
Chris@0 24 * As this class is mainly used during Kernel boot, where nothing is yet
Chris@0 25 * available, the Response content is always HTML.
Chris@0 26 *
Chris@0 27 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 28 * @author Nicolas Grekas <p@tchwork.com>
Chris@0 29 */
Chris@0 30 class ExceptionHandler
Chris@0 31 {
Chris@0 32 private $debug;
Chris@0 33 private $charset;
Chris@0 34 private $handler;
Chris@0 35 private $caughtBuffer;
Chris@0 36 private $caughtLength;
Chris@0 37 private $fileLinkFormat;
Chris@0 38
Chris@0 39 public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
Chris@0 40 {
Chris@0 41 $this->debug = $debug;
Chris@0 42 $this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
Chris@0 43 $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
Chris@0 44 }
Chris@0 45
Chris@0 46 /**
Chris@0 47 * Registers the exception handler.
Chris@0 48 *
Chris@0 49 * @param bool $debug Enable/disable debug mode, where the stack trace is displayed
Chris@0 50 * @param string|null $charset The charset used by exception messages
Chris@0 51 * @param string|null $fileLinkFormat The IDE link template
Chris@0 52 *
Chris@0 53 * @return static
Chris@0 54 */
Chris@0 55 public static function register($debug = true, $charset = null, $fileLinkFormat = null)
Chris@0 56 {
Chris@0 57 $handler = new static($debug, $charset, $fileLinkFormat);
Chris@0 58
Chris@0 59 $prev = set_exception_handler(array($handler, 'handle'));
Chris@0 60 if (is_array($prev) && $prev[0] instanceof ErrorHandler) {
Chris@0 61 restore_exception_handler();
Chris@0 62 $prev[0]->setExceptionHandler(array($handler, 'handle'));
Chris@0 63 }
Chris@0 64
Chris@0 65 return $handler;
Chris@0 66 }
Chris@0 67
Chris@0 68 /**
Chris@0 69 * Sets a user exception handler.
Chris@0 70 *
Chris@0 71 * @param callable $handler An handler that will be called on Exception
Chris@0 72 *
Chris@0 73 * @return callable|null The previous exception handler if any
Chris@0 74 */
Chris@0 75 public function setHandler(callable $handler = null)
Chris@0 76 {
Chris@0 77 $old = $this->handler;
Chris@0 78 $this->handler = $handler;
Chris@0 79
Chris@0 80 return $old;
Chris@0 81 }
Chris@0 82
Chris@0 83 /**
Chris@0 84 * Sets the format for links to source files.
Chris@0 85 *
Chris@0 86 * @param string|FileLinkFormatter $fileLinkFormat The format for links to source files
Chris@0 87 *
Chris@0 88 * @return string The previous file link format
Chris@0 89 */
Chris@0 90 public function setFileLinkFormat($fileLinkFormat)
Chris@0 91 {
Chris@0 92 $old = $this->fileLinkFormat;
Chris@0 93 $this->fileLinkFormat = $fileLinkFormat;
Chris@0 94
Chris@0 95 return $old;
Chris@0 96 }
Chris@0 97
Chris@0 98 /**
Chris@0 99 * Sends a response for the given Exception.
Chris@0 100 *
Chris@0 101 * To be as fail-safe as possible, the exception is first handled
Chris@0 102 * by our simple exception handler, then by the user exception handler.
Chris@0 103 * The latter takes precedence and any output from the former is cancelled,
Chris@0 104 * if and only if nothing bad happens in this handling path.
Chris@0 105 */
Chris@0 106 public function handle(\Exception $exception)
Chris@0 107 {
Chris@0 108 if (null === $this->handler || $exception instanceof OutOfMemoryException) {
Chris@0 109 $this->sendPhpResponse($exception);
Chris@0 110
Chris@0 111 return;
Chris@0 112 }
Chris@0 113
Chris@0 114 $caughtLength = $this->caughtLength = 0;
Chris@0 115
Chris@0 116 ob_start(function ($buffer) {
Chris@0 117 $this->caughtBuffer = $buffer;
Chris@0 118
Chris@0 119 return '';
Chris@0 120 });
Chris@0 121
Chris@0 122 $this->sendPhpResponse($exception);
Chris@0 123 while (null === $this->caughtBuffer && ob_end_flush()) {
Chris@0 124 // Empty loop, everything is in the condition
Chris@0 125 }
Chris@0 126 if (isset($this->caughtBuffer[0])) {
Chris@0 127 ob_start(function ($buffer) {
Chris@0 128 if ($this->caughtLength) {
Chris@0 129 // use substr_replace() instead of substr() for mbstring overloading resistance
Chris@0 130 $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
Chris@0 131 if (isset($cleanBuffer[0])) {
Chris@0 132 $buffer = $cleanBuffer;
Chris@0 133 }
Chris@0 134 }
Chris@0 135
Chris@0 136 return $buffer;
Chris@0 137 });
Chris@0 138
Chris@0 139 echo $this->caughtBuffer;
Chris@0 140 $caughtLength = ob_get_length();
Chris@0 141 }
Chris@0 142 $this->caughtBuffer = null;
Chris@0 143
Chris@0 144 try {
Chris@0 145 call_user_func($this->handler, $exception);
Chris@0 146 $this->caughtLength = $caughtLength;
Chris@0 147 } catch (\Exception $e) {
Chris@0 148 if (!$caughtLength) {
Chris@0 149 // All handlers failed. Let PHP handle that now.
Chris@0 150 throw $exception;
Chris@0 151 }
Chris@0 152 }
Chris@0 153 }
Chris@0 154
Chris@0 155 /**
Chris@0 156 * Sends the error associated with the given Exception as a plain PHP response.
Chris@0 157 *
Chris@0 158 * This method uses plain PHP functions like header() and echo to output
Chris@0 159 * the response.
Chris@0 160 *
Chris@0 161 * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
Chris@0 162 */
Chris@0 163 public function sendPhpResponse($exception)
Chris@0 164 {
Chris@0 165 if (!$exception instanceof FlattenException) {
Chris@0 166 $exception = FlattenException::create($exception);
Chris@0 167 }
Chris@0 168
Chris@0 169 if (!headers_sent()) {
Chris@0 170 header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
Chris@0 171 foreach ($exception->getHeaders() as $name => $value) {
Chris@0 172 header($name.': '.$value, false);
Chris@0 173 }
Chris@0 174 header('Content-Type: text/html; charset='.$this->charset);
Chris@0 175 }
Chris@0 176
Chris@0 177 echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
Chris@0 178 }
Chris@0 179
Chris@0 180 /**
Chris@0 181 * Gets the full HTML content associated with the given exception.
Chris@0 182 *
Chris@0 183 * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
Chris@0 184 *
Chris@0 185 * @return string The HTML content as a string
Chris@0 186 */
Chris@0 187 public function getHtml($exception)
Chris@0 188 {
Chris@0 189 if (!$exception instanceof FlattenException) {
Chris@0 190 $exception = FlattenException::create($exception);
Chris@0 191 }
Chris@0 192
Chris@0 193 return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
Chris@0 194 }
Chris@0 195
Chris@0 196 /**
Chris@0 197 * Gets the HTML content associated with the given exception.
Chris@0 198 *
Chris@0 199 * @param FlattenException $exception A FlattenException instance
Chris@0 200 *
Chris@0 201 * @return string The content as a string
Chris@0 202 */
Chris@0 203 public function getContent(FlattenException $exception)
Chris@0 204 {
Chris@0 205 switch ($exception->getStatusCode()) {
Chris@0 206 case 404:
Chris@0 207 $title = 'Sorry, the page you are looking for could not be found.';
Chris@0 208 break;
Chris@0 209 default:
Chris@0 210 $title = 'Whoops, looks like something went wrong.';
Chris@0 211 }
Chris@0 212
Chris@0 213 $content = '';
Chris@0 214 if ($this->debug) {
Chris@0 215 try {
Chris@0 216 $count = count($exception->getAllPrevious());
Chris@0 217 $total = $count + 1;
Chris@0 218 foreach ($exception->toArray() as $position => $e) {
Chris@0 219 $ind = $count - $position + 1;
Chris@0 220 $class = $this->formatClass($e['class']);
Chris@0 221 $message = nl2br($this->escapeHtml($e['message']));
Chris@0 222 $content .= sprintf(<<<'EOF'
Chris@0 223 <h2 class="block_exception clear_fix">
Chris@0 224 <span class="exception_counter">%d/%d</span>
Chris@0 225 <span class="exception_title">%s%s:</span>
Chris@0 226 <span class="exception_message">%s</span>
Chris@0 227 </h2>
Chris@0 228 <div class="block">
Chris@0 229 <ol class="traces list_exception">
Chris@0 230
Chris@0 231 EOF
Chris@0 232 , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
Chris@0 233 foreach ($e['trace'] as $trace) {
Chris@0 234 $content .= ' <li>';
Chris@0 235 if ($trace['function']) {
Chris@0 236 $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
Chris@0 237 }
Chris@0 238 if (isset($trace['file']) && isset($trace['line'])) {
Chris@0 239 $content .= $this->formatPath($trace['file'], $trace['line']);
Chris@0 240 }
Chris@0 241 $content .= "</li>\n";
Chris@0 242 }
Chris@0 243
Chris@0 244 $content .= " </ol>\n</div>\n";
Chris@0 245 }
Chris@0 246 } catch (\Exception $e) {
Chris@0 247 // something nasty happened and we cannot throw an exception anymore
Chris@0 248 if ($this->debug) {
Chris@0 249 $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
Chris@0 250 } else {
Chris@0 251 $title = 'Whoops, looks like something went wrong.';
Chris@0 252 }
Chris@0 253 }
Chris@0 254 }
Chris@0 255
Chris@0 256 return <<<EOF
Chris@0 257 <div id="sf-resetcontent" class="sf-reset">
Chris@0 258 <h1>$title</h1>
Chris@0 259 $content
Chris@0 260 </div>
Chris@0 261 EOF;
Chris@0 262 }
Chris@0 263
Chris@0 264 /**
Chris@0 265 * Gets the stylesheet associated with the given exception.
Chris@0 266 *
Chris@0 267 * @param FlattenException $exception A FlattenException instance
Chris@0 268 *
Chris@0 269 * @return string The stylesheet as a string
Chris@0 270 */
Chris@0 271 public function getStylesheet(FlattenException $exception)
Chris@0 272 {
Chris@0 273 return <<<'EOF'
Chris@0 274 .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
Chris@0 275 .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
Chris@0 276 .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
Chris@0 277 .sf-reset .clear_fix { display:inline-block; }
Chris@0 278 .sf-reset * html .clear_fix { height:1%; }
Chris@0 279 .sf-reset .clear_fix { display:block; }
Chris@0 280 .sf-reset, .sf-reset .block { margin: auto }
Chris@0 281 .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
Chris@0 282 .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
Chris@0 283 .sf-reset strong { font-weight:bold; }
Chris@0 284 .sf-reset a { color:#6c6159; cursor: default; }
Chris@0 285 .sf-reset a img { border:none; }
Chris@0 286 .sf-reset a:hover { text-decoration:underline; }
Chris@0 287 .sf-reset em { font-style:italic; }
Chris@0 288 .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
Chris@0 289 .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
Chris@0 290 .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
Chris@0 291 .sf-reset .exception_message { margin-left: 3em; display: block; }
Chris@0 292 .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
Chris@0 293 .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
Chris@0 294 border-bottom-right-radius: 16px;
Chris@0 295 border-bottom-left-radius: 16px;
Chris@0 296 border-bottom:1px solid #ccc;
Chris@0 297 border-right:1px solid #ccc;
Chris@0 298 border-left:1px solid #ccc;
Chris@0 299 word-wrap: break-word;
Chris@0 300 }
Chris@0 301 .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
Chris@0 302 border-top-left-radius: 16px;
Chris@0 303 border-top-right-radius: 16px;
Chris@0 304 border-top:1px solid #ccc;
Chris@0 305 border-right:1px solid #ccc;
Chris@0 306 border-left:1px solid #ccc;
Chris@0 307 overflow: hidden;
Chris@0 308 word-wrap: break-word;
Chris@0 309 }
Chris@0 310 .sf-reset a { background:none; color:#868686; text-decoration:none; }
Chris@0 311 .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
Chris@0 312 .sf-reset ol { padding: 10px 0; }
Chris@0 313 .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
Chris@0 314 border-radius: 10px;
Chris@0 315 border: 1px solid #ccc;
Chris@0 316 }
Chris@0 317 EOF;
Chris@0 318 }
Chris@0 319
Chris@0 320 private function decorate($content, $css)
Chris@0 321 {
Chris@0 322 return <<<EOF
Chris@0 323 <!DOCTYPE html>
Chris@0 324 <html>
Chris@0 325 <head>
Chris@0 326 <meta charset="{$this->charset}" />
Chris@0 327 <meta name="robots" content="noindex,nofollow" />
Chris@0 328 <style>
Chris@0 329 /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
Chris@0 330 html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
Chris@0 331
Chris@0 332 html { background: #eee; padding: 10px }
Chris@0 333 img { border: 0; }
Chris@0 334 #sf-resetcontent { width:970px; margin:0 auto; }
Chris@0 335 $css
Chris@0 336 </style>
Chris@0 337 </head>
Chris@0 338 <body ondblclick="var t = event.target; if (t.title && !t.href) { var f = t.innerHTML; t.innerHTML = t.title; t.title = f; }">
Chris@0 339 $content
Chris@0 340 </body>
Chris@0 341 </html>
Chris@0 342 EOF;
Chris@0 343 }
Chris@0 344
Chris@0 345 private function formatClass($class)
Chris@0 346 {
Chris@0 347 $parts = explode('\\', $class);
Chris@0 348
Chris@0 349 return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
Chris@0 350 }
Chris@0 351
Chris@0 352 private function formatPath($path, $line)
Chris@0 353 {
Chris@0 354 $file = $this->escapeHtml(preg_match('#[^/\\\\]*+$#', $path, $file) ? $file[0] : $path);
Chris@0 355 $fmt = $this->fileLinkFormat;
Chris@0 356
Chris@0 357 if ($fmt && $link = is_string($fmt) ? strtr($fmt, array('%f' => $path, '%l' => $line)) : $fmt->format($path, $line)) {
Chris@0 358 return sprintf(' in <a href="%s" title="Go to source">%s line %d</a>', $this->escapeHtml($link), $file, $line);
Chris@0 359 }
Chris@0 360
Chris@0 361 return sprintf(' in <a title="%s line %3$d">%s line %d</a>', $this->escapeHtml($path), $file, $line);
Chris@0 362 }
Chris@0 363
Chris@0 364 /**
Chris@0 365 * Formats an array as a string.
Chris@0 366 *
Chris@0 367 * @param array $args The argument array
Chris@0 368 *
Chris@0 369 * @return string
Chris@0 370 */
Chris@0 371 private function formatArgs(array $args)
Chris@0 372 {
Chris@0 373 $result = array();
Chris@0 374 foreach ($args as $key => $item) {
Chris@0 375 if ('object' === $item[0]) {
Chris@0 376 $formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
Chris@0 377 } elseif ('array' === $item[0]) {
Chris@0 378 $formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
Chris@0 379 } elseif ('null' === $item[0]) {
Chris@0 380 $formattedValue = '<em>null</em>';
Chris@0 381 } elseif ('boolean' === $item[0]) {
Chris@0 382 $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
Chris@0 383 } elseif ('resource' === $item[0]) {
Chris@0 384 $formattedValue = '<em>resource</em>';
Chris@0 385 } else {
Chris@0 386 $formattedValue = str_replace("\n", '', $this->escapeHtml(var_export($item[1], true)));
Chris@0 387 }
Chris@0 388
Chris@0 389 $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
Chris@0 390 }
Chris@0 391
Chris@0 392 return implode(', ', $result);
Chris@0 393 }
Chris@0 394
Chris@0 395 /**
Chris@0 396 * HTML-encodes a string.
Chris@0 397 */
Chris@0 398 private function escapeHtml($str)
Chris@0 399 {
Chris@0 400 return htmlspecialchars($str, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset);
Chris@0 401 }
Chris@0 402 }