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/SBogers93/fitale.nl/workbench/komma/kms/src/Komma/Kms/Pages/PageRepository.php
<?php
/**
 * Short description for the file.
 *
 * @author      Komma <info@komma.pro>
 * @copyright   (c) 2012-2015, Komma Mediadesign
 */

namespace Komma\Kms\Pages;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Route;
use Komma\Kms\Core\Entities\KmsHierarchicalListItemEntity;
use Komma\Kms\Core\Kms;
use Komma\Kms\Core\KmsRepository;
use Komma\Kms\Core\Routes\KmsRoute;
use Komma\Kms\Core\Routes\RoutableInterface;
use Komma\Kms\Core\Tree\Tree;
use Komma\Kms\Images\ImageRepository;

// Change these into new entity-type
use Komma\Kms\Images\ImageService;
use Komma\Kms\Pages\Models\Page;
use Komma\Kms\Pages\Models\PageTranslation;

class PageRepository extends KmsRepository
{

    // Here are some variables repeated in this repository
    // These change for every type of entity

    // Namespace
    protected $namespace = 'Pages';
    // Tables
    protected $table = 'pages';
    protected $tableTranslation = 'page_translations';
    protected $translationId = 'page_translation_id';
    protected $foreignKey = 'page_id';
    // Entities
    protected $entity = 'PageEntity';
    protected $entityTranslation = 'PageTranslationEntity';
    // Model-string
    protected $modelString = 'Page';
    protected $modelTranslationString = 'PageTranslation';

    /**
     * @var Tree
     */
    protected $tree;

    /**
     * @var ImageRepository
     */
    private $imageRepository;

    /**
     * @var
     */
    private $model;

    /**
     * @var
     */
    private $modelTranslation;

    private $imageService;

    /**
     * @param Kms $kms
     * @param Tree $tree
     * @param ImageRepository $imageRepository
     * @param $model
     * @param $modelTranslation
     */
    function __construct(
        Kms $kms,
        Kms $buttons,
        Tree $tree,
        ImageRepository $imageRepository,
        Page $model,
        PageTranslation $modelTranslation,
        ImageService $imageService
    )
    {
        parent::__construct($kms);

        $this->tree = $tree;

        $this->imageRepository = $imageRepository;
        $this->imageRepository->setRelatedModel(
            'Komma\\Kms\\' . $this->namespace . '\\Models\\' . $this->modelString);


        $this->model = $model;
        $this->modelTranslation = $modelTranslation;

        $this->imageService = $imageService;
    }

    public function newEntity()
    {
        $entityString = 'Komma\Kms\\' . $this->namespace . '\\' . $this->entity;
        $entity = new $entityString();

        $entityTranslationString = 'Komma\Kms\\' . $this->namespace . '\\' . $this->entityTranslation;

        foreach ($this->kms->getCurrentLanguages() as $language) {
            $entity->addTranslationEntity(new $entityTranslationString($language->id));
        }
        return $entity;
    }

    public function getEntity($id)
    {
        if ($id != null) {
            $model = $this->model->find($id);

            $entityString = 'Komma\Kms\\' . $this->namespace . '\\' . $this->entity;

            // Transform for album_id
            if ($model) {
                $entity = new $entityString($model->attributesToArray());
                $entity->parent_id = $model->getParentId();
                $entity->name = $model->name;
                $entity->images = $this->getImages($id, 'Komma\\Kms\\Pages\\Models\\Page');


                $entity->block_ids = $model->blocks->fetch('id')->toJson();

                foreach ($model->translations as $translation) {
                    if ($route = $this->getRouteByTranslationId($translation->id)) {
                        $translation->route = $route->route;
                    }

                    $entityTranslationString = 'Komma\Kms\\' . $this->namespace . '\\' . $this->entityTranslation;

                    $entity->addTranslationEntity(
                        new $entityTranslationString(
                            $translation->language_id,
                            $translation->attributesToArray()
                        )
                    );
                }

                return $entity;
            }
        }
        return $this->newEntity();
    }

    public function getEntities()
    {
        $tree = $this->getEntitiesAsTree();
        $this->makeRootIfNotExists();
        return $tree;
    }

    public function getEntitiesAsTree($langId = null)
    {
        if ($langId == null) $langId = $this->kms->getDefaultLanguageId();

        $records = \DB::table($this->table)
            ->select(
                $this->table . '.controller',
                $this->table . '.lft',
                $this->table . '.rgt',
                $this->table . '.id as id',

                $this->tableTranslation . '.id as ' . $this->translationId,
                $this->tableTranslation . '.name',
                $this->tableTranslation . '.meta_title',
                $this->tableTranslation . '.meta_description',
                $this->tableTranslation . '.slug',
                $this->tableTranslation . '.description'
            )
            ->leftJoin(
                $this->tableTranslation,
                $this->table . '.id', '=', $this->tableTranslation . '.' . $this->foreignKey
            )
            ->where(function ($query) use ($langId) {
                $query->whereNull($this->tableTranslation . '.language_id')
                    ->orWhere($this->tableTranslation . '.language_id', '=', $langId);
            })
            ->orderBy($this->table . '.lft', 'asc')
            ->get();

        $categories = [];
        foreach ($records as $record) {
            $record = (array)$record;
            //Get the first image for the thumb
            if ($images = $this->getImages($record['id'], 'Komma\\Kms\\Pages\\Models\\Page')) {
                $record['thumbnail'] = $images['0']['thumb_image_url'];
            }
            $categories[] = new KmsHierarchicalListItemEntity($record);
        }

        $tree = new Tree();
        $tree->make($categories);

        return $tree;
    }

