History.php 2.4 KB

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