NestIterator.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Cake\Collection\Collection;
  17. use RecursiveIterator;
  18. use Traversable;
  19. /**
  20. * A type of collection that is aware of nested items and exposes methods to
  21. * check or retrieve them
  22. */
  23. class NestIterator extends Collection implements RecursiveIterator
  24. {
  25. /**
  26. * The name of the property that contains the nested items for each element
  27. *
  28. * @var string|callable
  29. */
  30. protected $_nestKey;
  31. /**
  32. * Constructor
  33. *
  34. * @param array|\Traversable $items Collection items.
  35. * @param string|callable $nestKey the property that contains the nested items
  36. * If a callable is passed, it should return the childrens for the passed item
  37. */
  38. public function __construct($items, $nestKey)
  39. {
  40. parent::__construct($items);
  41. $this->_nestKey = $nestKey;
  42. }
  43. /**
  44. * Returns a traversable containing the children for the current item
  45. *
  46. * @return \Traversable
  47. */
  48. public function getChildren()
  49. {
  50. $property = $this->_propertyExtractor($this->_nestKey);
  51. return new static($property($this->current()), $this->_nestKey);
  52. }
  53. /**
  54. * Returns true if there is an array or a traversable object stored under the
  55. * configured nestKey for the current item
  56. *
  57. * @return bool
  58. */
  59. public function hasChildren()
  60. {
  61. $property = $this->_propertyExtractor($this->_nestKey);
  62. $children = $property($this->current());
  63. if (is_array($children)) {
  64. return !empty($children);
  65. }
  66. return $children instanceof Traversable;
  67. }
  68. }