Skip to content

Commit

Permalink
node visitorを使う
Browse files Browse the repository at this point in the history
  • Loading branch information
chihiro-adachi committed Jan 17, 2024
1 parent 98e0b15 commit 7863e8e
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/config/eccube/packages/twig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ twig:
# - 'Form/form_div_layout.twig'
date:
timezone: '%timezone%'
base_template_class: 'Eccube\Twig\Template'
# base_template_class: 'Eccube\Twig\Template'
exception_controller: null
76 changes: 76 additions & 0 deletions src/Eccube/Twig/Extension/TemplateEventExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

namespace Eccube\Twig\Extension;

use Twig\Compiler;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;

class TemplateEventExtension extends AbstractExtension
{
public function getNodeVisitors()
{
return [new TemplateEventNodeVisiror()];
}
}

class TemplateEventNodeVisiror implements NodeVisitorInterface
{
public function enterNode(Node $node, Environment $env): Node
{
return $node;
}

public function leaveNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
if (\str_starts_with($node->getTemplateName(), '__string_template__')) {
return $node;
}
$node->setNode('display_start', new Node([new TemplateEventNode(), $node->getNode('display_start')]));
}

return $node;
}

public function getPriority()
{
return 0;
}
}

class TemplateEventNode extends Node
{
public function compile(Compiler $compiler)
{
$compiler
->write('$__eccube__gblobal = $this->env->getGlobals();')
->raw("\n")
->write('$__eccube__eventDispatcher = $__eccube__gblobal[\'event_dispatcher\'];')
->raw("\n")
->write('$__eccube__source = $this->env->getLoader()->getSourceContext($this->getTemplateName())->getCode();')
->raw("\n")
->write('$__eccube__event = new \\Eccube\\Event\\TemplateEvent($this->getTemplateName(), $__eccube__source, $context);')
->raw("\n")
->write('$__eccube__eventDispatcher->dispatch($__eccube__event, $this->getTemplateName());')
->raw("\n")
->write('$context = $__eccube__event->getParameters();')
->raw("\n")
->write('if ($__eccube__event->getSource() !== $__eccube__source) {')
->indent()
->raw("\n")
->write('$__eccube__newTemplate = $this->env->createTemplate($__eccube__event->getSource());')
->raw("\n")
->write('$__eccube__newTemplate->display($__eccube__event->getParameters());')
->raw("\n")
->write('return;')
->raw("\n")
->outdent()
->write('}')
->raw("\n\n")
;
}
}

0 comments on commit 7863e8e

Please sign in to comment.