/** * Removes any empty group children from a tree structure, returning * the number of non-group entries. * * @param MenuPresenceInterface $presence * @return int the number of non-group children found on the levels below */ protected function filterNestedEmptyGroups(MenuPresenceInterface $presence) { if ($presence['type'] !== MenuPresenceType::GROUP) { return 1; } if (!$presence['children'] || !count($presence['children'])) { return 0; } $remove = []; $children = $presence['children']; $nonGroupCount = 0; foreach ($children as $key => $childPresence) { if (!$this->filterNestedEmptyGroups($childPresence)) { $remove[] = $key; continue; } $nonGroupCount++; } foreach ($remove as $key) { unset($children[$key]); } $presence->setChildren($children); return $nonGroupCount; }