Scope.php 1.9 KB

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