From.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /**
  11. * Imports macros.
  12. *
  13. * <pre>
  14. * {% from 'forms.html' import forms %}
  15. * </pre>
  16. */
  17. class Twig_TokenParser_From 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. public function parse(Twig_Token $token)
  27. {
  28. $macro = $this->parser->getExpressionParser()->parseExpression();
  29. $stream = $this->parser->getStream();
  30. $stream->expect('import');
  31. $targets = array();
  32. do {
  33. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  34. $alias = $name;
  35. if ($stream->test('as')) {
  36. $stream->next();
  37. $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  38. }
  39. $targets[$name] = $alias;
  40. if (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  41. break;
  42. }
  43. $stream->next();
  44. } while (true);
  45. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  46. $node = new Twig_Node_Import($macro, new Twig_Node_Expression_AssignName($this->parser->getVarName(), $token->getLine()), $token->getLine(), $this->getTag());
  47. foreach($targets as $name => $alias) {
  48. $this->parser->addImportedFunction($alias, 'get'.$name, $node->getNode('var'));
  49. }
  50. return $node;
  51. }
  52. /**
  53. * Gets the tag name associated with this token parser.
  54. *
  55. * @return string The tag name
  56. */
  57. public function getTag()
  58. {
  59. return 'from';
  60. }
  61. }