File: D:/HostingSpaces/SBogers10/rentman2019.komma.pro/app/Komma/Kms/Core/Tree/TreeResource.php
<?php
namespace App\Komma\Kms\Core\Tree;
use App\Komma\Kms\Core\AbstractTranslatableModel;
use App\Komma\Kms\Core\AbstractTranslationModel;
use App\Komma\Kms\Core\Attributes\Models\Traits\HasThumbnailInterface;
use App\Komma\Kms\Core\Attributes\Models\Traits\HasThumbnailTrait;
use App\Komma\Kms\Core\HasRoutesInterface;
use App\Komma\Kms\Core\NestedSets\Nodes\TreeModelInterface;
use Illuminate\Http\Resources\Json\Resource;
/**
* Class TreeResource
*
* A Tree resource. Used for Converting TreeModelInterfaces to json
* Representing the models you give it in a tree fashioned way.
*
* @see TreeResourceCollection
*/
class TreeResource extends Resource
{
public function toArray($request)
{
if (! is_a($this->resource, TreeModelInterface::class)) {
throw new \RuntimeException('The item that you put into a '.self::class.' must be an '.TreeModelInterface::class.' instance');
}
$thumbnail = '';
if (is_a($this->resource, HasThumbnailInterface::class)) {
/** @var HasThumbnailTrait $resource $ */
$resource = $this->resource;
$thumbnail = $resource->getThumbnail();
}
$data = [
'id' => $this->id,
'title' => $this->getSideBarName(),
'thumbnail' => $thumbnail,
'status' => 1,
];
if (is_a($this->resource, AbstractTranslatableModel::class)) {
/** @var $this HasRoutesInterface|TreeResource */
$data['routes'] = $this->retrieveRoutes();
}
if ($this->lft + 1 != $this->right) {
$data['children'] = new TreeResourceCollection(collect($this->findChildren()));
} else {
$data['children'] = [];
}
return $data;
}
/**
* Returns an array keyed by language id having route alias attributes as values
*
* @return array
*/
private function retrieveRoutes()
{
//Create empty Routes array
$routes = [];
//If there are no translations, return empty array
if (! isset($this->translations)) {
return $routes;
}
//Loop trough the translations
foreach ($this->translations as $translation) {
/** @var AbstractTranslationModel $translation */
//Get the primary route, if non existing, skip to the next language
if (! $route = $translation->route) {
continue;
}
//Set the alias based on the language id
$routes[$translation->language_id] = $route->alias;
}
//Return the array of routes
return $routes;
}
}