vendor/pimcore/pimcore/lib/Document/Editable/Block/BlockStateStack.php line 32

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Pimcore
  5. *
  6. * This source file is available under two different licenses:
  7. * - GNU General Public License version 3 (GPLv3)
  8. * - Pimcore Commercial License (PCL)
  9. * Full copyright and license information is available in
  10. * LICENSE.md which is distributed with this source code.
  11. *
  12. * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  13. * @license http://www.pimcore.org/license GPLv3 and PCL
  14. */
  15. namespace Pimcore\Document\Editable\Block;
  16. /**
  17. * @internal
  18. *
  19. * Handles block state (current block level, current block index)
  20. */
  21. final class BlockStateStack implements \Countable, \JsonSerializable
  22. {
  23. /**
  24. * @var BlockState[]
  25. */
  26. private $states = [];
  27. public function __construct()
  28. {
  29. // we need to make sure there's a default state on the stack
  30. $this->push();
  31. }
  32. /**
  33. * Adds a new state to the stack
  34. *
  35. * @param BlockState|null $blockState
  36. */
  37. public function push(BlockState $blockState = null)
  38. {
  39. if (null === $blockState) {
  40. $blockState = new BlockState();
  41. }
  42. array_push($this->states, $blockState);
  43. }
  44. /**
  45. * Removes current state from the stack
  46. *
  47. * @return BlockState
  48. */
  49. public function pop(): BlockState
  50. {
  51. if (count($this->states) <= 1) {
  52. throw new \LogicException('Can\'t pop the last state off the stack');
  53. }
  54. return array_pop($this->states);
  55. }
  56. /**
  57. * Returns current state
  58. *
  59. * @return BlockState
  60. */
  61. public function getCurrentState(): BlockState
  62. {
  63. if (empty($this->states)) {
  64. // this should never happen
  65. throw new \RuntimeException('State stack is empty');
  66. }
  67. return array_slice($this->states, -1)[0];
  68. }
  69. public function count(): int
  70. {
  71. return count($this->states);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function jsonSerialize()
  77. {
  78. return $this->states;
  79. }
  80. public function loadArray(array $array)
  81. {
  82. $this->states = [];
  83. foreach ($array as $blockStateData) {
  84. $blockState = new BlockState();
  85. foreach ($blockStateData['blocks'] as $blockData) {
  86. $blockState->pushBlock(new BlockName($blockData['name'], $blockData['realName']));
  87. }
  88. foreach ($blockStateData['indexes'] as $indexData) {
  89. $blockState->pushIndex($indexData);
  90. }
  91. $this->states[] = $blockState;
  92. }
  93. }
  94. }