Scope.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\NodeVisitor;
  11. /**
  12. * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
  13. */
  14. class Scope
  15. {
  16. /**
  17. * @var Scope|null
  18. */
  19. private $parent;
  20. /**
  21. * @var Scope[]
  22. */
  23. private $children;
  24. /**
  25. * @var array
  26. */
  27. private $data;
  28. /**
  29. * @var boolean
  30. */
  31. private $left;
  32. /**
  33. * @param Scope $parent
  34. */
  35. public function __construct(Scope $parent = null)
  36. {
  37. $this->parent = $parent;
  38. $this->left = false;
  39. $this->data = array();
  40. }
  41. /**
  42. * Opens a new child scope.
  43. *
  44. * @return Scope
  45. */
  46. public function enter()
  47. {
  48. $child = new self($this);
  49. $this->children[] = $child;
  50. return $child;
  51. }
  52. /**
  53. * Closes current scope and returns parent one.
  54. *
  55. * @return Scope|null
  56. */
  57. public function leave()
  58. {
  59. $this->left = true;
  60. return $this->parent;
  61. }
  62. /**
  63. * Stores data into current scope.
  64. *
  65. * @param string $key
  66. * @param mixed $value
  67. *
  68. * @throws \LogicException
  69. *
  70. * @return Scope Current scope
  71. */
  72. public function set($key, $value)
  73. {
  74. if ($this->left) {
  75. throw new \LogicException('Left scope is not mutable.');
  76. }
  77. $this->data[$key] = $value;
  78. return $this;
  79. }
  80. /**
  81. * Tests if a data is visible from current scope.
  82. *
  83. * @param string $key
  84. *
  85. * @return boolean
  86. */
  87. public function has($key)
  88. {
  89. if (array_key_exists($key, $this->data)) {
  90. return true;
  91. }
  92. if (null === $this->parent) {
  93. return false;
  94. }
  95. return $this->parent->has($key);
  96. }
  97. /**
  98. * Returns data visible from current scope.
  99. *
  100. * @param string $key
  101. * @param mixed $default
  102. *
  103. * @return mixed
  104. */
  105. public function get($key, $default = null)
  106. {
  107. if (array_key_exists($key, $this->data)) {
  108. return $this->data[$key];
  109. }
  110. if (null === $this->parent) {
  111. return $default;
  112. }
  113. return $this->parent->get($key, $default);
  114. }
  115. }