From c8cb9464c01557e112245d0b18e5f9664eb7e362 Mon Sep 17 00:00:00 2001 From: Dimitrios Kontoulis Date: Tue, 14 Jun 2022 12:33:13 +0300 Subject: [PATCH] Pass only required translations to ModelTransformer --- .../Transformers/CollectionTransformer.php | 63 +++++++++++++++++-- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/src/Translator/Transformers/CollectionTransformer.php b/src/Translator/Transformers/CollectionTransformer.php index 257651e..45a4bfe 100644 --- a/src/Translator/Transformers/CollectionTransformer.php +++ b/src/Translator/Transformers/CollectionTransformer.php @@ -1,15 +1,16 @@ groupBy(fn ($translation) => $this->groupByKey($translation)); + foreach ($collection as $model) { - app(ModelTransformer::class)->applyTranslations($model, $translations, $shallow); + if (($modelTranslations = $this->modelTranslations($translations, $model, $shallow))->isNotEmpty()) { + app(ModelTransformer::class)->applyTranslations($model, $modelTranslations, $shallow); + } } return $collection; } + + protected function modelTranslations(Collection $translations, Model $model, bool $shallow = false) + { + $relationTranslations = ($translations->get($this->groupByKey($model), collect()))->toBase(); + + if (!$shallow && $relations = array_filter($model->getRelations())) { + $relationTranslations = $relationTranslations->merge( + $this->parseRelationsTranslations($relations, $translations) + ); + } + + return new \Illuminate\Database\Eloquent\Collection( + $relationTranslations + ->filter() + ->flatten() + ); + } + + protected function parseRelationsTranslations(array $relations, Collection $translations): Collection + { + $relationTranslations = collect(); + foreach ($relations as $relation) { + if ($relation instanceof Collection) { + foreach ($relation as $item) { + $relationTranslations = $relationTranslations->merge( + $this->modelTranslations($translations, $item) + ->groupBy(fn ($item) => $this->groupByKey($item)) + ); + } + } else { + $relationTranslations->push($translations->get($this->groupByKey($relation))); + } + } + + return $relationTranslations; + } + + protected function groupByKey($item) + { + if ($item instanceof Translation || $item instanceof \stdClass) { + return $item->foreign_id.$item->resource; + } + + return $item->id.class_basename($item); + } }