TransChoiceTokenParser.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\TokenParser;
  11. use Symfony\Bridge\Twig\Node\TransNode;
  12. use Twig\Error\SyntaxError;
  13. use Twig\Node\Expression\AbstractExpression;
  14. use Twig\Node\Expression\ArrayExpression;
  15. use Twig\Node\Node;
  16. use Twig\Node\TextNode;
  17. use Twig\Token;
  18. /**
  19. * Token Parser for the 'transchoice' tag.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class TransChoiceTokenParser extends TransTokenParser
  24. {
  25. /**
  26. * Parses a token and returns a node.
  27. *
  28. * @param Token $token
  29. *
  30. * @return Node
  31. *
  32. * @throws SyntaxError
  33. */
  34. public function parse(Token $token)
  35. {
  36. $lineno = $token->getLine();
  37. $stream = $this->parser->getStream();
  38. $vars = new ArrayExpression(array(), $lineno);
  39. $count = $this->parser->getExpressionParser()->parseExpression();
  40. $domain = null;
  41. $locale = null;
  42. if ($stream->test('with')) {
  43. // {% transchoice count with vars %}
  44. $stream->next();
  45. $vars = $this->parser->getExpressionParser()->parseExpression();
  46. }
  47. if ($stream->test('from')) {
  48. // {% transchoice count from "messages" %}
  49. $stream->next();
  50. $domain = $this->parser->getExpressionParser()->parseExpression();
  51. }
  52. if ($stream->test('into')) {
  53. // {% transchoice count into "fr" %}
  54. $stream->next();
  55. $locale = $this->parser->getExpressionParser()->parseExpression();
  56. }
  57. $stream->expect(Token::BLOCK_END_TYPE);
  58. $body = $this->parser->subparse(array($this, 'decideTransChoiceFork'), true);
  59. if (!$body instanceof TextNode && !$body instanceof AbstractExpression) {
  60. throw new SyntaxError('A message inside a transchoice tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()->getName());
  61. }
  62. $stream->expect(Token::BLOCK_END_TYPE);
  63. return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag());
  64. }
  65. public function decideTransChoiceFork($token)
  66. {
  67. return $token->test(array('endtranschoice'));
  68. }
  69. /**
  70. * Gets the tag name associated with this token parser.
  71. *
  72. * @return string The tag name
  73. */
  74. public function getTag()
  75. {
  76. return 'transchoice';
  77. }
  78. }