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; ...@@ -4,33 +4,60 @@ use Modules\Menu\Repositories\MenuItemRepository;
class MenuService class MenuService
{ {
/**
* Current Menu Item being looped over
* @var
*/
protected $menuItem;
/** /**
* @var MenuItemRepository * @var MenuItemRepository
*/ */
private $menuItem; private $menuItemRepository;
public function __construct(MenuItemRepository $menuItem) public function __construct(MenuItemRepository $menuItem)
{ {
$this->menuItem = $menuItem; $this->menuItemRepository = $menuItem;
} }
public function handle($item, $position) public function handle($item, $position)
{ {
// Find menu item : $menuItem['id'] ->setRoot // Find menu item : $menuItem['id'] ->setRoot
$menuItem = $this->menuItem->find($item['id']); $this->menuItem = $this->menuItemRepository->find($item['id']);
$menuItem->position = $position; $this->savePosition($this->menuItem, $position);
$menuItem->save(); $this->menuItem->makeRoot();
$menuItem->makeRoot();
// If hasChildren ? set parent ˆ (recursive) // If hasChildren ? set parent ˆ (recursive)
if (isset($item['children'])) { if ($this->hasChildren($item)) {
foreach ($item['children'] as $childPosition => $childItem) { $this->setChildrenRecursively($item, $this->menuItem);
$childMenuItem = $this->menuItem->find($childItem['id']); }
$childMenuItem->position = $childPosition; }
$childMenuItem->save();
$childMenuItem->makeChildOf($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