8000 [WIP] Better exception page by hason · Pull Request #15792 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[WIP] Better exception page #15792

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

2.8.0
-----

* added TwigFlattenExceptionProcessor which adds twig files into the FlattenException

2.7.0
-----

Expand Down
140 changes: 140 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/TwigFlattenExceptionProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Debug;

use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\FlattenExceptionProcessorInterface;

/**
* TwigFlattener adds twig files into FlattenException.
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class TwigFlattenExceptionProcessor implements FlattenExceptionProcessorInterface
{
private $files = array();
private $twig;
private $loadedTemplates;

public function __construct(\Twig_Environment $twig)
{
$this->twig = $twig;
$this->loadedTemplates = new \ReflectionProperty($twig, 'loadedTemplates');
$this->loadedTemplates->setAccessible(true);
}

/**
* {@inheritdoc}
*/
public function process(\Exception $exception, FlattenException $flattenException, $master)
{
$trace = $flattenException->getTrace();
$origTrace = $exception->getTrace();

foreach ($origTrace as $key => $entry) {
$prevKey = $key - 1;

if (!isset($origTrace[$prevKey]) || !isset($entry['class']) || 'Twig_Template' === $entry['class'] || !is_subclass_of($entry['class'], 'Twig_Template')) {
continue;
}

$template = $this->getLoadedTemplate($entry['class']);

if (!$template instanceof \Twig_Template) {
continue;
}

$file = $this->findOrCreateFile($template);

$data = array('file' => $file);
if (isset($origTrace[$prevKey]['line'])) {
$data['line'] = $this->findLineInTemplate($origTrace[$prevKey]['line'], $template);
}

$trace[$prevKey]['related_codes'][] = $data;
}

if (isset($trace[-1]) && $exception instanceof \Twig_Error) {
$name = $exception->getTemplateFile();
$file = $this->findOrCreateFile($name, $name);

$trace[-1]['related_codes'][] = array('file' => $file, 'line' => $exception->getTemplateLine());
}

$flattenException->replaceTrace($trace);
}

private function getLoadedTemplate($class)
{
$loadedTemplates = $this->loadedTemplates->getValue($this->twig);

return isset($loadedTemplates[$class]) ? $loadedTemplates[$class] : null;
}

private function findOrCreateFile($template, $path = null)
{
$name = $template instanceof \Twig_Template ? $template->getTemplateName() : $template;

if (isset($this->files[$name])) {
return $this->files[$name];
}

foreach ($this->files as $key => $file) {
if (isset($file->path) && $file->path == $name) {
return $file;
}
}

$file = (object) array('name' => $name, 'type' => 'twig');

try {
$path = $path ?: $this->twig->getLoader()->getCacheKey($name);
} catch (\Twig_Error_Loader $e) {
}

if (is_file($path)) {
$file->path = $path;
} else {
$source = null;

if (method_exists($template, 'getSource')) {
$source = $template->getSource();
}

if (null === $source) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd move this if as the else of the previous one (and remove $source = null initialization)

try {
$source = $this->twig->getLoader()->getSource($name);
} catch (\Twig_Error_Loader $e) {
}
}

$file->content = $source;
}

return $this->files[$name] = $file;
}

private function findLineInTemplate($line, $template)
{
if (!method_exists($template, 'getDebugInfo')) {
return 1;
}

foreach ($template->getDebugInfo() as $codeLine => $templateLine) {
if ($codeLine <= $line) {
return $templateLine;
}
}

return 1;
}
}
82 changes: 82 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/TwigHighlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Debug;

use Symfony\Component\Debug\Highlighter\Highlighter;

