Trans.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2010 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. class Twig_Extensions_TokenParser_Trans extends Twig_TokenParser
  11. {
  12. /**
  13. * Parses a token and returns a node.
  14. *
  15. * @param Twig_Token $token A Twig_Token instance
  16. *
  17. * @return Twig_NodeInterface A Twig_NodeInterface instance
  18. */
  19. public function parse(Twig_Token $token)
  20. {
  21. $lineno = $token->getLine();
  22. $stream = $this->parser->getStream();
  23. $count = null;
  24. $plural = null;
  25. if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) {
  26. $body = $this->parser->getExpressionParser()->parseExpression();
  27. } else {
  28. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  29. $body = $this->parser->subparse(array($this, 'decideForFork'));
  30. if ('plural' === $stream->next()->getValue()) {
  31. $count = $this->parser->getExpressionParser()->parseExpression();
  32. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  33. $plural = $this->parser->subparse(array($this, 'decideForEnd'), true);
  34. }
  35. }
  36. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  37. $this->checkTransString($body, $lineno);
  38. return new Twig_Extensions_Node_Trans($body, $plural, $count, $lineno, $this->getTag());
  39. }
  40. public function decideForFork($token)
  41. {
  42. return $token->test(array('plural', 'endtrans'));
  43. }
  44. public function decideForEnd($token)
  45. {
  46. return $token->test('endtrans');
  47. }
  48. /**
  49. * Gets the tag name associated with this token parser.
  50. *
  51. * @param string The tag name
  52. */
  53. public function getTag()
  54. {
  55. return 'trans';
  56. }
  57. protected function checkTransString(Twig_NodeInterface $body, $lineno)
  58. {
  59. foreach ($body as $i => $node) {
  60. if (
  61. $node instanceof Twig_Node_Text
  62. ||
  63. ($node instanceof Twig_Node_Print && $node->getNode('expr') instanceof Twig_Node_Expression_Name)
  64. ) {
  65. continue;
  66. }
  67. throw new Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno);
  68. }
  69. }
  70. }