Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

HandleRepeatableUploads   F
last analyzed

Complexity

Total Complexity 69

Size/Duplication

Total Lines 337
Duplicated Lines 0 %

Importance

Changes 13
Bugs 11 Features 0
Metric Value
eloc 137
dl 0
loc 337
rs 2.88
c 13
b 11
f 0
wmc 69

26 Methods

Rating   Name   Duplication   Size   Complexity  
A handleRepeatableFiles() 0 13 2
A uploadRepeatableFiles() 0 2 1
A processRelationshipRepeatableUploaders() 0 7 2
A repeats() 0 7 1
A getRepeatableContainerName() 0 3 1
B uploadRelationshipFiles() 0 28 7
A hasDeletedFiles() 0 3 3
A getUploaderSubfield() 0 3 1
A getFileOrderFromRequest() 0 10 3
B deleteRepeatableRelationFiles() 0 46 9
A getValuesWithPathStripped() 0 10 3
A retrieveRepeatableRelationFiles() 0 16 3
A getRepeatableRelationType() 0 3 1
A getUploaderFieldSubfields() 0 3 1
A getUploaderField() 0 3 1
A getPreviousRepeatableValues() 0 9 2
A deleteRelationshipFiles() 0 4 2
A mergeValuesRecursive() 0 12 5
B deleteRepeatableFiles() 0 28 8
A shouldKeepPreviousValueUnchanged() 0 3 3
A getEntryAttributeValue() 0 3 1
A getEntryOriginalValue() 0 3 1
A shouldUploadFiles() 0 3 1
A retrieveRepeatableFiles() 0 21 4
A processRepeatableUploads() 0 13 2
A getFilesFromEntry() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like HandleRepeatableUploads often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HandleRepeatableUploads, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Backpack\CRUD\app\Library\Uploaders\Support\Traits;
4
5
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
6
use Backpack\CRUD\app\Library\Uploaders\Support\Interfaces\UploaderInterface;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Facades\Log;
10
use Illuminate\Support\Facades\Storage;
11
use Illuminate\Support\Str;
12
13
trait HandleRepeatableUploads
14
{
15
    public bool $handleRepeatableFiles = false;
16
17
    public null|string $repeatableContainerName = null;
18
19
    /*******************************
20
     * Setters - fluently configure the uploader
21
     *******************************/
22
    public function repeats(string $repeatableContainerName): self
23
    {
24
        $this->handleRepeatableFiles = true;
25
26
        $this->repeatableContainerName = $repeatableContainerName;
27
28
        return $this;
29
    }
30
31
    /*******************************
32
     * Getters
33
     *******************************/
34
    public function getRepeatableContainerName(): null|string
35
    {
36
        return $this->repeatableContainerName;
37
    }
38
39
    /*******************************
40
     * Default implementation methods
41
     *******************************/
42
    protected function uploadRepeatableFiles($values, $previousValues, $entry = null)
43
    {
44
    }
45
46
    protected function handleRepeatableFiles(Model $entry): Model
47
    {
48
        if ($this->isRelationship) {
49
            return $this->processRelationshipRepeatableUploaders($entry);
50
        }
51
52
        $values = collect(CRUD::getRequest()->get($this->getRepeatableContainerName()));
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on Backpack\CRUD\app\Librar...udPanel\CrudPanelFacade. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

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

52
        $values = collect(CRUD::/** @scrutinizer ignore-call */ getRequest()->get($this->getRepeatableContainerName()));
Loading history...
53
        $files = collect(CRUD::getRequest()->file($this->getRepeatableContainerName()));
54
        $value = $this->mergeValuesRecursive($values, $files);
55
56
        $entry->{$this->getRepeatableContainerName()} = json_encode($this->processRepeatableUploads($entry, $value));
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type array; however, parameter $values of Backpack\CRUD\app\Librar...cessRepeatableUploads() does only seem to accept Illuminate\Support\Collection, 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

56
        $entry->{$this->getRepeatableContainerName()} = json_encode($this->processRepeatableUploads($entry, /** @scrutinizer ignore-type */ $value));
Loading history...
57
58
        return $entry;
59
    }
60
61
    private function processRelationshipRepeatableUploaders(Model $entry)
62
    {
63
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
64
            $entry = $uploader->uploadRelationshipFiles($entry);
65
        }
66
67
        return $entry;
68
    }
