Macro.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. ;
  38. if (!count($this->getNode('arguments'))) {
  39. $compiler->write("\$context = \$this->env->getGlobals();\n\n");
  40. } else {
  41. $compiler
  42. ->write("\$context = array_merge(\$this->env->getGlobals(), array(\n")
  43. ->indent()
  44. ;
  45. foreach ($this->getNode('arguments') as $argument) {
  46. $compiler
  47. ->write('')
  48. ->string($argument->getAttribute('name'))
  49. ->raw(' => $'.$argument->getAttribute('name'))
  50. ->raw(",\n")
  51. ;
  52. }
  53. $compiler
  54. ->outdent()
  55. ->write("));\n\n")
  56. ;
  57. }
  58. $compiler
  59. ->write("\$blocks = array();\n\n")
  60. ->write("ob_start();\n")
  61. ->write("try {\n")
  62. ->indent()
  63. ->subcompile($this->getNode('body'))
  64. ->outdent()
  65. ->write("} catch(Exception \$e) {\n")
  66. ->indent()
  67. ->write("ob_end_clean();\n\n")
  68. ->write("throw \$e;\n")
  69. ->outdent()
  70. ->write("}\n\n")
  71. ->write("return ob_get_clean();\n")
  72. ->outdent()
  73. ->write("}\n\n")
  74. ;
  75. }
  76. }