File: D:/HostingSpaces/SBogers10/honger.komma.pro/app/KommaApp/Cases/CaseService.php
<?php
namespace App\KommaApp\Cases;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
use App\KommaApp\Cases\Models\CaseModel;
use Illuminate\Support\Str;
class CaseService
{
protected $cases;
/**
* Get all cases with current language
*
* @return Collection|false
*/
public function all()
{
// Fetch all cases from the database
if(empty($this->cases)) $this->cases = $this->cases();
return $this->cases;
}
/**
* Get a number of cases with current language
*
* @return Collection|false
*/
public function other($except,$limit = null)
{
// Fetch all cases from the database
if(empty($this->cases)) $this->cases = $this->cases();
$cases = $this->cases->except($except);
if($limit != null) $cases = $cases->take($limit);
return $cases;
}
/**
* Get cases with current language
*
* @return Collection|false
*/
private function cases($limit = null, $except = null)
{
return Cache::rememberForever('cases',function() use ($limit,$except){
// Get cases with translations
$caseBuilder = CaseModel::with('translation', 'images')
->whereHas('translation')
->where('active',1)
->where('lft', '!=', 1)
->orderBy('lft','asc');
// Take a limit of cases
if( $limit != null) $caseBuilder->take($limit);
// Skip a case
if( $except != null) $caseBuilder->where('id','!=',$except);
// Run query
if( ! $cases = $caseBuilder->get()) return false;
return $this->prepareCasesForUsage($cases);
});
}
/**
* Return a case by its slug
*
* @param $slug
* @return CaseModel|false
*/
public function caseBySlug($slug)
{
// Get case with translations
if( ! $case = CaseModel::with('translation', 'images')
->whereHas('translation')
->first()) return false;
// QnD: bind first translations directly to model
$case->translation = $case->translations->first();
return $case;
}
/**
* Return a next and previous case
*
* @param CaseModel $case
* @return false|Collection
*/
public function adjacentCases(CaseModel $case)
{
// Get case with translations
if( ! $cases = CaseModel::with('translation', 'images')
->whereHas('translation')
->where('active',1)
->where(function ($query) use ($case){
$query->where('lft','=',($case->lft + 2))
->orWhere('lft','=',$case->lft - 2);
})
->where('lft', '!=', 1)
->orderBy('lft','asc')
->get()) return false;
return $this->prepareCasesForUsage($cases);
}
/**
* Bind key and set default thumbnail
*
* @param $cases
* @return mixed
*/
private function prepareCasesForUsage($cases)
{
// Loop through cases
foreach($cases as $key => $case)
{
// Bind key
! empty($case->code_name) ?
$cases[$key]->key = $case->code_name : $cases[$key]->key = Str::camel($cases[$key]->translation->slug);
// Set default thumbnail
// Find thumbnail
$case->images->isEmpty() ?
$cases[$key]->thumbnail = '/images/komma/temp/temp.jpg' :
$cases[$key]->thumbnail = $case->images->shift()->large_image_url;
}
return $cases;
}
}