Commit a7548229 authored by Nicolas Widart's avatar Nicolas Widart

Save child items recursively

parent 90fcd7a0
......@@ -4,33 +4,60 @@ use Modules\Menu\Repositories\MenuItemRepository;
class MenuService
{
/**
* Current Menu Item being looped over
* @var
*/
protected $menuItem;
/**
* @var MenuItemRepository
*/
private $menuItem;
private $menuItemRepository;
public function __construct(MenuItemRepository $menuItem)
{
$this->menuItem = $menuItem;
$this->menuItemRepository = $menuItem;
}
public function handle($item, $position)
{
// Find menu item : $menuItem['id'] ->setRoot
$menuItem = $this->menuItem->find($item['id']);
$menuItem->position = $position;
$menuItem->save();
$menuItem->makeRoot();
$this->menuItem = $this->menuItemRepository->find($item['id']);
$this->savePosition($this->menuItem, $position);
$this->menuItem->makeRoot();
// If hasChildren ? set parent ˆ (recursive)
if (isset($item['children'])) {
foreach ($item['children'] as $childPosition => $childItem) {
$childMenuItem = $this->menuItem->find($childItem['id']);
$childMenuItem->position = $childPosition;
$childMenuItem->save();
$childMenuItem->makeChildOf($menuItem);
}
if ($this->hasChildren($item)) {
$this->setChildrenRecursively($item, $this->menuItem);
}
}
/**
* @param $item
* @return bool
*/
private function hasChildren($item)
{
return isset($item['children']);
}
private function setChildrenRecursively($item, $parent)
{
foreach ($item['children'] as $childPosition => $childItem) {
$childMenuItem = $this->menuItemRepository->find($childItem['id']);
$this->savePosition($childMenuItem, $childPosition);
$childMenuItem->makeChildOf($parent);
if ($this->hasChildren($childItem)) $this->setChildrenRecursively($childItem, $childMenuItem);
}
// If no more children finish the recursive call
}
/**
* @param $item
* @param $position
*/
private function savePosition($item, $position)
{
$item->position = $position;
$item->save();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment