AssetTransformer::transform()   B
last analyzed

Complexity

Conditions 7
Paths 36

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 17
c 1
b 0
f 0
nc 36
nop 2
dl 0
loc 27
ccs 0
cts 23
cp 0
crap 56
rs 8.8333
1
<?php
2
3
namespace Distilleries\Contentful\Models\Transformers;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Collection;
7
use Distilleries\Contentful\Models\Asset;
8
use Distilleries\Contentful\Helpers\Image;
9
10
/**
11
 * @OAS\Schema(schema="Asset", type="object",
12
 *   @OAS\Property(property="title", type="string", description="Asset title"),
13
 *   @OAS\Property(property="description", type="string", description="Asset description"),
14
 *   @OAS\Property(property="url", type="string", description="Asset URL")
15
 * )
16
 */
17
class AssetTransformer
18
{
19
    /**
20
     * Transform given asset.
21
     *
22
     * @param  \Distilleries\Contentful\Models\Asset  $model
23
     * @param  array  $parameters
24
     * @return array
25
     */
26
    public function transform(Asset $model, array $parameters = []): array
27
    {
28
        if (Str::startsWith($model->content_type, 'image/')) {
29
            $width = 0;
30
            if (isset($parameters['width'])) {
31
                $width = (int) $parameters['width'];
32
            }
33
34
            $height = 0;
35
            if (isset($parameters['height'])) {
36
                $height = (int) $parameters['height'];
37
            }
38
39
            $fit = '';
40
            if (isset($parameters['fit'])) {
41
                $fit = trim($parameters['fit']);
42
            }
43
44
            $url = Image::url($model->url, $width, $height, '', 0, null, $fit);
45
        } else {
46
            $url = $model->url;
47
        }
48
49
        return [
50
            'title' => ! empty($model->title) ? $model->title : null,
51
            'description' => ! empty($model->description) ? $model->description : null,
52
            'url' => $url,
53
        ];
54
    }
55
56
    /**
57
     * Transform given collection data.
58
     *
59
     * @param  \Illuminate\Support\Collection  $collection
60
     * @param  array  $parameters
61
     * @return \Illuminate\Support\Collection
62
     */
63
    public function transformCollection(Collection $collection, array $parameters = []): Collection
64
    {
65
        $collection->filter(function ($value) {
66
            return ! empty($value);
67
        });
68
69
        if ($collection->isEmpty()) {
70
            return collect();
71
        }
72
73
        return $collection->transform(function ($model) use ($parameters) {
74
            return $this->transform($model, $parameters);
75
        });
76
    }
77
}
78