FrameTreeIterator.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Dompdf\Frame;
  3. use Iterator;
  4. use Dompdf\Frame;
  5. /**
  6. * Pre-order Iterator
  7. *
  8. * Returns frames in preorder traversal order (parent then children)
  9. *
  10. * @access private
  11. * @package dompdf
  12. */
  13. class FrameTreeIterator implements Iterator
  14. {
  15. /**
  16. * @var Frame
  17. */
  18. protected $_root;
  19. /**
  20. * @var array
  21. */
  22. protected $_stack = [];
  23. /**
  24. * @var int
  25. */
  26. protected $_num;
  27. /**
  28. * @param Frame $root
  29. */
  30. public function __construct(Frame $root)
  31. {
  32. $this->_stack[] = $this->_root = $root;
  33. $this->_num = 0;
  34. }
  35. /**
  36. *
  37. */
  38. public function rewind()
  39. {
  40. $this->_stack = [$this->_root];
  41. $this->_num = 0;
  42. }
  43. /**
  44. * @return bool
  45. */
  46. public function valid()
  47. {
  48. return count($this->_stack) > 0;
  49. }
  50. /**
  51. * @return int
  52. */
  53. public function key()
  54. {
  55. return $this->_num;
  56. }
  57. /**
  58. * @return Frame
  59. */
  60. public function current()
  61. {
  62. return end($this->_stack);
  63. }
  64. /**
  65. * @return Frame
  66. */
  67. public function next()
  68. {
  69. $b = end($this->_stack);
  70. // Pop last element
  71. unset($this->_stack[key($this->_stack)]);
  72. $this->_num++;
  73. // Push all children onto the stack in reverse order
  74. if ($c = $b->get_last_child()) {
  75. $this->_stack[] = $c;
  76. while ($c = $c->get_prev_sibling()) {
  77. $this->_stack[] = $c;
  78. }
  79. }
  80. return $b;
  81. }
  82. }