69
70
    protected function uploadRelationshipFiles(Model $entry): Model
71
    {
72
        $entryValue = $this->getFilesFromEntry($entry);
73
74
        if ($this->handleMultipleFiles && is_string($entryValue)) {
75
            try {
76
                $entryValue = json_decode($entryValue, true);
77
            } catch (\Exception) {
78
                return $entry;
79
            }
80
        }
81
82
        if ($this->hasDeletedFiles($entryValue)) {
83
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, false);
0 ignored issues
show
Bug introduced by
It seems like getAttributeName() 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

83
            $entry->{$this->/** @scrutinizer ignore-call */ getAttributeName()} = $this->uploadFiles($entry, false);
Loading history...
Bug introduced by
It seems like uploadFiles() 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

83
            /** @scrutinizer ignore-call */ 
84
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, false);
Loading history...
84
            $this->updatedPreviousFiles = $this->getEntryAttributeValue($entry);
0 ignored issues
show
Bug Best Practice introduced by
The property updatedPreviousFiles does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
85
        }
86
87
        if ($this->shouldKeepPreviousValueUnchanged($entry, $entryValue)) {
88
            $entry->{$this->getAttributeName()} = $this->updatedPreviousFiles ?? $this->getEntryOriginalValue($entry);
89
90
            return $entry;
91
        }
92
93
        if ($this->shouldUploadFiles($entryValue)) {
94
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, $entryValue);
95
        }
96
97
        return $entry;
98
    }
99
100
    protected function getFilesFromEntry(Model $entry)
101
    {
102
        return $entry->getAttribute($this->getAttributeName());
103
    }
104
105
    protected function getEntryAttributeValue(Model $entry)
106
    {
107
        return $entry->{$this->getAttributeName()};
108
    }
109
110
    protected function getEntryOriginalValue(Model $entry)
111
    {
112
        return $entry->getOriginal($this->getAttributeName());
113
    }
114
115
    protected function shouldUploadFiles($entryValue): bool
116
    {
117
        return true;
118
    }
119
120
    protected function shouldKeepPreviousValueUnchanged(Model $entry, $entryValue): bool
121
    {
122
        return $entry->exists && ($entryValue === null || $entryValue === [null]);
123
    }
124
125
    protected function hasDeletedFiles($entryValue): bool
126
    {
127
        return $entryValue === false || $entryValue === null || $entryValue === [null];
128
    }
129
130
    protected function processRepeatableUploads(Model $entry, Collection $values): Collection
131
    {
132
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
133
            $uploadedValues = $uploader->uploadRepeatableFiles($values->pluck($uploader->getAttributeName())->toArray(), $this->getPreviousRepeatableValues($entry, $uploader));
134
135
            $values = $values->map(function ($item, $key) use ($uploadedValues, $uploader) {
136
                $item[$uploader->getAttributeName()] = $uploadedValues[$key] ?? null;
137
138
                return $item;
139
            });
140
        }
141
142
        return $values;
143
    }
144
145
    private function retrieveRepeatableFiles(Model $entry): Model
146
    {
147
        if ($this->isRelationship) {
148
            return $this->retrieveRepeatableRelationFiles($entry);
149
        }
150
151
        $repeatableUploaders = app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName());
152
153
        $values = $entry->{$this->getRepeatableContainerName()};
154
        $values = is_string($values) ? json_decode($values, true) : $values;
155
        $values = array_map(function ($item) use ($repeatableUploaders) {
156
            foreach ($repeatableUploaders as $upload) {
157
                $item[$upload->getAttributeName()] = $this->getValuesWithPathStripped($item, $upload);
158
            }
159
160
            return $item;
161
        }, $values);
