Set.php 3.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. * Represents a set node.
  12. *
  13. * @package twig
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Node_Set extends Twig_Node
  17. {
  18. public function __construct($capture, Twig_NodeInterface $names, Twig_NodeInterface $values, $lineno, $tag = null)
  19. {
  20. parent::__construct(array('names' => $names, 'values' => $values), array('capture' => $capture, 'safe' => false), $lineno, $tag);
  21. /*
  22. * Optimizes the node when capture is used for a large block of text.
  23. *
  24. * {% set foo %}foo{% endset %} is compiled to $context['foo'] = new Twig_Markup("foo");
  25. */
  26. if ($this->getAttribute('capture')) {
  27. $this->setAttribute('safe', true);
  28. $values = $this->getNode('values');
  29. if ($values instanceof Twig_Node_Text) {
  30. $this->setNode('values', new Twig_Node_Expression_Constant($values->getAttribute('data'), $values->getLine()));
  31. $this->setAttribute('capture', false);
  32. }
  33. }
  34. }
  35. /**
  36. * Compiles the node to PHP.
  37. *
  38. * @param Twig_Compiler A Twig_Compiler instance
  39. */
  40. public function compile(Twig_Compiler $compiler)
  41. {
  42. $compiler->addDebugInfo($this);
  43. if (count($this->getNode('names')) > 1) {
  44. $compiler->write('list(');
  45. foreach ($this->getNode('names') as $idx => $node) {
  46. if ($idx) {
  47. $compiler->raw(', ');
  48. }
  49. $compiler->subcompile($node);
  50. }
  51. $compiler->raw(')');
  52. } else {
  53. if ($this->getAttribute('capture')) {
  54. $compiler
  55. ->write("ob_start();\n")
  56. ->subcompile($this->getNode('values'))
  57. ;
  58. }
  59. $compiler->subcompile($this->getNode('names'), false);
  60. if ($this->getAttribute('capture')) {
  61. $compiler->raw(" = new Twig_Markup(ob_get_clean())");
  62. }
  63. }
  64. if (!$this->getAttribute('capture')) {
  65. $compiler->raw(' = ');
  66. if (count($this->getNode('names')) > 1) {
  67. $compiler->write('array(');
  68. foreach ($this->getNode('values') as $idx => $value) {
  69. if ($idx) {
  70. $compiler->raw(', ');
  71. }
  72. $compiler->subcompile($value);
  73. }
  74. $compiler->raw(')');
  75. } else {
  76. if ($this->getAttribute('safe')) {
  77. $compiler
  78. ->raw("new Twig_Markup(")
  79. ->subcompile($this->getNode('values'))
  80. ->raw(")")
  81. ;
  82. } else {
  83. $compiler->subcompile($this->getNode('values'));
  84. }
  85. }
  86. }
  87. $compiler->raw(";\n");
  88. }
  89. }