File: D:/HostingSpaces/SBogers93/fitale.nl/workbench/komma/kms/src/Komma/Kms/Core/Tree/TreeService.php
<?php namespace Komma\Kms\Core\Tree;
use Komma\Kms\Core\KmsRepository;
use Komma\Kms\Core\Kms;
use Komma\Kms\Pages\Models\Page;
use Illuminate\Database\Eloquent\Model;
/**
* Short description for the file.
*
* @author Komma <info@komma.pro>
* @copyright (c) 2012-2015, Komma Mediadesign
*/
class TreeService
{
protected $kms;
protected $repository;
protected $model;
public function __construct(Kms $kms)
{
$this->kms = $kms;
}
public function setRepository(KmsRepository $repository)
{
$this->repository = $repository;
}
public function setModel(Model $model)
{
$this->model = $model;
}
public function getStructureAsJson()
{
$entityTree = $this->repository->getEntitiesAsTree();
return $this->getTreeLevel($entityTree->getTree());
}
public function setStructureWithJson($tree)
{
$count = 1;
return $this->mapTree($tree, $count);
}
protected function getTreeLevel($level)
{
$currentLevel = [];
foreach($level as $item){
$currentLevel[] = [
'id' => $item->node->id,
'title' => $item->node->name,
'thumbnail' => $item->node->thumbnail,
'children' => $this->getTreeLevel($item->getChildren())
];
}
return $currentLevel;
}
protected function mapTree(array $nodes, &$count = 0)
{
if(!$this->model) throw new \Exception('You need to set a model in TreeService to save a tree');
foreach($nodes as $key => $value){
// set the lft/rgt positions
$nodes[$key]->lft = ++$count;
$nodes[$key]->children = $this->mapTree($nodes[$key]->children, $count);
$nodes[$key]->rgt = ++$count;
// save lft/rgt positions (not optimal to save all records)
$model = $this->model->find($nodes[$key]->id);
$model->lft = $nodes[$key]->lft;
$model->rgt = $nodes[$key]->rgt;
$model->save();
}
return $nodes;
}
}