diff --git a/src/Abstracts/Transformers/Transformer.php b/src/Abstracts/Transformers/Transformer.php index d7ac7e62..2483f53a 100644 --- a/src/Abstracts/Transformers/Transformer.php +++ b/src/Abstracts/Transformers/Transformer.php @@ -2,6 +2,7 @@ namespace Apiato\Core\Abstracts\Transformers; +use Apiato\Core\Contracts\HasResourceKey; use Apiato\Core\Exceptions\CoreInternalErrorException; use Apiato\Core\Exceptions\UnsupportedFractalIncludeException; use Illuminate\Support\Facades\Config; @@ -13,30 +14,31 @@ abstract class Transformer extends FractalTransformer { - public function nullableItem($data, $transformer, $resourceKey = null): Primitive|Item + protected function nullableItem($data, $transformer, $resourceKey = null): Primitive|Item { if (is_null($data)) { return $this->primitive(null); } - return $this->item($data, $transformer, $resourceKey = null); + return $this->item($data, $transformer, $resourceKey); } - public function item($data, $transformer, $resourceKey = null): Item + protected function item($data, $transformer, string|null $resourceKey = null): Item { - // set a default resource key if none is set - if (!$resourceKey && $data) { + if (!$resourceKey && $data instanceof HasResourceKey) { $resourceKey = $data->getResourceKey(); } return parent::item($data, $transformer, $resourceKey); } - public function collection($data, $transformer, $resourceKey = null): Collection + protected function collection($data, $transformer, string|null $resourceKey = null): Collection { - // set a default resource key if none is set if (!$resourceKey && $data->isNotEmpty()) { - $resourceKey = $data->first()->getResourceKey(); + $firstItem = $data->first(); + if ($firstItem instanceof HasResourceKey) { + $resourceKey = $firstItem->getResourceKey(); + } } return parent::collection($data, $transformer, $resourceKey);