|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\wmcontroller\Twig\NodeVisitor; |
| 4 | + |
| 5 | +use Twig\Environment; |
| 6 | +use Twig\Node\ModuleNode; |
| 7 | +use Twig\Node\Node; |
| 8 | +use Twig\Node\TextNode; |
| 9 | +use Twig\NodeVisitor\NodeVisitorInterface; |
| 10 | + |
| 11 | +/** |
| 12 | + * A Twig node visitor that adds debug information around components. |
| 13 | + */ |
| 14 | +class DebugNodeVisitor implements NodeVisitorInterface |
| 15 | +{ |
| 16 | + /** |
| 17 | + * {@inheritdoc} |
| 18 | + */ |
| 19 | + public function enterNode(Node $node, Environment $env): Node |
| 20 | + { |
| 21 | + if (!$env->isDebug()) { |
| 22 | + return $node; |
| 23 | + } |
| 24 | + |
| 25 | + if (!$node instanceof ModuleNode) { |
| 26 | + return $node; |
| 27 | + } |
| 28 | + |
| 29 | + if (!$source = $node->getSourceContext()) { |
| 30 | + return $node; |
| 31 | + } |
| 32 | + |
| 33 | + $name = $source->getName(); |
| 34 | + $path = str_replace(DRUPAL_ROOT . '/', '', $source->getPath()); |
| 35 | + |
| 36 | + if ($this->isNodeEmpty($node->getNode('body'))) { |
| 37 | + // This node is empty. |
| 38 | + return $node; |
| 39 | + } |
| 40 | + |
| 41 | + $nodes = [ |
| 42 | + new TextNode('<!-- TWIG DEBUG -->', 0), |
| 43 | + new TextNode(sprintf('<!-- Template: %s -->', $name), 0), |
| 44 | + ]; |
| 45 | + |
| 46 | + if ($name !== $path) { |
| 47 | + $nodes[] = new TextNode(sprintf('<!-- Path: %s -->', $path), 0); |
| 48 | + } |
| 49 | + |
| 50 | + $node->getNode('display_start') |
| 51 | + ->setNode('_components_debug', new Node($nodes)); |
| 52 | + |
| 53 | + return $node; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * {@inheritdoc} |
| 58 | + */ |
| 59 | + public function leaveNode(Node $node, Environment $env): ?Node |
| 60 | + { |
| 61 | + return $node; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * {@inheritdoc} |
| 66 | + */ |
| 67 | + public function getPriority(): int |
| 68 | + { |
| 69 | + return 0; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Checks whether a node - or one of its subnodes - actually contain something. |
| 74 | + */ |
| 75 | + protected function isNodeEmpty(Node $node): bool |
| 76 | + { |
| 77 | + $subNodes = iterator_to_array($node); |
| 78 | + if (count($subNodes) > 1) { |
| 79 | + return FALSE; |
| 80 | + } |
| 81 | + |
| 82 | + foreach ($subNodes as $subNode) { |
| 83 | + if (!$this->isNodeEmpty($subNode)) { |
| 84 | + return FALSE; |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return TRUE; |
| 89 | + } |
| 90 | +} |
0 commit comments