File: D:/HostingSpaces/fire-tech/fire-tech.nl/app/KommaApp/Kms/Core/Tree/TreeService.php
<?php namespace App\KommaApp\Kms\Core\Tree;
use App\Helpers\KommaHelpers;
use App\KommaApp\Kms\Core\KmsInterface;
use App\KommaApp\Kms\Core\KmsRepository;
use App\KommaApp\Kms\Core\Kms;
use App\KommaApp\Kms\Core\Sections\SectionService;
use App\KommaApp\Pages\Models\Page;
use Illuminate\Database\Eloquent\Model;
/**
*
*
* @author Komma <info@komma.pro>
* @copyright (c) 2012-2016, Komma
*/
class TreeService
{
protected $kms;
protected $sectionService;
protected $model;
public function __construct()
{
$this->kms = \App::make(KmsInterface::class);
}
public function setSectionService(SectionService $sectionService)
{
$this->sectionService = $sectionService;
}
public function setModel(Model $model)
{
$this->model = $model;
}
public function getStructure(){
$entityTree = $this->sectionService->getModelsAsTree($this->kms->getSiteId());
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->getSiteDefaultLanguage();
foreach ($level as $item) {
$title = KommaHelpers::str_limit_full_word($item->getTranslationField('name',$language));
if(isset($item->node->status)) $status = $item->node->status;
elseif( isset($item->node->active) ) $status = $item->node->active;
else $status = null;
$currentLevel[] = [
'id' => $item->node->id,
'title' => $title,
'thumbnail' => $item->node->thumbnail,
'routes' => $item->getRoutes($item),
'children' => $this->getTreeLevel($item->getChildren()),
'status' => $status,
];
}
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;
}
}