-
Notifications
You must be signed in to change notification settings - Fork 802
Zend_Navigation_Container::getChildren() returns null after recursive iteration #420
Comments
Maybe related: zendframework/zendframework#4517 |
This will break existing unit tests:
|
I misunderstood the usage of getChildren(). It returns an iterator for the current iterator entry, not an array, containing children of current element. So maybe this issue is not a bug, we CAN NOT use hasChildren() + getChildren() to implement iteration, unless we call rewind() + next() manually. hasChildren() + getChildren() suit RecursiveIteratorIterator, not friendly with foreach When someone wants to iterate a Navigation(Container), I think the 3 methods below are appropriate. // 1. use the RecursiveIteratorIterator class
$mode = RecursiveIteratorIterator::SELF_FIRST;
// $mode = RecursiveIteratorIterator::LEAVES_ONLY;
// $mode = RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new RecursiveIteratorIterator($container, $mode);
foreach ($iterator as $page) {
echo $page->getLabel(), PHP_EOL;
} Using RecursiveIteratorIterator::LEAVES_ONLY result in echo nothing, but I think this is acceptable. // 2. use custom function and Zend_Navigation_Container::getPages()
function showLabels1(Zend_Navigation_Page $page) {
echo $page->getLabel(), PHP_EOL;
if ($page->hasPages()) { // $page->hasChildren() also OK
$subPages = $page->getPages(); // CANNOT use $page->getChildren()
foreach ($subPages as $subPage) {
showLabels1($subPage);
}
}
}
foreach ($container as $page) {
showLabels1($page);
} // 3. use custom function and Zend_Navigation_Container::getChildren()
function showLabels2(Zend_Navigation_Page $page) {
echo $page->getLabel(), PHP_EOL;
if ($page->hasChildren()) {
$page->rewind();
while($subPage = $page->getChildren()) {
showLabels2($subPage);
$page->next();
}
}
}
foreach ($container as $page) {
showLabels2($page);
} |
|
Output:
It is because Zend_Navigation_Container uses $_index property to implement RecursiveIterator interface, and after a recursive iteration, the internal pointer points beyond the end of the $_index. key($this->_index) returns null.
I think use this method can avoid the problem.
The text was updated successfully, but these errors were encountered: