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

namespace Komma\Kms\Posts;

use Carbon\Carbon;
use Illuminate\Support\Collection;
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\Languages\Language;
use Komma\Kms\Pages\Models\Page;
use Komma\Kms\Posts\Models\Post;
use Komma\Kms\Posts\Models\PostTranslation;
use Komma\Kms\Schools\School;

class PostRepository extends KmsRepository
{

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

    // Namespace
    protected $namespace = 'Posts';
    // Tables
    protected $table = 'Posts';
    protected $tableTranslation = 'post_translations';
    protected $translationId = 'post_translation_id';
    protected $foreignKey = 'post_id';
    // Entities
    protected $entity = 'PostEntity';
    protected $entityTranslation = 'PostTranslationEntity';
    // Model-string
    protected $modelString = 'Post';
    protected $modelTranslationString = 'PostTranslation';


    //news or blog
    protected $type = 'news';

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

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

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

    private $imageService;

    private $languages;

    /**
     * PostRepository constructor.
     * @param Kms $kms
     * @param ImageService $imageService
     */
    function __construct(
        Kms $kms,
        ImageService $imageService,
        Language $language
    )
    {
        parent::__construct($kms);
        $this->imageService = $imageService;
        $this->languages = $language;
    }

    public function newEntity()
    {
        $entity = new PostEntity();

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

        return $entity;
    }

    public function getEntity($id)
    {
        if($id == null) return $this->newEntity();

        $model = Post::find($id);


        if( ! $model) return false;

        $entity = new PostEntity($model->attributesToArray());

//        $entity->parent_id = $model->getParentId();
//        $entity->name = $model->name;

        $entity->schools = $model->schools->fetch('id')->toArray();

        $entity->images = $this->getImages($id, get_class($model));

        if($entity->images) $entity->thumbnail = $entity->images[0]['thumb_image_url'];

        foreach ($this->kms->getCurrentLanguages() as $language)
        {

            $languageTrans = PostTranslation::where('language_id', '=', $language->id)
                ->where('post_id', '=', $id)
                ->first();

            if( ! $languageTrans)
            {
                $entity->addTranslationEntity(
                    new PostTranslationEntity($language->id)
                );
                continue;
            };

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


            $route = $this->getRouteByTranslationId($languageTrans->id);
            if(isset($route))
            {
                //check if route starts with language string, if true remove it
                $languageString = $this->languages->find($languageTrans->language_id)->iso_2;
                if(substr($route->route, 0, 3) == $languageString . '/')
                {
                    $languageTrans->route = substr($route->route, 3);
                }
                else
                {
                    $languageTrans->route = $route->route;
                }
            }

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

        }

        return $entity;


    }

    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 . '.id as id',
                $this->table . '.date',

                $this->tableTranslation . '.id as ' . $this->translationId,
                $this->tableTranslation . '.name',


                'images.thumb_image_url as thumbnail'
            )
            ->leftJoin(
                $this->tableTranslation,
                $this->table . '.id', '=', $this->tableTranslation . '.' . $this->foreignKey
            )
            ->leftJoin('images', function ($join)
            {
                $join->on($this->table . '.id', '=', 'images.imageble_id')
                    ->where('images.imageble_type', '=', 'Komma\Kms\\' . $this->namespace . '\Models\\' . $this->modelString)
                    ->where('images.sort_order', '=', '1');
            })
            ->where(function ($query) use ($langId)
            {
                $query->whereNull($this->tableTranslation . '.language_id')
                    ->orWhere($this->tableTranslation . '.language_id', '=', $langId);
            })
            ->orderBy($this->table . '.date', 'desc')
            ->get();

        $categories = [];

        foreach ($records as $record)
        {

            $date = Carbon::createFromFormat(Carbon::DEFAULT_TO_STRING_FORMAT, $record->date);
            $record->name = $record->name . '<br/><sub>' . $date->format('d-m-Y') . '</sub>';

            $categories[] = new KmsHierarchicalListItemEntity((array)$record);
        }

        return $categories;

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

