History.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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\Component\BrowserKit;
  11. /**
  12. * History.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class History
  17. {
  18. protected $stack = [];
  19. protected $position = -1;
  20. /**
  21. * Clears the history.
  22. */
  23. public function clear()
  24. {
  25. $this->stack = [];
  26. $this->position = -1;
  27. }
  28. /**
  29. * Adds a Request to the history.
  30. */
  31. public function add(Request $request)
  32. {
  33. $this->stack = \array_slice($this->stack, 0, $this->position + 1);
  34. $this->stack[] = clone $request;
  35. $this->position = \count($this->stack) - 1;
  36. }
  37. /**
  38. * Returns true if the history is empty.
  39. *
  40. * @return bool true if the history is empty, false otherwise
  41. */
  42. public function isEmpty()
  43. {
  44. return 0 == \count($this->stack);
  45. }
  46. /**
  47. * Goes back in the history.
  48. *
  49. * @return Request A Request instance
  50. *
  51. * @throws \LogicException if the stack is already on the first page
  52. */
  53. public function back()
  54. {
  55. if ($this->position < 1) {
  56. throw new \LogicException('You are already on the first page.');
  57. }
  58. return clone $this->stack[--$this->position];
  59. }
  60. /**
  61. * Goes forward in the history.
  62. *
  63. * @return Request A Request instance
  64. *
  65. * @throws \LogicException if the stack is already on the last page
  66. */
  67. public function forward()
  68. {
  69. if ($this->position > \count($this->stack) - 2) {
  70. throw new \LogicException('You are already on the last page.');
  71. }
  72. return clone $this->stack[++$this->position];
  73. }
  74. /**
  75. * Returns the current element in the history.
  76. *
  77. * @return Request A Request instance
  78. *
  79. * @throws \LogicException if the stack is empty
  80. */
  81. public function current()
  82. {
  83. if (-1 == $this->position) {
  84. throw new \LogicException('The page history is empty.');
  85. }
  86. return clone $this->stack[$this->position];
  87. }
  88. }