Skip to content

[WIP][DX] Better exception page #12363

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 4 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
6 changes: 6 additions & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGELOG
=========

2.7.0
-----

* added TwigFlattener which adds twig files into the FlattenException
* added PHP and Twig syntax highlighters

2.5.0
-----

Expand Down
75 changes: 75 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/Highlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?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;

/**
* The base class for syntax highlighters
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
abstract class Highlighter
{
/**
* Highlights a code
*
* @param string $code The code
* @param int $line The selected line number
* @param int $count The number of lines above and below the selected line
*
* @return string The highlighted code
*/
abstract public function highlight($code, $line = -1, $count = -1);

/**
* Returns true if this class is able to highlight the given file name.
*
* @param string $name The file name
*
* @return bool true if this class supports the given file name, false otherwise
*/
abstract public function supports($file);

protected function createLines($lines, $line, $count)
{
$code = '';
$lastOpenSpan = '';

if ($count < 0) {
$count = count($lines);
}

$from = max(max($line, 1) - $count, 1);
if ($from > 1 && 0 !== strpos($line[$from - 1], '<span')) {
for ($i = $from - 2; $i >= 0; $i--) {
if (preg_match('#^.*(</?span[^>]*>)#', $lines[$i], $match) && '/' != $match[1][1]) {
$lastOpenSpan = $match[1];
break;
}
}
}

for ($i = $from, $max = min(max($line, 1) + $count, count($lines)); $i <= $max; $i++) {
$code .= '<li'.($i == $line ? ' class="selected"' : '').'><code>'.($lastOpenSpan.$lines[$i - 1]);
if (preg_match('#^.*(</?span[^>]*>)#', $lines[$i - 1], $match)) {
$lastOpenSpan = '/' != $match[1][1] ? $match[1] : '';
}

if ($lastOpenSpan) {
$code .= '</span>';
}

$code .= "</code></li>\n";
}

return '<ol class="code" start="'.max($line - $count, 1).'">'.$code.'</ol>';
}
}
79 changes: 79 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/PHPHighlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?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;

/**
* Simple PHP syntax highlighter
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class PHPHighlighter extends Highlighter
{
private $styles;
private $regex;

public function __construct()
{
$style = ' style="color: %s"';
$this->styles = array(
' class="comment"' => sprintf($style, ini_get('highlight.comment')),
' class="name"' => sprintf($style, ini_get('highlight.default')),
' class="tag"' => sprintf($style, ini_get('highlight.html')),
' class="operator"' => sprintf($style, ini_get('highlight.keyword')),
' class="string"' => sprintf($style, ini_get('highlight.string')),
);

$this->regex = '
/(?:
(?P<variable>\$[a-zA-Z0-9]+)|
(?P<keyword>
\b(?:__halt_compiler|abstract|and|array|as|break|callable|case|catch|class|clone|const|continue|
declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|
final|finally|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|
list|namespace|new|or|print|private|protected|public|require|require_once|return|static|switch|throw|trait|try|
unset|use|var|while|xor|yield)(?![^<"\']*?["\'])\b
)
)/ix'
;
}

/**
* {@inheritdoc}
*/
public function highlight($code, $line = -1, $count = -1)
{
// highlight_file could throw warnings
// see https://bugs.php.net/bug.php?id=25725
$code = @highlight_string($code, true);
// remove main code/span tags
$code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code);

$code = $this->createLines(preg_split('#<br />#', $code), $line, $count);

$code = str_replace('&nbsp;', ' ', $code);
$code = str_replace(array_values($this->styles), array_keys($this->styles), $code);
$code = preg_replace_callback($this->regex, function ($match) {
$keys = array_keys($match);
return sprintf('<span class="%s">%s</span>', $keys[count($match) - 2], $match[0]);
}, $code);

return $code;
}

/**
* {@inheritdoc}
*/
public function supports($file)
{
return 'php' === pathinfo($file, PATHINFO_EXTENSION);
}
}
91 changes: 91 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/TwigFlattener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?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\ExceptionFlattenerInterface;

/**
* TwigFlattener adds twig files into FlattenException
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class TwigFlattener implements ExceptionFlattenerInterface
{
private $loader;

public function __construct(\Twig_LoaderInterface $loader)
{
$this->loader = $loader;
}

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

switch (count($trace) - count($origTrace)) {
case 0:
$from = 0;
break;
case 1:
$from = 1;
break;
default:
throw new \InvalidArgumentException();
}

foreach ($origTrace as $key => $entry) {
if (!isset($origTrace[$key - 1]) || !isset($entry['class']) || 'Twig_Template' === $entry['class'] || !is_subclass_of($entry['class'], 'Twig_Template')) {
continue;
}

$template = unserialize(sprintf('O:%d:"%s":0:{}', strlen($entry['class']), $entry['class']));

$data = array('name' => $template->getTemplateName());
$path = $this->loader->getCacheKey($data['name']);
if (is_file($path)) {
$data['path'] = $path;
}

if (isset($origTrace[$key - 1]['line'])) {
$line = $origTrace[$key - 1]['line'];
foreach ($template->getDebugInfo() as $codeLine => $templateLine) {
if ($codeLine <= $line) {
$data['line'] = $templateLine;
break;
}
}
}

$trace[$from + $key - 1]['related_files'][] = $data;
$trace[$from + $key - 1]['tags'][] = 'twig';
}

if ($from == 1 && $exception instanceof \Twig_Error) {
$data = array(
'path' => $exception->getTemplateFile(),
'line' => $exception->getTemplateLine(),
);

$trace[0]['related_files'][] = $data;
$trace[0]['tags'][] = 'twig';
}

$flattenException->setRawTrace($trace);

return $flattenException;
}
}
75 changes: 75 additions & 0 deletions src/Symfony/Bridge/Twig/Debug/TwigHighlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?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;

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

Choose a reason for hiding this comment

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

should be private


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, $line = -1, $count = -1)
{
$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]);
}

return '<span class="tag">'.$matches[1].'</span>'.$matches[2].'<span class="tag">'.$matches[3].'</span>';
}, htmlspecialchars(str_replace(array("\r\n", "\r"), "\n", $code), ENT_NOQUOTES));

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

/**
* {@inheritdoc}
*/
public function supports($file)
{
return 'twig' === pathinfo($file, PATHINFO_EXTENSION);
}
}
Loading