Completed
Pull Request — master (#139)
by Sebastian
07:31
created

ContentBlockTransformer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 14 1
A getMediaAttributes() 0 8 1
A getTranslatedAttributes() 0 10 2
1
<?php
2
3
namespace App\Models\Transformers;
4
5
use App\Models\ContentBlock;
6
use League\Fractal\TransformerAbstract;
7
8
class ContentBlockTransformer extends TransformerAbstract
9
{
10
    public function transform(ContentBlock $contentBlock)
11
    {
12
        $attributes = [
13
            'id' => $contentBlock->id,
14
            'type' => $contentBlock->type,
15
            'orderColumn' => $contentBlock->order_column,
16
        ];
17
18
        return array_merge(
19
            $attributes,
20
            $this->getMediaAttributes($contentBlock),
21
            $this->getTranslatedAttributes($contentBlock)
22
        );
23
    }
24
25
    protected function getMediaAttributes(ContentBlock $contentBlock): array
26
    {
27
        return array_reduce($contentBlock->mediaLibraryCollectionNames(), function ($mediaAttributes, $collectionName) use ($contentBlock) {
28
            $mediaAttributes[$collectionName] = fractal($contentBlock->getMedia($collectionName), new MediaTransformer())->toArray();
29
30
            return $mediaAttributes;
31
        }, []);
32
    }
33
34
    protected function getTranslatedAttributes(ContentBlock $contentBlock): array
35
    {
36
        return array_reduce($contentBlock->translatable, function ($translatables, $attribute) use ($contentBlock) {
37
            foreach (config('app.locales') as $locale) {
38
                $translatables[$attribute][$locale] = $contentBlock->getTranslation($attribute, $locale);
39
            }
40
41
            return $translatables;
42
        }, []);
43
    }
44
}
45