HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers33/bbec.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;
    }
}