From.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. public function parse(Twig_Token $token)
  20. {
  21. $macro = $this->parser->getExpressionParser()->parseExpression();
  22. $stream = $this->parser->getStream();
  23. $stream->expect('import');
  24. $targets = array();
  25. do {
  26. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  27. $alias = $name;
  28. if ($stream->nextIf('as')) {
  29. $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  30. }
  31. $targets[$name] = $alias;
  32. if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) {
  33. break;
  34. }
  35. } while (true);
  36. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  37. $node = new Twig_Node_Import($macro, new Twig_Node_Expression_AssignName($this->parser->getVarName(), $token->getLine()), $token->getLine(), $this->getTag());
  38. foreach ($targets as $name => $alias) {
  39. if ($this->parser->isReservedMacroName($name)) {
  40. throw new Twig_Error_Syntax(sprintf('"%s" cannot be an imported macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getFilename());
  41. }
  42. $this->parser->addImportedSymbol('function', $alias, 'get'.$name, $node->getNode('var'));
  43. }
  44. return $node;
  45. }
  46. public function getTag()
  47. {
  48. return 'from';
  49. }
  50. }