File: D:/HostingSpaces/SBogers10/honger.komma.pro/app/KommaApp/Cases/Kms/CaseRepository.php
<?php
/**
*
*
* @author Komma <info@komma.pro>
* @copyright (c) 2012-2016, Komma
*/
namespace App\KommaApp\Cases\Kms;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use App\KommaAppCases\Models\CaseModel;
use App\KommaAppCases\Models\CaseTranslation;
use App\KommaAppKms\Core\Kms;
use App\KommaAppKms\Core\KmsSiteRepository;
use App\KommaAppKms\Core\NestedSets\Nodes\EloquentNode;
use App\KommaAppRoutes\Route;
use App\KommaAppKms\Core\Tree\Tree;
use App\KommaAppImages\ImageService;
use Symfony\Component\CssSelector\Node\ElementNode;
use App\KommaAppRoutes\RouteService;
class CaseRepository extends KmsSiteRepository
{
//Variables
protected $sortable = true;
protected $imageabletype = 'KommaApp\\Cases\\Models\\CaseModel';
protected $tree;
protected $imageService;
protected $routeService;
function __construct(Kms $kms, Tree $tree, ImageService $imageService, RouteService $routeService)
{
parent::__construct($kms);
$this->tree = $tree;
$this->imageService = $imageService;
//set the imageabletype
$this->imageService->setImageableType($this->imageabletype);
$this->routeService = $routeService;
}
/**
* This method will get an model based on the id.
* When the id us NULL, we will generate a new.
* This is Called in KmsSection@loadEntity.
*
* @param $id
* @return CaseModel
*/
public function getModel($case)
{
//Check if the id is null; return newModel
if($case == null) return $this->newModel();
//if( ! is_object($case) ) $case = CaseModel::find($case);
//Id is set, load page model
$model = $case;
$this->setExtraModelFields($model);
return $model;
}
/**
* This method will set extra modelFields.
* eg title and thumbnail for the form.
*
* @param $model
*/
public function setExtraModelFields(&$model)
{
// Set name to the model
if($model->translations->count() != 0) $model->title = $model->translations()->first()->name;
//Set images
$model->images = $this->imageService->getImages($model->id);
//set parent_id
$model->parent_id = $model->getParent()->id;
//Set the thumbnail
$this->setThumbnail($model, $model->images);
}
/**
* Set the thumbnail for the model.
*
* @param $model
*/
public function setThumbnail(&$model, $new = false)
{
//Set the thumbnail
$model->thumbnail = ['image_url' => '/images/kms/structure/page.png'];
if($new === true) return;
if(isset($model->images) && count($model->images) > 0)
{
//Set thumbnail
$model->thumbnail = ['image_url' => $model->images[0]->thumb];
}
}
/**
* This method will create a new page with its translations,
* This is only a container used for the page create form
* It is not used to save the date in the database.
*
* @param null $siteId
* @return CaseModel
*/
public function newModel($siteId = null)
{
//If no siteId, get the id from the current site
if($siteId == null) $siteId = $this->kms->getCurrentSiteId();
//Create a base page if it doesnt exist already
$this->makeRootPageIfNotExists($siteId);
//Create a new page
$case = new CaseModel();
//Create translations per language
foreach ($this->kms->getCurrentSiteLanguages() as $language)
{
//new translation per language
$translation = new CaseTranslation();
//set the language
$translation->fill(['language_id', $language->id]);
//couple page and translation together
$case->translations->add($translation);
}
//Set the thumbnail
$this->setThumbnail($case, true);
return $case;
}
/**
* This method will get all the models.
* And build a hierarchical page tree.
*
* @param $siteId
* @return Tree
*/
public function getModels($siteId)
{
//Create a base page if it doesnt exist already
$this->makeRootPageIfNotExists($siteId);
//Create the tree based on the site id
$tree = $this->getModelsAsTree($siteId);
return $tree;
}
/**
* This method will build an page tree.
* Based on the site and language-id
*
* @param null $siteId
* @param null $langId
* @return Tree
*/
public function getModelsAsTree($siteId = null, $langId = null)
{
//If siteId is null set currentSiteId
if($siteId == null) $siteId = $this->kms->getCurrentSiteId();
//If LangId is null set current LanguageId
if($langId == null) $langId = $this->kms->getDefaultLanguageId();
$cases = CaseModel::with('translations')
->with('images')
->orderBy('cases.lft', 'asc')
->get();
// Set thumbnail if has any images
foreach ($cases as &$case){
if(!isset($case->images) || is_bool($case->images) || $case->images->count() == 0) continue;
$case->thumbnail = $case->images->first()->thumb_image_url;
}
$tree = new Tree();
$tree = $tree->make($cases->all());
return $tree;
}
/**
* This method will load entities between
* the given left and right boundaries
* For the given site- and lang-id
*
* @param $lft
* @param $rgt
* @param $siteId
* @param $langId
* @return mixed
*/
protected function getModelsBetween($lft, $rgt, $siteId, $langId)
{
//If siteId is null set currentSiteId
if($siteId == null) $siteId = $this->kms->getCurrentSiteId();
//If LangId is null set current LanguageId
if($langId == null) $langId = $this->kms->getDefaultLanguageId();
// $records = CaseModel::whereBetween('lft', [$lft + 1, $rgt - 1])
// ->with('translations')
// ->orderBy('lft', 'asc')
// ->get();
$records = \DB::table('cases')
->select('cases.lft', 'cases.rgt', 'case_translations.name', 'cases.id as id', 'case_translations.id as case_translations_id', 'case_translations.description', 'case_translations.slug')
->leftJoin('case_translations', 'cases.id', '=', 'case_translations.page_id')
->whereBetween('cases.lft', array($lft + 1, $rgt - 1))
->where('cases.site_id', '=', $siteId)
->where(function ($query) use ($langId) {
$query->whereNull('case_translations.language_id')
->orWhere('case_translations.language_id', '=', $langId);
})
->orderBy('cases.lft', 'asc')
->get();
return $records;
}
/**
* This method will save an model
*
* @param $input , filtered form input
* @param $page , Page model or null
* @return mixed
*/
public function saveModel($input, $case = null)
{
//create an empty fill array
$fill = [];
//Check if page is null
if($case == null)
{
// New Page
$case = new CaseModel();
//Set the lft and rgt based on the parent
$case->makeFirstChildOf($case->find($input['parent_id']));
}
else{
$case = CaseModel::find($case->id);
}
//Set the values from the form input
$case->active = $input['active'];
$case->code_name = $input['code_name'];
$case->primary_color = $input['primary_color'];
$case->drip_color = $input['drip_color'];
//Save the page
$case->save();
//Get all the routes for the current page
$routeIds = $this->routeService->getRouteIdsByRoute('cases/' . $case->id);
//Loop trough the language of the site
foreach ($this->kms->getCurrentSiteLanguages() as $language)
{
//Reset the $fill
$fill = [];
//Check if we can find a translation on the given page for the language from the current loop
if( ! $translation = $case->translations()->where('language_id', '=', $language->id)->first())
{
//No, new pageTranslation
$translation = new CaseTranslation();
//Set the default translations values
$fill['language_id'] = $language->id;
}
//Set the values from the form input
$fill['name'] = $input['name_' . $language->id];
$fill['slug'] = $input['slug_' . $language->id];
$fill['description'] = $input['description_' . $language->id];
$fill['meta_description'] = $input['meta_description_' . $language->id];
//Fill the translation
$translation->fill($fill);
//Bind and save the translation to the page
$case->translations()->save($translation);
$routeAlias = Str::slug($case->name);
//Let's do the routes
//Check if whe can find a route for this translation
$route = $translation->routes()->firstOrCreate([
'site_id' => $this->kms->getCurrentSiteId(),
'language_id' => $language->id,
'primary' => true,
'alias' => $routeAlias,
'route' => 'cases/' . $case->id
]);
$route->active = 1;
//Save the route
$route->save();
//Remove the id from the routeIds
$routeIds = array_diff($routeIds, [$route->id]);
}
//Pass the images to the saveImagesMethod
$this->imageService->saveImages($input['images'], $case->id);
//Set the status of the old routes to 0
$this->routeService->setFieldOnRouteIds($routeIds, 'active', 0);
//Return the pageId
return $case->id;
}
/**
* This method will remove an Page
*
* @param $id
*/
public function destroyModel($model)
{
//if( ! is_object($model) ) $model = CaseModel::find($model);
//delete the images
$this->deleteModelImages($model->id);
foreach ($model->translations()->get() as $translation)
{
//Delete the route of the translation
$translation->routes()->delete();
//Delete the translation
$translation->delete();
}
$model->delete();
}
/**
* This method will get one route based on the pageTranslationId
*
* @param $pageTranslationId
* @return null|Route
*/
public function getRouteByTranslationId($pageTranslationId)
{
if( ! $route = CaseTranslation::find($pageTranslationId)) return null;
return $route->routes()->first();
}
/**
* This method will create the root page if necessary.
* This page is used as a base for the lft and rgt.
*
* @param $siteId
* @return Page
*/
protected function makeRootPageIfNotExists($siteId)
{
//Check if there is a page for the current site with lft on 1
$page = \DB::table('cases')
->where('lft', 1)
->first();
//True, return true
if($page) return $page;
//Root page doesn't exist, so create a new
$page = new CaseModel(['site_id' => $siteId]);
$page->active = 1;
$page->makeRoot();
return $page;
}
/**
* Update the routes based on the RouteString
*
* @param $route
* @param $routeString
* @param $site_id
*/
protected function saveRoute($route, $routeString, $site_id)
{
$route->route = $routeString;
$route->save();
}
/**
* This function will save the route of the current page
* And adjust the routes of the available child pages
*
* @param $translationModel
* @param $model
* @param $translation
* @return bool
*/
protected function saveRouteAndChildRoutes($translationModel, $model, $translation)
{
$old_route = null;
//Load the routeableInterface
if($old_route = $this->getRouteByTranslationId($translationModel->id))
{
$old_route_text = $old_route->getAttribute('route');
//Update based on the route
$this->saveRoute($old_route, $translation->route, $model->getAttribute('site_id'));
}
else
{
//create based on the translationModel
$this->saveRoute($translationModel, $translation->route, $model->getAttribute('site_id'));
}
//Can we load the model attributes
if( ! $att = $model->getAttributes())
{
//no: exit function
return false;
}
//Can we load the children of the models
if( ! $children = $this->getModelsBetween($att['lft'], $att['rgt'], $att['site_id'], $translation->getLanguageId()))
{
//no: exit function
return false;
}
//We are going to loop trough the children and change the routes accordingly
foreach ($children as $child)
{
//Load The child route
if( ! $route = $this->getRouteByTranslationId($child->case_translations_id))
{
//no route (?!) go to next
continue;
}
//Replace the old_route part with the new route (translation_route) part
$new_route = str_replace($old_route_text, $translation->route, $route->getAttribute('route'));
$this->saveRoute($route, $new_route, $model->getAttribute('site_id'));
}
return true;
}
}