You are here

function _potx_parse_twig_file in Translation template extractor 6.3

Same name and namespace in other branches
  1. 8 potx.inc \_potx_parse_twig_file()
  2. 7.3 potx.inc \_potx_parse_twig_file()
  3. 7.2 potx.inc \_potx_parse_twig_file()

Parse a Twig template for translatables. Drupal 8+.

2 calls to _potx_parse_twig_file()
_potx_process_file in ./potx.inc
Process a file and put extracted information to the given parameters.
_potx_process_inline_templates in ./potx.inc
Process Twig inline templates inside PHP files. Drupal 8+

File

./potx.inc, line 1714
Extraction API used by the web and command line interface.

Code

function _potx_parse_twig_file($code, $file, $save_callback) {
  $twig_lexer = new Twig_Lexer(new Twig_Environment());
  $stream = $twig_lexer
    ->tokenize($code, $file);
  while (!$stream
    ->isEOF()) {
    $token = $stream
      ->next();

    // Capture strings translated with the t or trans filter.
    if ($token
      ->test(Twig_Token::VAR_START_TYPE)) {
      $token = $stream
        ->next();
      if ($token
        ->test(Twig_Token::NAME_TYPE)) {
        continue;
      }
      $string = $token
        ->getValue();
      $line = $token
        ->getLine();
      $has_t = false;
      $chained = false;
      $is_concat = false;
      if ($stream
        ->test(Twig_Token::PUNCTUATION_TYPE, '.')) {
        $is_concat = true;
      }
      while (!$stream
        ->isEOF() && ($token = $stream
        ->next()) && !$token
        ->test(Twig_Token::VAR_END_TYPE)) {
        if ($token
          ->test(Twig_Token::PUNCTUATION_TYPE, '|')) {
          if ($stream
            ->test(array(
            't',
            'trans',
          ))) {
            $has_t = true;
          }
          else {
            $chained = true;
          }
        }
      }
      if ($has_t) {
        if (!$chained && !$is_concat) {
          $save_callback(_potx_format_quoted_string('"' . trim($string) . '"'), POTX_CONTEXT_NONE, $file, $line);
        }
        else {
          $message = t('Uses of the t filter in Twig templates should start with a single literal string, and should not be chained.');

          // TODO: Fill in specific URL for Twig documentation once it exists.
          potx_status('error', $message, $file, NULL, NULL, 'https://drupal.org/developing/api/localization');
        }
      }
    }
    elseif ($token
      ->test(Twig_Token::BLOCK_START_TYPE)) {
      $token = $stream
        ->next();
      if ($token
        ->test('trans')) {
        _potx_process_twig_trans_tag($stream, $file, $save_callback);
      }
    }
  }
}