HandleMedias::getMedias()   C
last analyzed

Complexity

Conditions 12
Paths 2

Size

Total Lines 59
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 116.0688

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 42
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 59
ccs 4
cts 39
cp 0.1026
crap 116.0688
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace A17\Twill\Repositories\Behaviors;
4
5
use A17\Twill\Models\Media;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
10
trait HandleMedias
11
{
12
    /**
13
     * @param \A17\Twill\Models\Model $object
14
     * @param array $fields
15
     * @return \A17\Twill\Models\Model
16
     */
17 3
    public function hydrateHandleMedias($object, $fields)
18
    {
19 3
        if ($this->shouldIgnoreFieldBeforeSave('medias')) {
0 ignored issues
show
Bug introduced by
It seems like shouldIgnoreFieldBeforeSave() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

19
        if ($this->/** @scrutinizer ignore-call */ shouldIgnoreFieldBeforeSave('medias')) {
Loading history...
20
            return $object;
21
        }
22
23 3
        $mediasCollection = Collection::make();
24 3
        $mediasFromFields = $this->getMedias($fields);
25
26 3
        $mediasFromFields->each(function ($media) use ($object, $mediasCollection) {
27
            $newMedia = Media::withTrashed()->find(is_array($media['id']) ? Arr::first($media['id']) : $media['id']);
28
            $pivot = $newMedia->newPivot($object, Arr::except($media, ['id']), config('twill.mediables_table', 'twill_mediables'), true);
29
            $newMedia->setRelation('pivot', $pivot);
30
            $mediasCollection->push($newMedia);
31 3
        });
32
33 3
        $object->setRelation('medias', $mediasCollection);
34
35 3
        return $object;
36
    }
37
38
    /**
39
     * @param \A17\Twill\Models\Model $object
40
     * @param array $fields
41
     * @return void
42
     */
43 21
    public function afterSaveHandleMedias($object, $fields)
44
    {
45 21
        if ($this->shouldIgnoreFieldBeforeSave('medias')) {
46
            return;
47
        }
48
49 21
        $object->medias()->sync([]);
50
51 21
        $this->getMedias($fields)->each(function ($media) use ($object) {
52
            $object->medias()->attach($media['id'], Arr::except($media, ['id']));
53 21
        });
54 21
    }
55
56
    /**
57
     * @param array $fields
58
     * @return \Illuminate\Support\Collection
59
     */
60 22
    private function getMedias($fields)
61
    {
62 22
        $medias = Collection::make();
63
64 22
        if (isset($fields['medias'])) {
65
            foreach ($fields['medias'] as $role => $mediasForRole) {
66
                if (config('twill.media_library.translated_form_fields', false)) {
67
                    if (Str::contains($role, ['[', ']'])) {
68
                        $start = strpos($role, '[') + 1;
69
                        $finish = strpos($role, ']', $start);
70
                        $locale = substr($role, $start, $finish - $start);
71
                        $role = strtok($role, '[');
72
                    }
73
                }
74
75
                $locale = $locale ?? config('app.locale');
76
77
                if (in_array($role, array_keys($this->model->mediasParams ?? []))
78
                    || in_array($role, array_keys(config('twill.block_editor.crops', [])))
79
                    || in_array($role, array_keys(config('twill.settings.crops', [])))) {
80
                    Collection::make($mediasForRole)->each(function ($media) use (&$medias, $role, $locale) {
81
                        $customMetadatas = $media['metadatas']['custom'] ?? [];
82
                        if (isset($media['crops']) && !empty($media['crops'])) {
83
                            foreach ($media['crops'] as $cropName => $cropData) {
84
                                $medias->push([
85
                                    'id' => $media['id'],
86
                                    'crop' => $cropName,
87
                                    'role' => $role,
88
                                    'locale' => $locale,
89
                                    'ratio' => $cropData['name'],
90
                                    'crop_w' => $cropData['width'],
91
                                    'crop_h' => $cropData['height'],
92
                                    'crop_x' => $cropData['x'],
93
                                    'crop_y' => $cropData['y'],
94
                                    'metadatas' => json_encode($customMetadatas),
95
                                ]);
96
                            }
97
                        } else {
98
                            foreach ($this->getCrops($role) as $cropName => $cropDefinitions) {
99
                                $medias->push([
100
                                    'id' => $media['id'],
101
                                    'crop' => $cropName,
102
                                    'role' => $role,
103
                                    'locale' => $locale,
104
                                    'ratio' => Arr::first($cropDefinitions)['name'],
105
                                    'crop_w' => null,
106
                                    'crop_h' => null,
107
                                    'crop_x' => null,
108
                                    'crop_y' => null,
109
                                    'metadatas' => json_encode($customMetadatas),
110
                                ]);
111
                            }
112
                        }
113
                    });
114
                }
115
            }
116
        }
117
118 22
        return $medias;
119
    }
120
121
    /**
122
     * @param \A17\Twill\Models\Model $object
123
     * @param array $fields
124
     * @return array
125
     */
126 6
    public function getFormFieldsHandleMedias($object, $fields)
127
    {
128 6
        $fields['medias'] = null;
129
130 6
        if ($object->has('medias')) {
131 6
            foreach ($object->medias->groupBy('pivot.role') as $role => $mediasByRole) {
0 ignored issues
show
Bug introduced by
The property medias does not seem to exist on A17\Twill\Models\Model. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
132
                if (config('twill.media_library.translated_form_fields', false)) {
133
                    foreach ($mediasByRole->groupBy('pivot.locale') as $locale => $mediasByLocale) {
134
                        foreach ($this->getMediaFormItems($mediasByLocale) as $item) {
135
                            $fields['medias'][$locale][$role][] = $item;
136
                        }
137
                    }
138
                } else {
139
                    foreach ($this->getMediaFormItems($mediasByRole) as $item) {
140
                        $fields['medias'][$role][] = $item;
141
                    }
142
                }
143
            }
144
        }
145
146 6
        return $fields;
147
    }
148
149
    /**
150
     * @param \Illuminate\Database\Eloquent\Collection $medias
151
     * @return array
152
     */
153
    private function getMediaFormItems($medias)
154
    {
155
        $itemsForForm = [];
156
157
        foreach ($medias->groupBy('id') as $id => $mediasById) {
158
            $item = $mediasById->first();
159
160
            $itemForForm = $item->toCmsArray();
161
162
            $itemForForm['metadatas']['custom'] = json_decode($item->pivot->metadatas, true);
163
164
            foreach ($mediasById->groupBy('pivot.crop') as $crop => $mediaByCrop) {
165
                $media = $mediaByCrop->first();
166
                $itemForForm['crops'][$crop] = [
167
                    'name' => $media->pivot->ratio,
168
                    'width' => $media->pivot->crop_w,
169
                    'height' => $media->pivot->crop_h,
170
                    'x' => $media->pivot->crop_x,
171
                    'y' => $media->pivot->crop_y,
172
                ];
173
            }
174
175
            $itemsForForm[] = $itemForForm;
176
        }
177
178
        return $itemsForForm;
179
    }
180
181
    /**
182
     * @param string $role
183
     * @return array
184
     */
185
    public function getCrops($role)
186
    {
187
        return $this->model->mediasParams[$role];
188
    }
189
}
190