Skip to content

Commit

Permalink
Adapt Twig node to remove usage of ob_start with Twig 3.9
Browse files Browse the repository at this point in the history
  • Loading branch information
notFloran committed Apr 24, 2024
1 parent e98f3cd commit b3d9020
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/Twig/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Twig\Compiler;
use Twig\Node\Node as Twig_Node;
use Twig\Node\CaptureNode;

class Node extends Twig_Node
{
Expand All @@ -13,6 +14,11 @@ class Node extends Twig_Node
*/
public function __construct(Twig_Node $value, $line, $tag = null)
{
if (class_exists(CaptureNode::class)) {
$value = new CaptureNode($value, $line, $tag);
$value->setAttribute('raw', true);
}

parent::__construct(['value' => $value], ['name' => $tag], $line, $tag);
}

Expand All @@ -21,14 +27,32 @@ public function __construct(Twig_Node $value, $line, $tag = null)
*/
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this)
->write('ob_start();'.PHP_EOL)
->subcompile($this->getNode('value'))
->write('$content = ob_get_clean();'.PHP_EOL)
if (class_exists(CaptureNode::class)) {
$compiler
->addDebugInfo($this)
->indent()
->write("\$content = ")
->subcompile($this->getNode('value'))
->raw("\n")
->outdent()
;
} else {
$compiler
->addDebugInfo($this)
->indent()
->write("ob_start();\n")
->subcompile($this->getNode('value'))
->outdent()
->write("\$content = ob_get_clean();\n")
;
}

$compiler
->write('preg_match("/^\s*/", $content, $matches);'.PHP_EOL)
->write('$lines = explode("\n", $content);'.PHP_EOL)
->write('$content = preg_replace(\'/^\' . $matches[0]. \'/\', "", $lines);'.PHP_EOL)
->write('$content = implode("\n", $content);'.PHP_EOL)
->write('echo $this->env->getExtension("'.Extension::class.'")->getMjml()->render($content);'.PHP_EOL);
->write('$content = implode("\n", $content);'.PHP_EOL);

$compiler->write('echo $this->env->getExtension("'.Extension::class.'")->getMjml()->render($content);'.PHP_EOL);
}
}

0 comments on commit b3d9020

Please sign in to comment.