AssetsRepository::getFieldValue()   A
last analyzed

Complexity

Conditions 5
Paths 16

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 4
c 1
b 0
f 0
nc 16
nop 6
dl 0
loc 7
ccs 0
cts 7
cp 0
crap 30
rs 9.6111
1
<?php
2
3
namespace Distilleries\Contentful\Repositories;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Collection;
7
use Distilleries\Contentful\Models\Asset;
8
use Distilleries\Contentful\Models\Locale;
9
10
class AssetsRepository
11
{
12
    use Traits\EntryType;
13
14
    /**
15
     * Truncate all Assets related tables.
16
     *
17
     * @return void
18
     */
19
    public function truncateRelatedTables()
20
    {
21
        Asset::query()->truncate();
22
    }
23
24
    /**
25
     * Map Contentful asset payload to an Eloquent one.
26
     *
27
     * @param  array  $asset
28
     * @param \Illuminate\Support\Collection  $locales
29
     * @return void
30
     */
31
    public function toContentfulModel(array $asset, Collection $locales)
32
    {
33
        $this->upsertEntryType($asset, 'asset');
34
35
        foreach ($locales as $locale) {
36
            $this->upsertAsset($asset, $locale->code);
37
        }
38
    }
39
40
    /**
41
     * Delete asset with given Contentful ID.
42
     *
43
     * @param  string  $assetId
44
     * @return void
45
     */
46
    public function delete(string $assetId)
47
    {
48
        $this->deleteEntryType($assetId);
49
50
        Asset::query()->where('contentful_id', '=', $assetId)->delete();
51
    }
52
53
    /**
54
     * Return all locales in asset payload.
55
     *
56
     * @param  array  $asset
57
     * @return array
58
     */
59
    private function assetLocales(array $asset): array
0 ignored issues
show
Unused Code introduced by
The method assetLocales() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
60
    {
61
        $locales = [];
62
63
        if (isset($asset['fields']) && ! empty($asset['fields'])) {
64
            $firstField = Arr::first($asset['fields']);
65
            $locales = array_keys($firstField);
0 ignored issues
show
Bug introduced by
It seems like $firstField can also be of type null; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

65
            $locales = array_keys(/** @scrutinizer ignore-type */ $firstField);
Loading history...
66
        }
67
68
        return $locales;
69
    }
70
71
    /**
72
     * Insert OR update given asset.
73
     *
74
     * @param  array  $asset
75
     * @param  string  $locale
76
     * @return \Distilleries\Contentful\Models\Asset
77
     */
78
    private function upsertAsset(array $asset, string $locale): ?Asset
79
    {
80
        $country = Locale::getCountry($locale);
81
        $iso = Locale::getLocale($locale);
82
83
        if (! Locale::canBeSave($country, $iso)) {
84
            return null;
85
        }
86
87
        $data = $this->mapAsset($asset, $locale);
88
        $instance = Asset::query()
89
            ->where('contentful_id', '=', $asset['sys']['id'])
90
            ->where('locale', '=', $iso)
91
            ->where('country', '=', $country)
92
            ->first();
93
94
        if (empty($instance)) {
95
            $instance = Asset::query()->create($data);
96
        } else {
97
            Asset::query()
98
                ->where('contentful_id', '=', $asset['sys']['id'])
99
                ->where('locale', '=', $iso)
100
                ->where('country', '=', $country)
101
                ->update($data);
102
103
            $instance = Asset::query()
104
                ->where('contentful_id', '=', $asset['sys']['id'])
105
                ->where('locale', '=', $iso)
106
                ->where('country', '=', $country)
107
                ->first();
108
        }
109
110
        return $instance;
111
    }
112
113
    /**
114
     * Map a Contentful asset to it's Eloquent model signature.
115
     *
116
     * @param  array  $asset
117
     * @param  string  $locale
118
     * @return array
119
     */
120
    private function mapAsset(array $asset, string $locale): array
121
    {
122
        return [
123
            'contentful_id' => $asset['sys']['id'],
124
            'locale' => Locale::getLocale($locale),
125
            'country' => Locale::getCountry($locale),
126
        ] + $this->fieldsWithFallback($asset['fields'], $locale);
127
    }
128
129
    /**
130
     * Return asset fields with locale OR locale fallback data.
131
     *
132
     * @param  array  $fields
133
     * @param  string  $locale
134
     * @return array
135
     */
136
    private function fieldsWithFallback(array $fields, string $locale): array
137
    {
138
        $fallbackLocale = Locale::fallback($locale);
139
        $secondFallback = Locale::fallback($fallbackLocale);
140
        $file = $this->getFieldValue($fields, 'file', $locale, $fallbackLocale, [], $secondFallback);
141
        $details = isset($file['details']) ? $file['details'] : [];
142
143
        return [
144
            'title' => $this->getFieldValue($fields, 'title', $locale, $fallbackLocale, '', $secondFallback),
145
            'description' => $this->getFieldValue($fields, 'description', $locale, $fallbackLocale, '', $secondFallback),
146
            'url' => isset($file['url']) ? $file['url'] : '',
147
            'file_name' => isset($file['fileName']) ? $file['fileName'] : '',
148
            'content_type' => isset($file['contentType']) ? $file['contentType'] : '',
149
            'size' => (isset($details['size'])) ? intval($details['size']) : 0,
150
            'width' => (isset($details['image']) && isset($details['image']['width'])) ? intval($details['image']['width']) : 0,
151
            'height' => (isset($details['image']) && isset($details['image']['height'])) ? intval($details['image']['height']) : 0,
152
        ];
153
    }
154
155
    /**
156
     * Get given field value.
157
     *
158
     * @param  array  $fields
159
     * @param  string  $field
160
     * @param  string  $locale
161
     * @param  string  $fallbackLocale
162
     * @param  mixed  $default
163
     * @param  string|null  $secondFallback
164
     * @return mixed
165
     */
166
    protected function getFieldValue(array $fields, string $field, string $locale, string $fallbackLocale, $default, string $secondFallback = null)
167
    {
168
        return ! empty($fields[$field][$locale]) ?
169
            $fields[$field][$locale] :
170
            (
171
                ! empty($fields[$field][$fallbackLocale]) ? $fields[$field][$fallbackLocale] :
172
                (! empty($secondFallback) && ! empty($fields[$field][$secondFallback]) ? $fields[$field][$secondFallback] : $default)
173
            );
174
    }
175
}
176