Macro.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 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. * Represents a macro node.
  12. *
  13. * @package twig
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Node_Macro extends Twig_Node
  17. {
  18. public function __construct($name, Twig_NodeInterface $body, Twig_NodeInterface $arguments, $lineno, $tag = null)
  19. {
  20. parent::__construct(array('body' => $body, 'arguments' => $arguments), array('name' => $name), $lineno, $tag);
  21. }
  22. /**
  23. * Compiles the node to PHP.
  24. *
  25. * @param Twig_Compiler A Twig_Compiler instance
  26. */
  27. public function compile(Twig_Compiler $compiler)
  28. {
  29. $arguments = array();
  30. foreach ($this->getNode('arguments') as $argument) {
  31. $arguments[] = '$'.$argument->getAttribute('name').' = null';
  32. }
  33. $compiler
  34. ->addDebugInfo($this)
  35. ->write(sprintf("public function get%s(%s)\n", $this->getAttribute('name'), implode(', ', $arguments)), "{\n")
  36. ->indent()
  37. ->write("\$context = array_merge(\$this->env->getGlobals(), array(\n")
  38. ->indent()
  39. ;
  40. foreach ($this->getNode('arguments') as $argument) {
  41. $compiler
  42. ->write('')
  43. ->string($argument->getAttribute('name'))
  44. ->raw(' => $'.$argument->getAttribute('name'))
  45. ->raw(",\n")
  46. ;
  47. }
  48. $compiler
  49. ->outdent()
  50. ->write("));\n\n")
  51. ->write("ob_start();\n")
  52. ->write("try {\n")
  53. ->indent()
  54. ->subcompile($this->getNode('body'))
  55. ->outdent()
  56. ->write("} catch(Exception \$e) {\n")
  57. ->indent()
  58. ->write("ob_end_clean();\n\n")
  59. ->write("throw \$e;\n")
  60. ->outdent()
  61. ->write("}\n\n")
  62. ->write("return ob_get_clean();\n")
  63. ->outdent()
  64. ->write("}\n\n")
  65. ;
  66. }
  67. }