Set.php 3.0 KB

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