Scope.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 array
  22. */
  23. private $data = array();
  24. /**
  25. * @var bool
  26. */
  27. private $left = false;
  28. /**
  29. * @param Scope $parent
  30. */
  31. public function __construct(Scope $parent = null)
  32. {
  33. $this->parent = $parent;
  34. }
  35. /**
  36. * Opens a new child scope.
  37. *
  38. * @return self
  39. */
  40. public function enter()
  41. {
  42. return new self($this);
  43. }
  44. /**
  45. * Closes current scope and returns parent one.
  46. *
  47. * @return self|null
  48. */
  49. public function leave()
  50. {
  51. $this->left = true;
  52. return $this->parent;
  53. }
  54. /**
  55. * Stores data into current scope.
  56. *
  57. * @param string $key
  58. * @param mixed $value
  59. *
  60. * @return $this
  61. *
  62. * @throws \LogicException
  63. */
  64. public function set($key, $value)
  65. {
  66. if ($this->left) {
  67. throw new \LogicException('Left scope is not mutable.');
  68. }
  69. $this->data[$key] = $value;
  70. return $this;
  71. }
  72. /**
  73. * Tests if a data is visible from current scope.
  74. *
  75. * @param string $key
  76. *
  77. * @return bool
  78. */
  79. public function has($key)
  80. {
  81. if (array_key_exists($key, $this->data)) {
  82. return true;
  83. }
  84. if (null === $this->parent) {
  85. return false;
  86. }
  87. return $this->parent->has($key);
  88. }
  89. /**
  90. * Returns data visible from current scope.
  91. *
  92. * @param string $key
  93. * @param mixed $default
  94. *
  95. * @return mixed
  96. */
  97. public function get($key, $default = null)
  98. {
  99. if (array_key_exists($key, $this->data)) {
  100. return $this->data[$key];
  101. }
  102. if (null === $this->parent) {
  103. return $default;
  104. }
  105. return $this->parent->get($key, $default);
  106. }
  107. }