public function Twig_ExpressionParser::parseHashExpression

1 call to Twig_ExpressionParser::parseHashExpression()
Twig_ExpressionParser::parsePrimaryExpression in drupal/core/vendor/twig/twig/lib/Twig/ExpressionParser.php

File

drupal/core/vendor/twig/twig/lib/Twig/ExpressionParser.php, line 232

Class

Twig_ExpressionParser
Parses expressions.

Code

public function parseHashExpression() {
  $stream = $this->parser
    ->getStream();
  $stream
    ->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
  $node = new Twig_Node_Expression_Array(array(), $stream
    ->getCurrent()
    ->getLine());
  $first = true;
  while (!$stream
    ->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
    if (!$first) {
      $stream
        ->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');

      // trailing ,?
      if ($stream
        ->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
        break;
      }
    }
    $first = false;

    // a hash key can be:
    //
    //  * a number -- 12
    //  * a string -- 'a'
    //  * a name, which is equivalent to a string -- a
    //  * an expression, which must be enclosed in parentheses -- (1 + 2)
    if ($stream
      ->test(Twig_Token::STRING_TYPE) || $stream
      ->test(Twig_Token::NAME_TYPE) || $stream
      ->test(Twig_Token::NUMBER_TYPE)) {
      $token = $stream
        ->next();
      $key = new Twig_Node_Expression_Constant($token
        ->getValue(), $token
        ->getLine());
    }
    elseif ($stream
      ->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
      $key = $this
        ->parseExpression();
    }
    else {
      $current = $stream
        ->getCurrent();
      throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($current
        ->getType(), $current
        ->getLine()), $current
        ->getValue()), $current
        ->getLine(), $this->parser
        ->getFilename());
    }
    $stream
      ->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
    $value = $this
      ->parseExpression();
    $node
      ->addElement($value, $key);
  }
  $stream
    ->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
  return $node;
}