feature #1807 Inline original source code in compiled templates (nicolas-grekas)

This PR was submitted for the master branch but it was merged into the 1.x branch instead (closes #1807).

Discussion
----------

Inline original source code in compiled templates

For introspection purposes (e.g. instead of https://github.com/symfony/symfony/pull/15653) it is sometimes useful to be able to retrieve the original template source code.

I propose to inline it commented after the compiled class declaration.
This creates no memory nor cpu overhead while still allowing to get the source with very simple parsing logic.

Commits
-------

c9fb373 Inline original source code in compiled templates
This commit is contained in:
Fabien Potencier
2015-09-10 10:50:56 +02:00
3 changed files with 60 additions and 1 deletions
+7 -1
View File
@@ -593,7 +593,13 @@ class Twig_Environment
public function compileSource($source, $name = null)
{
try {
return $this->compile($this->parse($this->tokenize($source, $name)));
$compiled = $this->compile($this->parse($this->tokenize($source, $name)), $source);
if (isset($source[0])) {
$compiled .= '// '.str_replace(array("\r\n", "\r", "\n"), "\n// ", $source)."\n";
}
return $compiled;
} catch (Twig_Error $e) {
$e->setTemplateFile($name);
throw $e;
+8
View File
@@ -138,6 +138,14 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
*/
}
public function testCompileSource()
{
$twig = new Twig_Environment($this->getMock('Twig_LoaderInterface'));
$expected = file_get_contents(__DIR__.'/Fixtures/environment-compile.php');
$this->assertSame($expected, $twig->compileSource("{{ foo }}\n{{ bar }}\n", 'index'));
}
public function testExtensionsAreNotInitializedWhenRenderingACompiledTemplate()
{
$options = array('cache' => sys_get_temp_dir().'/twig', 'auto_reload' => false, 'debug' => false);
@@ -0,0 +1,45 @@
<?php
/* index */
class __TwigTemplate_e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo twig_escape_filter($this->env, (isset($context["foo"]) ? $context["foo"] : null), "html", null, true);
echo "
";
// line 2
echo twig_escape_filter($this->env, (isset($context["bar"]) ? $context["bar"] : null), "html", null, true);
echo "
";
}
public function getTemplateName()
{
return "index";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 23 => 2, 19 => 1,);
}
}
// {{ foo }}
// {{ bar }}
//