Trans.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * {@inheritdoc}
  14. */
  15. public function parse(Twig_Token $token)
  16. {
  17. $lineno = $token->getLine();
  18. $stream = $this->parser->getStream();
  19. $count = null;
  20. $plural = null;
  21. $notes = null;
  22. if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) {
  23. $body = $this->parser->getExpressionParser()->parseExpression();
  24. } else {
  25. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  26. $body = $this->parser->subparse(array($this, 'decideForFork'));
  27. $next = $stream->next()->getValue();
  28. if ('plural' === $next) {
  29. $count = $this->parser->getExpressionParser()->parseExpression();
  30. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  31. $plural = $this->parser->subparse(array($this, 'decideForFork'));
  32. if ('notes' === $stream->next()->getValue()) {
  33. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  34. $notes = $this->parser->subparse(array($this, 'decideForEnd'), true);
  35. }
  36. } elseif ('notes' === $next) {
  37. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  38. $notes = $this->parser->subparse(array($this, 'decideForEnd'), true);
  39. }
  40. }
  41. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  42. $this->checkTransString($body, $lineno);
  43. return new Twig_Extensions_Node_Trans($body, $plural, $count, $notes, $lineno, $this->getTag());
  44. }
  45. public function decideForFork(Twig_Token $token)
  46. {
  47. return $token->test(array('plural', 'notes', 'endtrans'));
  48. }
  49. public function decideForEnd(Twig_Token $token)
  50. {
  51. return $token->test('endtrans');
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getTag()
  57. {
  58. return 'trans';
  59. }
  60. protected function checkTransString(Twig_Node $body, $lineno)
  61. {
  62. foreach ($body as $i => $node) {
  63. if (
  64. $node instanceof Twig_Node_Text
  65. ||
  66. ($node instanceof Twig_Node_Print && $node->getNode('expr') instanceof Twig_Node_Expression_Name)
  67. ) {
  68. continue;
  69. }
  70. throw new Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno);
  71. }
  72. }
  73. }
  74. class_alias('Twig_Extensions_TokenParser_Trans', 'Twig\Extensions\TokenParser\TransTokenParser', false);