TransChoiceTokenParser.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /**
  13. * Token Parser for the 'transchoice' tag.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class TransChoiceTokenParser extends TransTokenParser
  18. {
  19. /**
  20. * Parses a token and returns a node.
  21. *
  22. * @param \Twig_Token $token A Twig_Token instance
  23. *
  24. * @return \Twig_NodeInterface A Twig_NodeInterface instance
  25. *
  26. * @throws \Twig_Error_Syntax
  27. */
  28. public function parse(\Twig_Token $token)
  29. {
  30. $lineno = $token->getLine();
  31. $stream = $this->parser->getStream();
  32. $vars = new \Twig_Node_Expression_Array(array(), $lineno);
  33. $count = $this->parser->getExpressionParser()->parseExpression();
  34. $domain = null;
  35. $locale = null;
  36. if ($stream->test('with')) {
  37. // {% transchoice count with vars %}
  38. $stream->next();
  39. $vars = $this->parser->getExpressionParser()->parseExpression();
  40. }
  41. if ($stream->test('from')) {
  42. // {% transchoice count from "messages" %}
  43. $stream->next();
  44. $domain = $this->parser->getExpressionParser()->parseExpression();
  45. }
  46. if ($stream->test('into')) {
  47. // {% transchoice count into "fr" %}
  48. $stream->next();
  49. $locale = $this->parser->getExpressionParser()->parseExpression();
  50. }
  51. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  52. $body = $this->parser->subparse(array($this, 'decideTransChoiceFork'), true);
  53. if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) {
  54. throw new \Twig_Error_Syntax('A message must be a simple text.');
  55. }
  56. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  57. return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag());
  58. }
  59. public function decideTransChoiceFork($token)
  60. {
  61. return $token->test(array('endtranschoice'));
  62. }
  63. /**
  64. * Gets the tag name associated with this token parser.
  65. *
  66. * @return string The tag name
  67. */
  68. public function getTag()
  69. {
  70. return 'transchoice';
  71. }
  72. }