I'm looking for the cleanest way to get the next child sibling of an object (next child of the parent).
-- Parent Object
-- Child 1
-- Child 2 (<== Current object)
-- Child 3 (<== Required object)
-- Child 4
Let assume in this example that we are talking about pages (Sonata pages). Currently I have Page 2 (Child 2), and need the next page of the same parent (in this case child 3). In the case I have the last page (child 4), then I need the first child again.
One option would be to request the parent, then request all the childs, loop over all the childs and look for the current child. Then take the next child, or the first one in case there is no next one. But this seems like a lot of code, with a lot of ugly if logic and loops. So I'm wondering if there is some sort of pattern to solve this.
Eventually I came up with the next solution:
/**
* $siblings is an array containing all pages with the same parent.
* So it also includes the current page.
* First check if there are siblings: Check if the parent has more then 1 child
**/
if (count($siblings) != 1) {
// Find the current page in the array
for ($i = 0; $i < count($siblings); $i++) {
// If we're not at the end of the array: Return next sibling
if ($siblings{$i}->getId() === $page->getId() && $i+1 != count($siblings)) {
return $siblings{$i+1};
}
// If we're at the end: Return first sibling
if ($siblings{$i}->getId() === $page->getId() && $i+1 == count($siblings)) {
return $siblings{0};
}
}
}
This seems like a quite clean solution to tackle this problem. We don't have an excessive amount of loops and if logic, however the code is still readable.