8a5dc05d75084a5242064daece5b060e0387abac
[yaffs-website] / web / core / lib / Drupal / Core / Template / TwigNodeVisitor.php
1 <?php
2
3 namespace Drupal\Core\Template;
4
5 /**
6  * Provides a Twig_NodeVisitor to change the generated parse-tree.
7  *
8  * This is used to ensure that everything printed is wrapped via the
9  * TwigExtension->renderVar() function in order to just write {{ content }}
10  * in templates instead of having to write {{ render_var(content) }}.
11  *
12  * @see twig_render
13  */
14 class TwigNodeVisitor extends \Twig_BaseNodeVisitor {
15
16   /**
17    * {@inheritdoc}
18    */
19   protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) {
20     return $node;
21   }
22
23   /**
24    * {@inheritdoc}
25    */
26   protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) {
27     // We use this to inject a call to render_var -> TwigExtension->renderVar()
28     // before anything is printed.
29     if ($node instanceof \Twig_Node_Print) {
30       if (!empty($this->skipRenderVarFunction)) {
31         // No need to add the callback, we have escape active already.
32         unset($this->skipRenderVarFunction);
33         return $node;
34       }
35       $class = get_class($node);
36       $line = $node->getTemplateLine();
37       return new $class(
38         new \Twig_Node_Expression_Function('render_var', new \Twig_Node([$node->getNode('expr')]), $line),
39         $line
40       );
41     }
42     // Change the 'escape' filter to our own 'drupal_escape' filter.
43     elseif ($node instanceof \Twig_Node_Expression_Filter) {
44       $name = $node->getNode('filter')->getAttribute('value');
45       if ('escape' == $name || 'e' == $name) {
46         // Use our own escape filter that is SafeMarkup aware.
47         $node->getNode('filter')->setAttribute('value', 'drupal_escape');
48
49         // Store that we have a filter active already that knows
50         // how to deal with render arrays.
51         $this->skipRenderVarFunction = TRUE;
52       }
53     }
54
55     return $node;
56   }
57
58   /**
59    * {@inheritdoc}
60    */
61   public function getPriority() {
62     // Just above the Optimizer, which is the normal last one.
63     return 256;
64   }
65
66 }