File: D:/HostingSpaces/SBogers10/blije-gasten.komma.pro/app/Komma/Kms/JsonApi/TranslatableResource.php
<?php
namespace App\Komma\Kms\JsonApi;
use App\Helpers\KommaHelpers;
use App\Komma\Kms\Core\AbstractTranslatableModel;
use Illuminate\Http\Resources\Json\Resource;
class TranslatableResource extends Resource
{
public function __construct($resource)
{
if(!is_a($resource,AbstractTranslatableModel::class)) throw new \InvalidArgumentException('The resource must be an instance of '.AbstractTranslatableModel::class);
parent::__construct($resource);
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$attributes = $this->resource->toArray();
$attributes['translations'] = [];
$index = 0;
foreach ($attributes as $key => $attribute) {
if(is_array($attribute)) array_splice($attributes, $index, 1);
$index++;
}
$data = [
'id' => (string) $this->id,
'type' => KommaHelpers::getShortNameFromClass($this->resource, true),
'attributes' => $attributes,
];
$this->resource->translation()->get()->each(function($translation) use(&$data) {
$data['attributes']['translation'][] = new TranslationResource($translation);
});
return $data;
}
}