File: D:/HostingSpaces/EUmans/umansradepo.be/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\Posts\Models\Post;
use Komma\Kms\Posts\Models\PostTranslation;
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 = 'blog';
/**
* @var Tree
*/
protected $tree;
/**
* @var ImageRepository
*/
private $imageRepository;
/**
* @var
*/
private $model;
/**
* @var
*/
private $modelTranslation;
private $imageService;
private $languages;
/**
* PostRepository constructor.
* @param Kms $kms
* @param Tree $tree
* @param ImageService $imageService
*/
function __construct(
Kms $kms,
Tree $tree,
ImageService $imageService,
Language $language
)
{
parent::__construct($kms);
$this->tree = $tree;
$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->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 . '.lft',
$this->table . '.rgt',
$this->table . '.id as id',
$this->tableTranslation . '.id as ' . $this->translationId,
$this->tableTranslation . '.name',
$this->tableTranslation . '.sub_title',
$this->tableTranslation . '.description',
'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(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)
{
$categories[] = new KmsHierarchicalListItemEntity((array)$record);
}
$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->makeLastChildOf(Post::where('lft', '=', 1)->first());
}
//Set the fields
$post->active = $entity->active;
$post->show_on_home = $entity->show_on_home;
//Slugify the code_name, just o be safe
$post->code_name = \Str::slug($entity->code_name);
//if Date is not set, make it date today
if($entity->date == null)
{
$post->date = Carbon::now();
}
else
{
if(isset($_POST['timepicker'])){
$subTime = $_POST['timepicker'];
$subTime = preg_replace('/\s+/', '', $subTime);
$subTime .= ':00';
$post->date = $entity->date->format('Y-m-d').' '.$subTime;
}
else{
//add current time to string because datepicker only returns time
$post->date = $entity->date->format('Y-m-d').' '.Carbon::now()->addHour()->format('H:i:s');
}
}
$post->save();
foreach ($entity->getTranslations() as $translation)
{
if(( ! isset($translation->name) || $translation->name == '') && ( ! isset($translation->sub_title) || $translation->sub_title == '') && ( ! isset($translation->meta_description) || $translation->meta_description == '') && ( ! isset($translation->description) || $translation->description == '[]'))
{
continue;
}
$postTranslation = PostTranslation::firstOrNew(['post_id' => $post->id, 'language_id' => $translation->getLanguageId()]);
$postTranslation->name = $translation->name;
$postTranslation->sub_title = $translation->sub_title;
//$postTranslation->description = $translation->description;
$postTranslation->meta_description = $translation->meta_description;
$dps = \App::make('Komma\Kms\Core\Services\DynamicPageService');
$description = $dps->prepareDynamicDescription(json_decode($translation->description), $post);
$postTranslation->description = $description;
$postTranslation->save();
if($translation->id != null && $translation->route != 'blog/' && $translation->route != '')
{
if($this->kms->getCurrentLanguages()->count()> 1)
{
$languageIso = $this->getLanguageIso($translation->getLanguageId());
$routeSting = $languageIso->iso_2 . '/' . $translation->route;
}
else{
$routeSting = $translation->route;
}
$this->saveRoute($postTranslation, $routeSting, $this->type . '/' . $post->id);
}
elseif($translation->name != '')
{
$route = $this->getBaseUrl($translation->getLanguageId()) . '/' . \Str::slug($postTranslation->name);
$this->saveRoute($postTranslation, $route, $this->type . '/' . $post->id);
}
}
//Link the images to this model
$this->imageService->linkImagesToModel('images', $post);
return $post;
}
public function getForSelect($languageId = null, $excludeId = null)
{
return [];
$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(' ', $record->getDepth());
$entity['htmlContent'] = $indent . $record->node->getName();
if( ! $entity['htmlContent']) $entity['htmlContent'] = '\\';
$entities[] = $entity;
}
return $entities;
}
protected function getProductCategoryIds($postId)
{
$records = \DB::table('post_categories')
->where('post_id', $postId)
->select('category_id as id')
->get();
$ids = [];
foreach ($records as $record)
{
$ids[] = $record->id;
}
return $ids;
}
public function getCategoriesForSelect()
{
$records = \DB::table('categories')
->leftJoin('category_translations', 'categories.id', '=', 'category_translations.category_id')
->orderBy('categories.lft', 'asc')
->select('categories.lft', 'categories.rgt', 'category_translations.name', 'categories.id as id', 'category_translations.id as category_translation_id')
->where('category_translations.name', '!=', 'null')
->get();
$entities = [];
foreach ($records as $record) {
$entity = [];
$entity['value'] = $record->id;
$entity['fullValue'] = $record->id;
$entity['content'] = $record->name;
$entity['htmlContent'] = $record->name;
$entities[] = $entity;
}
return $entities;
}
public function destroyEntity($id)
{
$entity = Post::find($id);
foreach ($entity->translations()->get() as $translation)
{
$translation->routes()->delete();
}
$entity->delete();
}
public function getRouteByTranslationId($productId)
{
if($route = PostTranslation::find($productId))
{
return $route->routes()->first();
}
return null;
}
public function checkIfRouteExist($routeString, $notId = false, $routable = null)
{
//dd($routable);
if( ! $notId) return \DB::table('routes')->where('route', $routeString)->exists();
return \DB::table('routes')->where('routable_id', '!=', $notId)->where('route', $routeString)->exists();
}
protected function saveRoute(RoutableInterface $routable, $routeString, $restRoute = null)
{
$routeString = $this->makeRouteUnique($routable, $routeString);
if($route = $this->getRouteByTranslationId($routable->id))
{
if($this->checkIfRouteExist($routeString, $routable->id, $routable)) $routeString .= '-' . Carbon::now()->timestamp;
$route->route = $routeString;
if($restRoute != null) $route->rest_route = $restRoute;
$route->save();
}
else
{
if($this->checkIfRouteExist($routeString)) $routeString .= '-' . Carbon::now()->timestamp;
$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();
}
}
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');
}
public function getBaseUrl($language)
{
//Lang toevoegen
if( ! $route = KmsRoute::select('routes.*')
->where('routes.rest_route', '=', $this->type)
->Join('page_translations', 'routes.routable_id', '=', 'page_translations.id')
->where('page_translations.language_id', '=', $language)
->first()
) return '';
return $route->route;
}
public function getLanguageIso($langId)
{
return Language::where('id', $langId)->first();
}
}