/**
* Simple Twig syntax highlighter
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class TwigHighlighter extends Highlighter
{
protected $regexString = '"[^"\\\\]*?(?:\\\\.[^"\\\\]*?)*?"|\'[^\'\\\\]*?(?:\\\\.[^\'\\\\]*?)*?\'';
protected $regexTags;
protected $regex;

public function __construct()
{
$this->regexTags = '{({{-?|{%-?|{#-?)((?:'.$this->regexString.'|[^"\']*?)+?)(-?}}|-?%}|-?#})}s';
$this->regexKeywords = 'and|or|with';
$this->regex = '
/(?:
(?P<string>'.$this->regexString.')|
(?P<number>\b\d+(?:\.\d+)?\b)|
(?P<variable>(?<!\.)\b[a-z][a-z0-9_]*(?=\.|\[|\s*=))|
(?P<name>\b[a-z0-9_]+(?=\s*\()|(?<=\||\|\s)[a-z0-9_]+\b)|
(?P<operator>(?:\*\*|\.\.|==|!=|>=|<=|\/\/|\?:|[+\-~\*\/%\.=><\|\(\)\[\]\{\}\?:,]))|
(?P<keyword>\b(?:if|and|or|b-and|b-xor|b-or|in|matches|starts with|ends with|is|not|as|import|with|true|false|null|none)\b)
)/xi'
;
}

/**
* {@inheritdoc}
*/
public function highlight($code, $from = 1, $to = -1, $line = -1)
{
$oldCode = htmlspecialchars(str_replace(array("\r\n", "\r"), "\n", $code), ENT_NOQUOTES);
$regex = $this->regex;
$code = preg_replace_callback($this->regexTags, function ($matches) use ($regex) {
if ($matches[1] == '{#') {
return '<span class="comment">' . $matches[0] . '</span>';
}

$matches[2] = preg_replace_callback($regex, function ($match) {
$keys = array_keys($match);

return sprintf('<span class="%s">%s</span>', $keys[count($match) - 2], $match[0]);
}, $matches[2]);

if ($matches[1][1] == '%') {
$matches[2] = preg_replace('/^(\s*)([a-z0-9_]+)/i', '\\1<span class="keyword">\\2</span>', $matches[2]);
}
10000
return '<span class="tag">'.$matches[1].'</span>'.$matches[2].'<span class="tag">'.$matches[3].'</span>';
}, $oldCode);

if ('' == $code) {
$code = $oldCode;
}

return $this->createLines(explode("\n", $code), $from, $to, $line);
}

/**
* {@inheritdoc}
*/
public function supports($file)
{
return 'twig' === pathinfo($file, PATHINFO_EXTENSION);
}
}
44 changes: 14 additions & 30 deletions src/Symfony/Bridge/Twig/Extension/CodeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*/

namespace Symfony\Bridge\Twig\Extension;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\Utils\HtmlUtils;

/**
* Twig extension relate to PHP code and used by the profiler and the default exception templates.
Expand All @@ -21,6 +23,7 @@ class CodeExtension extends \Twig_Extension
private $fileLinkFormat;
private $rootDir;
private $charset;
private $htmlUtils;

/**
* Constructor.
Expand All @@ -29,11 +32,12 @@ class CodeExtension extends \Twig_Extension
* @param string $rootDir The project root directory
* @param string $charset The charset
*/
public function __construct($fileLinkFormat, $rootDir, $charset)
public function __construct($fileLinkFormat, $rootDir, $charset, HtmlUtils $htmlUtils = null)
{
$this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
$this->rootDir = str_replace('/', DIRECTORY_SEPARATOR, dirname($rootDir)).DIRECTORY_SEPARATOR;
$this->charset = $charset;
$this->htmlUtils = $htmlUtils;
}

/**
Expand All @@ -50,6 +54,7 @@ public function getFilters()
new \Twig_SimpleFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))),
new \Twig_SimpleFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))),
new \Twig_SimpleFilter('file_link', array($this, 'getFileLink')),
new \Twig_SimpleFilter('highlight_code', array($this->htmlUtils, 'highlight'), array('is_safe' => array('html'))),
);
}

Expand Down Expand Up @@ -78,48 +83,27 @@ public function abbrMethod($method)
/**
* Formats an array as a string.
*
* @param array $args The argument array
* @param array $args The argument array
* @param FlattenException|null $exception The flatten exception
*
* @return string
*/
public function formatArgs($args)
public function formatArgs($args, $exception = null)
{
$result = array();
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$parts = explode('\\', $item[1]);
$short = array_pop($parts);
$formattedValue = sprintf('<em>object</em>(<abbr title="%s">%s</abbr>)', $item[1], $short);
} elseif ('array' === $item[0]) {
$formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
} elseif ('string' === $item[0]) {
$formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES, $this->charset));
} elseif ('null' === $item[0]) {
$formattedValue = '<em>null</em>';
} elseif ('boolean' === $item[0]) {
$formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
} elseif ('resource' === $item[0]) {
$formattedValue = '<em>resource</em>';
} else {
$formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES, $this->charset), true));
}

$result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
}

return implode(', ', $result);
return $this->htmlUtils->formatArgs($args, $exception);
}

/**
* Formats an array as a string.
*
* @param array $args The argument array
* @param array $args The argument array
* @param FlattenException|null $exception The flatten exception
*
* @return string
*/
public function formatArgsAsText($args)
public function formatArgsAsText($args, $exception = null)
{
return strip_tags($this->formatArgs($args));
return strip_tags($this->formatArgs($args, $exception));
}

/**
Expand Down
Loading
0