* * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Debug; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Debug\Exception\FlattenException; /** * ExceptionHandler converts an exception to a Response object. * * It is mostly useful in debug mode to replace the default PHP/XDebug * output with something prettier and more useful. * * As this class is mainly used during Kernel boot, where nothing is yet * available, the Response content is always HTML. * * @author Fabien Potencier */ class ExceptionHandler { private $debug; private $charset; public function __construct($debug = true, $charset = 'UTF-8') { $this->debug = $debug; $this->charset = $charset; } /** * Registers the exception handler. * * @param bool $debug * * @return ExceptionHandler The registered exception handler */ public static function register($debug = true) { $handler = new static($debug); set_exception_handler(array($handler, 'handle')); return $handler; } /** * Sends a response for the given Exception. * * If you have the Symfony HttpFoundation component installed, * this method will use it to create and send the response. If not, * it will fallback to plain PHP functions. * * @param \Exception $exception An \Exception instance * * @see sendPhpResponse() * @see createResponse() */ public function handle(\Exception $exception) { if (class_exists('Symfony\Component\HttpFoundation\Response')) { $this->createResponse($exception)->send(); } else { $this->sendPhpResponse($exception); } } /** * Sends the error associated with the given Exception as a plain PHP response. * * This method uses plain PHP functions like header() and echo to output * the response. * * @param \Exception|FlattenException $exception An \Exception instance */ public function sendPhpResponse($exception) { if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } if (!headers_sent()) { header(sprintf('HTTP/1.0 %s', $exception->getStatusCode())); foreach ($exception->getHeaders() as $name => $value) { header($name.': '.$value, false); } } echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception)); } /** * Creates the error Response associated with the given Exception. * * @param \Exception|FlattenException $exception An \Exception instance * * @return Response A Response instance */ public function createResponse($exception) { if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } return new Response($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders()); } /** * Gets the HTML content associated with the given exception. * * @param FlattenException $exception A FlattenException instance * * @return string The content as a string */ public function getContent(FlattenException $exception) { switch ($exception->getStatusCode()) { case 404: $title = 'Sorry, the page you are looking for could not be found.'; break; default: $title = 'Whoops, looks like something went wrong.'; } $content = ''; $flags = PHP_VERSION_ID >= 50400 ? ENT_QUOTES | ENT_SUBSTITUTE : ENT_QUOTES; if ($this->debug) { try { $count = count($exception->getAllPrevious()); $total = $count + 1; foreach ($exception->toArray() as $position => $e) { $ind = $count - $position + 1; $class = $this->abbrClass($e['class']); $message = nl2br(htmlspecialchars($e['message'], $flags, $this->charset)); $content .= sprintf(<<

%d/%d %s: %s

    EOF , $ind, $total, $class, $message); foreach ($e['trace'] as $trace) { $content .= '
  1. '; if ($trace['function']) { $content .= sprintf('at %s%s%s(%s)', $this->abbrClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args'])); } if (isset($trace['file']) && isset($trace['line'])) { if ($linkFormat = ini_get('xdebug.file_link_format')) { $link = str_replace(array('%f', '%l'), array($trace['file'], $trace['line']), $linkFormat); $content .= sprintf(' in %s line %s', $link, $trace['file'], $trace['line']); } else { $content .= sprintf(' in %s line %s', $trace['file'], $trace['line']); } } $content .= "
  2. \n"; } $content .= "
\n
\n"; } } catch (\Exception $e) { // something nasty happened and we cannot throw an exception anymore if ($this->debug) { $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), htmlspecialchars($e->getMessage(), $flags, $this->charset)); } else { $title = 'Whoops, looks like something went wrong.'; } } } return <<

$title

$content EOF; } /** * Gets the stylesheet associated with the given exception. * * @param FlattenException $exception A FlattenException instance * * @return string The stylesheet as a string */ public function getStylesheet(FlattenException $exception) { return << $content EOF; } private function abbrClass($class) { $parts = explode('\\', $class); return sprintf("%s", $class, array_pop($parts)); } /** * Formats an array as a string. * * @param array $args The argument array * * @return string */ private function formatArgs(array $args) { if (PHP_VERSION_ID >= 50400) { $flags = ENT_QUOTES | ENT_SUBSTITUTE; } else { $flags = ENT_QUOTES; } $result = array(); foreach ($args as $key => $item) { if ('object' === $item[0]) { $formattedValue = sprintf("object(%s)", $this->abbrClass($item[1])); } elseif ('array' === $item[0]) { $formattedValue = sprintf("array(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]); } elseif ('string' === $item[0]) { $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], $flags, $this->charset)); } elseif ('null' === $item[0]) { $formattedValue = 'null'; } elseif ('boolean' === $item[0]) { $formattedValue = ''.strtolower(var_export($item[1], true)).''; } elseif ('resource' === $item[0]) { $formattedValue = 'resource'; } else { $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], $flags, $this->charset), true)); } $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue); } return implode(', ', $result); } }