TransTokenParser.php 2.6 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 'trans' tag.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class TransTokenParser extends \Twig_TokenParser
  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. $domain = null;
  34. $locale = null;
  35. if (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
  36. if ($stream->test('with')) {
  37. // {% trans with vars %}
  38. $stream->next();
  39. $vars = $this->parser->getExpressionParser()->parseExpression();
  40. }
  41. if ($stream->test('from')) {
  42. // {% trans from "messages" %}
  43. $stream->next();
  44. $domain = $this->parser->getExpressionParser()->parseExpression();
  45. }
  46. if ($stream->test('into')) {
  47. // {% trans into "fr" %}
  48. $stream->next();
  49. $locale = $this->parser->getExpressionParser()->parseExpression();
  50. } elseif (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
  51. throw new \Twig_Error_Syntax('Unexpected token. Twig was looking for the "with" or "from" keyword.');
  52. }
  53. }
  54. // {% trans %}message{% endtrans %}
  55. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  56. $body = $this->parser->subparse(array($this, 'decideTransFork'), true);
  57. if (!$body instanceof \Twig_Node_Text && !$body instanceof \Twig_Node_Expression) {
  58. throw new \Twig_Error_Syntax('A message inside a trans tag must be a simple text');
  59. }
  60. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  61. return new TransNode($body, $domain, null, $vars, $locale, $lineno, $this->getTag());
  62. }
  63. public function decideTransFork($token)
  64. {
  65. return $token->test(array('endtrans'));
  66. }
  67. /**
  68. * Gets the tag name associated with this token parser.
  69. *
  70. * @return string The tag name
  71. */
  72. public function getTag()
  73. {
  74. return 'trans';
  75. }
  76. }