//        return $tree;
    }

    /**
     * @param $entity
     * @return mixed
     */
    public function saveEntity($entity)
    {

        $post = Post::firstOrNew(['id' => $entity->id]);

        if($post->id == null)
        {
            $post->code_name = 'post' . Carbon::now()->getTimestamp();
        }
        else
        {
            // Get the code_name
            $post->code_name = $entity->code_name;
        }

        // Set the fields
        $post->active = $entity->active;
        $post->show_on_home = $entity->show_on_home;

        // If Date is not set, make it date today
        if($entity->date == null)
        {
            $post->date = Carbon::now()->format('Y-m-d') . ' 00:00:00';
        }
        else
        {
            // Add current time to string because datepicker only returns time
            $post->date = $entity->date->format('Y-m-d') . ' 00:00:00';
        }

        $post->save();

        // Append id to entity for restfull routing
        $entity->id = $post->id;

        if($entity->schools != 0 ){
            $post->schools()->sync($entity->schools);
        }
        else{
            $post->schools()->detach();
        }

        foreach ($entity->getTranslations() as $translation)
        {
            $postTranslation = PostTranslation::firstOrNew(['post_id' => $post->id, 'language_id' => $translation->getLanguageId()]);
            $postTranslation->name = $translation->name;
            $postTranslation->description = $translation->description;
            $postTranslation->save();

        }

        $this->saveRoutes($entity->schools, $post);

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

        return $post;
    }

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

    protected function saveRoutes($schools, Post $post){

        // Gather the saved routes
        $savedRoutes = [];

        if($schools == 0 ) {
            return $this->removeUnusedRoutes($post, $savedRoutes);
        }

        foreach ($schools as $schoolId){
            //Find schools which are checked
            $school = School::find($schoolId);

            // Find interview page of this school
            $page = Page::where('code_name', $school->type.'-actual-news')->first();

            // If site should be multi language rewrite this
            $pageRoute = $page->translations->first()->routes->first()->route;
            $referenceRoute = $pageRoute.'/'.\Str::slug($post->translations()->first()->name);

            foreach ($post->translations as $translation)
            {
                $routeString = $this->makeRouteUnique($translation, $referenceRoute);

                if($route = $this->getRouteByTranslationIdAndRoute($translation->id, $routeString))
                {
                    $route->route = $routeString;
                    $route->rest_route = $this->type.'/' . $post->id;
                    $route->save();
                }
                else
                {
                    $route = new KmsRoute([
                        'route'      => $routeString,
                        'rest_route' => $this->type.'/' . $post->id
                    ]);
                    $translation->routes()->save($route);
                }

                $savedRoutes[] = $routeString;

            }
        }

        $this->removeUnusedRoutes($post, $savedRoutes);
    }


    public function getRouteByTranslationId($productId)
    {
        if($route = PostTranslation::find($productId))
        {
            return $route->routes()->first();
        }

        return null;
    }

    public function getRouteByTranslationIdAndRoute($postId, $routeString)
    {
        if ($route = PostTranslation::find($postId)) {
            foreach ($route->routes()->get() as $route){
                if($route->route == $routeString) return $route;
            }
            return false;
        }
        return null;
    }

    public function findAllRoutesOfReferences( Post $post)
    {
        $routes = [];

        foreach ($post->translations()->get() as $postTranslation){
            foreach ($postTranslation->routes()->get() as $postRoute){
                $routes[] = $postRoute;
            }
        }

        return $routes;
    }

    public function removeUnusedRoutes(Post $post, $usedRoutes){

        // Get all Routes of all translations and schools
        $allPostRoutes = $this->findAllRoutesOfReferences($post);

        foreach ($allPostRoutes as $postRoute){
            // If in used routes array, continue
            if(in_array($postRoute->route, $usedRoutes)) continue;

            // Else remove this route
            $postRoute->delete();
        }
    }


//    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();
//        }
//    }

    public function makeRouteUnique($routeable, $route)
    {
        $routes = KmsRoute::where('route', '=', $route)
            ->Join('post_translations', 'routes.routable_id', '=', 'post_translations.id')
            ->where('post_translations.language_id', '=', $routeable->language_id)
            ->where(function ($query) use ($routeable)
            {
                $query->where('routable_id', '!=', $routeable->id);
                $query->where('routable_type', '==', get_class($routeable));
            })
            ->get();
        if($routes->count() == 0) return $route;

        return $this->makeRouteUnique($routeable, $route . '-1');
    }


}