TwigNodeTrans.php 5.92 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php

/**
 * @file
 * Contains \Drupal\Core\Template\TwigNodeTrans.
 *
 * This Twig extension was originally based on Twig i18n extension. It has been
 * severely modified to work properly with the complexities of the Drupal
 * translation system.
 *
 * @see http://twig.sensiolabs.org/doc/extensions/i18n.html
 * @see https://github.com/fabpot/Twig-extensions
 */

namespace Drupal\Core\Template;

17
use Drupal\Component\Utility\Unicode;
18
use Drupal\Core\Site\Settings;
19

20 21 22 23 24 25 26 27
/**
 * A class that defines the Twig 'trans' tag for Drupal.
 */
class TwigNodeTrans extends \Twig_Node {

  /**
   * {@inheritdoc}
   */
28
  public function __construct(\Twig_NodeInterface $body, \Twig_NodeInterface $plural = NULL, \Twig_Node_Expression $count = NULL, \Twig_Node_Expression $options = NULL, $lineno, $tag = NULL) {
29 30 31
    parent::__construct(array(
      'count' => $count,
      'body' => $body,
32 33
      'plural' => $plural,
      'options' => $options,
34 35 36 37 38 39 40 41 42
    ), array(), $lineno, $tag);
  }

  /**
   * {@inheritdoc}
   */
  public function compile(\Twig_Compiler $compiler) {
    $compiler->addDebugInfo($this);

43 44
    $options = $this->getNode('options');

45 46 47 48 49 50 51 52 53
    list($singular, $tokens) = $this->compileString($this->getNode('body'));
    $plural = NULL;

    if (NULL !== $this->getNode('plural')) {
      list($plural, $pluralTokens) = $this->compileString($this->getNode('plural'));
      $tokens = array_merge($tokens, $pluralTokens);
    }

    // Start writing with the function to be called.
54
    $compiler->write('echo ' . (empty($plural) ? 't' : '\Drupal::translation()->formatPlural') . '(');
55 56 57 58 59 60 61 62 63 64 65 66 67 68

    // Move the count to the beginning of the parameters list.
    if (!empty($plural)) {
      $compiler->raw('abs(')->subcompile($this->getNode('count'))->raw('), ');
    }

    // Write the singular text parameter.
    $compiler->subcompile($singular);

    // Write the plural text parameter, if necessary.
    if (!empty($plural)) {
      $compiler->raw(', ')->subcompile($plural);
    }

69 70 71 72 73 74 75 76 77 78 79
    // Write any tokens found as an associative array parameter, otherwise just
    // leave as an empty array.
    $compiler->raw(', array(');
    foreach ($tokens as $token) {
      $compiler->string($token->getAttribute('placeholder'))->raw(' => ')->subcompile($token)->raw(', ');
    }
    $compiler->raw(')');

    // Write any options passed.
    if (!empty($options)) {
      $compiler->raw(', ')->subcompile($options);
80 81 82 83 84
    }

    // Write function closure.
    $compiler->raw(')');

85
    // @todo Add debug output, see https://www.drupal.org/node/2512672
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    // End writing.
    $compiler->raw(";\n");
  }

  /**
   * Extracts the text and tokens for the "trans" tag.
   *
   * @param \Twig_NodeInterface $body
   *   The node to compile.
   *
   * @return array
   *   Returns an array containing the two following parameters:
   *   - string $text
   *       The extracted text.
   *   - array $tokens
   *       The extracted tokens as new \Twig_Node_Expression_Name instances.
   */
  protected function compileString(\Twig_NodeInterface $body) {
    if ($body instanceof \Twig_Node_Expression_Name || $body instanceof \Twig_Node_Expression_Constant || $body instanceof \Twig_Node_Expression_TempName) {
      return array($body, array());
    }

    $tokens = array();
    if (count($body)) {
      $text = '';

      foreach ($body as $node) {
        if (get_class($node) === 'Twig_Node' && $node->getNode(0) instanceof \Twig_Node_SetTemp) {
          $node = $node->getNode(1);
        }

        if ($node instanceof \Twig_Node_Print) {
          $n = $node->getNode('expr');
          while ($n instanceof \Twig_Node_Expression_Filter) {
            $n = $n->getNode('node');
          }
123 124 125

          $args = $n;

126
          // Support TwigExtension->renderVar() function in chain.
127 128 129
          if ($args instanceof \Twig_Node_Expression_Function) {
            $args = $n->getNode('arguments')->getNode(0);
          }
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

          // Detect if a token implements one of the filters reserved for
          // modifying the prefix of a token. The default prefix used for
          // translations is "@". This escapes the printed token and makes them
          // safe for templates.
          // @see TwigExtension::getFilters()
          $argPrefix = '@';
          while ($args instanceof \Twig_Node_Expression_Filter) {
            switch ($args->getNode('filter')->getAttribute('value')) {
              case 'placeholder':
                $argPrefix = '%';
                break;
            }
            $args = $args->getNode('node');
          }
          if ($args instanceof \Twig_Node_Expression_GetAttr) {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            $argName = array();
            // Reuse the incoming expression.
            $expr = $args;
            // Assemble a valid argument name by walking through the expression.
            $argName[] = $args->getNode('attribute')->getAttribute('value');
            while ($args->hasNode('node')) {
              $args = $args->getNode('node');
              if ($args instanceof \Twig_Node_Expression_Name) {
                $argName[] = $args->getAttribute('name');
              }
              else {
                $argName[] = $args->getNode('attribute')->getAttribute('value');
              }
            }
            $argName = array_reverse($argName);
            $argName = implode('.', $argName);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
          }
          else {
            $argName = $n->getAttribute('name');
            if (!is_null($args)) {
              $argName = $args->getAttribute('name');
            }
            $expr = new \Twig_Node_Expression_Name($argName, $n->getLine());
          }
          $placeholder = sprintf('%s%s', $argPrefix, $argName);
          $text .= $placeholder;
          $expr->setAttribute('placeholder', $placeholder);
          $tokens[] = $expr;
        }
        else {
          $text .= $node->getAttribute('data');
        }
      }
    }
    else {
      $text = $body->getAttribute('data');
    }

    return array(new \Twig_Node(array(new \Twig_Node_Expression_Constant(trim($text), $body->getLine()))), $tokens);
  }

}