    /**
     * @param $entity
     * @return mixed
     */
    public function saveEntity($entity)
    {
        $modelString = 'Komma\Kms\\' . $this->namespace . '\Models\\' . $this->modelString;
        $model = new $modelString;

        if ($entity->id) // UPDATE model
        {
            $model = $model->find($entity->id);
            $model->fill([
                'active' => $entity->active,
                'controller' => $entity->controller,
                'code_name' => $entity->code_name,
            ]);
            if ($model->getParentId() != $entity->parent_id) $model->makeLastChildOf($model->find($entity->parent_id));
        } else { // INSERT model
            $model->fill([
                'active' => $entity->active,
                'controller' => $entity->controller,
                'code_name' => $entity->code_name,
            ]);
            $model->makeLastChildOf($this->model->find($entity->parent_id));
        }

        $model->save();

        $model->blocks()->sync(json_decode($entity->block_ids));

        $entityId = $model->id;

        foreach ($entity->getTranslations() as $translation) {

            $translationModel = $this->modelTranslation->firstOrNew([
                $this->foreignKey => $entityId,
                'language_id' => $translation->getLanguageId()
            ]);

            $description = $translation->description;

            if (\Input::has('dynamic_page')) {
                //load the DynamicPageService
                $dps = \App::make('Komma\Kms\Core\Services\DynamicPageService');
                $description = $dps->prepareDynamicDescription(json_decode($description), $model);
            }

            $translationModel->fill([
                $this->foreignKey => $entityId,
                'name' => $translation->name,
                'meta_title' => $translation->meta_title,
                'meta_description' => $translation->meta_description,
                'slug' => $translation->slug,
                'description' => $description,
                //'meta_title' => $translation->meta_title,
                //'meta_description' => $translation->meta_description
            ]);
            $translationModel->save();


            // If isset rest_route
            if (isset($entity->rest_route) && !empty($entity->rest_route)) {
                $entity->rest_route = str_replace('[[id]]', $entityId, $entity->rest_route);
            }

            $this->saveRoute($translationModel, $translation->route, $entity->rest_route);
        }

        //Link the images to this model
        $this->imageService->linkImagesToModel('images', $model);
        
        return $model;
    }

    public function getForSelect($languageId = null, $excludeId = null)
    {
        $tree = $this->getEntitiesAsTree($languageId);
        if ($excludeId) $tree->removeFromIndex((int)$excludeId);
        $entities = [];

        // QnD !!! Indexing trees per language (multiple queries)
        $treePerLanguage = [];
        foreach ($this->kms->getCurrentLanguages() as $language) {
            $treePerLanguage[$language->id] = $this->getEntitiesAsTree($language->id);
        }
        // End QnD !!!

        foreach ($tree->getIndex() as $record) {
            $entity = [];
            $entity['value'] = $record->node->id;

            // QnD !!! Getting the path from the indexed trees
            $paths = [];
            foreach ($this->kms->getCurrentLanguages() as $language) {
                $path = implode('/', $treePerLanguage[$language->id]->getEntityById($entity['value'])->getSlugPath());
                $paths[$language->id] = $path ? $path . '/' : '';
            }
            $entity['fullValue'] = json_encode($paths);
            // End QnD !!!

            $entity['content'] = $record->node->getName();
            if (!$entity['content']) $entity['content'] = '\\';

            $indent = str_repeat('&nbsp;&nbsp;&nbsp;', $record->getDepth());
            $entity['htmlContent'] = $indent . $record->node->getName();
            if (!$entity['htmlContent']) $entity['htmlContent'] = '\\';

            $entities[] = $entity;
        }
        return $entities;
    }

    public function getButton()
    {
        return $this->buttons;
    }

    public function destroyEntity($id)
    {
        $entity = $this->model->find($id);
        foreach ($entity->translations()->get() as $translation) {
            $translation->routes()->delete();
        }
        $entity->delete();
    }

    public function getRouteByTranslationId($productId)
    {
        if ($route = $this->modelTranslation->find($productId)) {
            return $route->routes()->first();
        }
        return null;
    }

    protected function saveRoute(RoutableInterface $routable, $routeString, $restRoute = null)
    {
        if ($route = $this->getRouteByTranslationId($routable->id)) {
            $route->route = $routeString;


            //Only update restRoute when it start with pages
            if ($restRoute != null && preg_match('/^pages/',$route->rest_route)) $route->rest_route = $restRoute;

            $route->save();
        } else {
            $route = new KmsRoute([
                'route' => $routeString,
            ]);

            if ($restRoute != null) $route->rest_route = $restRoute;
            $routable->routes()->save($route);
        }
    }

    protected function makeRootIfNotExists()
    {
        $model = \DB::table($this->table)
            ->where('lft', 1)
            ->first();
        if (!$model) {
            $modelString = 'Komma\Kms\\' . $this->namespace . '\Models\\' . $this->modelString;
            $model = new $modelString;
            $model->makeRoot();
        }
    }
}