162
163
        $entry->{$this->getRepeatableContainerName()} = $values;
164
165
        return $entry;
166
    }
167
168
    private function retrieveRepeatableRelationFiles(Model $entry)
169
    {
170
        switch($this->getRepeatableRelationType()) {
171
            case 'BelongsToMany':
172
            case 'MorphToMany':
173
                $pivotClass = app('crud')->getModel()->{$this->getUploaderSubfield()['baseEntity']}()->getPivotClass();
174
                $pivotFieldName = 'pivot_'.$this->getAttributeName();
175
                $connectedEntry = new $pivotClass([$this->getAttributeName() => $entry->$pivotFieldName]);
176
                $entry->{$pivotFieldName} = $this->retrieveFiles($connectedEntry)->{$this->getAttributeName()};
0 ignored issues
show
Bug introduced by
It seems like retrieveFiles() 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

176
                $entry->{$pivotFieldName} = $this->/** @scrutinizer ignore-call */ retrieveFiles($connectedEntry)->{$this->getAttributeName()};
Loading history...
177
178
                break;
179
            default:
180
                $entry = $this->retrieveFiles($entry);
181
        }
182
183
        return $entry;
184
    }
185
186
    private function getRepeatableRelationType()
187
    {
188
        return $this->getUploaderField()->getAttributes()['relation_type'];
189
    }
190
191
    private function getUploaderField()
192
    {
193
        return app('crud')->field($this->getRepeatableContainerName());
194
    }
195
196
    private function getUploaderSubfield()
197
    {
198
        return collect($this->getUploaderFieldSubfields())->where('name', '===', $this->getName())->first();
0 ignored issues
show
Bug introduced by
It seems like getName() 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

198
        return collect($this->getUploaderFieldSubfields())->where('name', '===', $this->/** @scrutinizer ignore-call */ getName())->first();
Loading history...
199
    }
200
201
    private function getUploaderFieldSubfields()
202
    {
203
        return $this->getUploaderField()->getAttributes()['subfields'];
204
    }
205
206
    private function deleteRepeatableFiles(Model $entry): void
207
    {
208
        if ($this->isRelationship) {
209
            $this->deleteRelationshipFiles($entry);
210
211
            return;
212
        }
213
214
        $repeatableValues = collect($entry->{$this->getName()});
215
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $upload) {
216
            if (! $upload->shouldDeleteFiles()) {
217
                continue;
218
            }
219
            $values = $repeatableValues->pluck($upload->getName())->toArray();
220
            foreach ($values as $value) {
221
                if (! $value) {
222
                    continue;
223
                }
224
225
                if (is_array($value)) {
226
                    foreach ($value as $subvalue) {
227
                        Storage::disk($upload->getDisk())->delete($upload->getPath().$subvalue);
228
                    }
229
230
                    continue;
231
                }
232
233
                Storage::disk($upload->getDisk())->delete($upload->getPath().$value);
234
            }
235
        }
236
    }
237
    /*******************************
238
     * Helper methods
239
     *******************************/
240
241
    /**
242
     * Given two multidimensional arrays/collections, merge them recursively.
243
     */
244
    protected function mergeValuesRecursive(array|Collection $array1, array|Collection $array2): array|Collection
245
    {
246
        $merged = $array1;
247
        foreach ($array2 as $key => &$value) {
248
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
249
                $merged[$key] = $this->mergeValuesRecursive($merged[$key], $value);
250
            } else {
251
                $merged[$key] = $value;
252
            }
253
        }
254
255
        return $merged;
256
    }
257
258
    /**
259
     * Repeatable items send `_order_` parameter in the request.
260
     * This holds the order of the items in the repeatable container.
261
     */
262
    protected function getFileOrderFromRequest(): array
