UnfoldIterator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Collection\Iterator;
  16. use IteratorIterator;
  17. use RecursiveIterator;
  18. /**
  19. * An iterator that can be used to generate nested iterators out of a collection
  20. * of items by applying an function to each of the elements in this iterator.
  21. *
  22. * @internal
  23. * @see \Cake\Collection\Collection::unfold()
  24. */
  25. class UnfoldIterator extends IteratorIterator implements RecursiveIterator
  26. {
  27. /**
  28. * A function that is passed each element in this iterator and
  29. * must return an array or Traversable object.
  30. *
  31. * @var callable
  32. */
  33. protected $_unfolder;
  34. /**
  35. * A reference to the internal iterator this object is wrapping.
  36. *
  37. * @var \Iterator
  38. */
  39. protected $_innerIterator;
  40. /**
  41. * Creates the iterator that will generate child iterators from each of the
  42. * elements it was constructed with.
  43. *
  44. * @param array|\Traversable $items The list of values to iterate
  45. * @param callable $unfolder A callable function that will receive the
  46. * current item and key. It must return an array or Traversable object
  47. * out of which the nested iterators will be yielded.
  48. */
  49. public function __construct($items, callable $unfolder)
  50. {
  51. $this->_unfolder = $unfolder;
  52. parent::__construct($items);
  53. $this->_innerIterator = $this->getInnerIterator();
  54. }
  55. /**
  56. * Returns true as each of the elements in the array represent a
  57. * list of items
  58. *
  59. * @return bool
  60. */
  61. public function hasChildren()
  62. {
  63. return true;
  64. }
  65. /**
  66. * Returns an iterator containing the items generated by transforming
  67. * the current value with the callable function.
  68. *
  69. * @return \RecursiveIterator
  70. */
  71. public function getChildren()
  72. {
  73. $current = $this->current();
  74. $key = $this->key();
  75. $unfolder = $this->_unfolder;
  76. return new NoChildrenIterator($unfolder($current, $key, $this->_innerIterator));
  77. }
  78. }