File: D:/HostingSpaces/SBogers85/equichecker.com/app/KommaApp/Kms/Core/Tree/TreeService.php
<?php namespace KommaApp\Kms\Core\Tree;
use KommaApp\Kms\Core\KmsRepository;
use KommaApp\Kms\Core\Kms;
use KommaApp\Pages\Models\Page;
use Illuminate\Database\Eloquent\Model;
/**
*
*
* @author Komma <info@komma.pro>
* @copyright (c) 2012-2016, 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 getStructure(){
$entityTree = $this->repository->getModelsAsTree($this->kms->getCurrentSiteId());
return $this->getTreeLevel($entityTree->getTree());
}
public function getStructureAsJson()
{
return $this->getStructure();
}
public function setStructureWithJson($tree)
{
$count = 1;
return $this->mapTree($tree, $count);
}
public function getTreeLevel($level)
{
$currentLevel = [];
$language= $this->kms->getDefaultLanguage();
foreach ($level as $item) {
$currentLevel[] = [
'id' => $item->node->id,
'title' => $item->getTranslationField('name',$language),
'thumbnail' => $item->node->thumbnail,
'routes' => $item->getRoutes($item),
'children' => $this->getTreeLevel($item->getChildren()),
'status' => (isset($item->node->active) && $item->node->active== '1' ? 'active' : ''),
];
}
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)
$page = $this->model->find($nodes[$key]->id);
$page->lft = $nodes[$key]->lft;
$page->rgt = $nodes[$key]->rgt;
$page->save();
}
return $nodes;
}
}