263
    {
264
        $items = CRUD::getRequest()->input('_order_'.$this->getRepeatableContainerName()) ?? [];
265
266
        array_walk($items, function (&$key, $value) {
267
            $requestValue = $key[$this->getName()] ?? null;
268
            $key = $this->handleMultipleFiles ? (is_string($requestValue) ? explode(',', $requestValue) : $requestValue) : $requestValue;
269
        });
270
271
        return $items;
272
    }
273
274
    private function getPreviousRepeatableValues(Model $entry, UploaderInterface $uploader): array
275
    {
276
        $previousValues = json_decode($entry->getOriginal($uploader->getRepeatableContainerName()), true);
0 ignored issues
show
Bug introduced by
It seems like $entry->getOriginal($upl...eatableContainerName()) can also be of type array; however, parameter $json of json_decode() does only seem to accept string, 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

276
        $previousValues = json_decode(/** @scrutinizer ignore-type */ $entry->getOriginal($uploader->getRepeatableContainerName()), true);
Loading history...
277
278
        if (! empty($previousValues)) {
279
            $previousValues = array_column($previousValues, $uploader->getName());
280
        }
281
282
        return $previousValues ?? [];
283
    }
284
285
    private function getValuesWithPathStripped(array|string|null $item, UploaderInterface $upload)
286
    {
287
        $uploadedValues = $item[$upload->getName()] ?? null;
288
        if (is_array($uploadedValues)) {
289
            return array_map(function ($value) use ($upload) {
290
                return Str::after($value, $upload->getPath());
291
            }, $uploadedValues);
292
        }
293
294
        return isset($uploadedValues) ? Str::after($uploadedValues, $upload->getPath()) : null;
295
    }
296
297
    private function deleteRelationshipFiles(Model $entry): void
298
    {
299
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
300
            $uploader->deleteRepeatableRelationFiles($entry);
301
        }
302
    }
303
304
    private function deleteRepeatableRelationFiles(Model $entry)
305
    {
306
        if (in_array($this->getRepeatableRelationType(), ['BelongsToMany', 'MorphToMany'])) {
307
            $pivotAttributes = $entry->getAttributes();
308
            $connectedPivot = $entry->pivotParent->{$this->getRepeatableContainerName()}->where(function ($item) use ($pivotAttributes) {
309
                $itemPivotAttributes = $item->pivot->only(array_keys($pivotAttributes));
310
311
                return $itemPivotAttributes === $pivotAttributes;
312
            })->first();
313
314
            if (! $connectedPivot) {
315
                return;
316
            }
317
318
            $files = $connectedPivot->getOriginal()['pivot_'.$this->getAttributeName()];
319
320
            if (! $files) {
321
                return;
322
            }
323
324
            if ($this->handleMultipleFiles && is_string($files)) {
325
                try {
326
                    $files = json_decode($files, true);
327
                } catch (\Exception) {
328
                    Log::error('Could not parse files for deletion pivot entry with key: '.$entry->getKey().' and uploader: '.$this->getName());
329
330
                    return;
331
                }
332
            }
333
334
            if (is_array($files)) {
335
                foreach ($files as $value) {
336
                    $value = Str::start($value, $this->getPath());
0 ignored issues
show
Bug introduced by
It seems like getPath() 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

336
                    $value = Str::start($value, $this->/** @scrutinizer ignore-call */ getPath());
Loading history...
337
                    Storage::disk($this->getDisk())->delete($value);
0 ignored issues
show
Bug introduced by
It seems like getDisk() 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

337
                    Storage::disk($this->/** @scrutinizer ignore-call */ getDisk())->delete($value);
Loading history...
338
                }
339
340
                return;
341
            }
342
343
            $value = Str::start($files, $this->getPath());
344
            Storage::disk($this->getDisk())->delete($value);
345
346
            return;
347
        }
348
349
        $this->deleteFiles($entry);
0 ignored issues
show
Bug introduced by
It seems like deleteFiles() 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

349
        $this->/** @scrutinizer ignore-call */ 
350
               deleteFiles($entry);
Loading history...
350
    }
351
}
352