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

Passed
Push — fix-uploaders ( a7ecbc...1c3162 )
by Pedro
12:45
created

HandleRepeatableUploads::deletePivotFiles()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 22
rs 9.8333
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\Database\Eloquent\Relations\Pivot;
9
use Illuminate\Support\Collection;
10
use Illuminate\Support\Facades\Log;
11
use Illuminate\Support\Facades\Storage;
12
use Illuminate\Support\Str;
13
14
/**
15
 * @codeCoverageIgnore
16
 */
17
trait HandleRepeatableUploads
18
{
19
    public bool $handleRepeatableFiles = false;
20
21
    public null|string $repeatableContainerName = null;
22
23
    /*******************************
24
     * Setters - fluently configure the uploader
25
     *******************************/
26
    public function repeats(string $repeatableContainerName): self
27
    {
28
        $this->handleRepeatableFiles = true;
29
30
        $this->repeatableContainerName = $repeatableContainerName;
31
32
        return $this;
33
    }
34
35
    /*******************************
36
     * Getters
37
     *******************************/
38
    public function getRepeatableContainerName(): null|string
39
    {
40
        return $this->repeatableContainerName;
41
    }
42
43
    /*******************************
44
     * Default implementation methods
45
     *******************************/
46
    protected function uploadRepeatableFiles($values, $previousValues, $entry = null)
47
    {
48
    }
49
50
    protected function handleRepeatableFiles(Model $entry): Model
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
55
        $value = $this->mergeValuesRecursive($values, $files);
56
57
        if ($this->isRelationship()) {
0 ignored issues
show
Bug introduced by
It seems like isRelationship() 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

57
        if ($this->/** @scrutinizer ignore-call */ isRelationship()) {
Loading history...
58
            if($value->isEmpty()) {
59
                return $entry;
60
            }
61
            return $this->processRelationshipRepeatableUploaders($entry);
62
        }
63
64
        $processedEntryValues = $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

64
        $processedEntryValues = $this->processRepeatableUploads($entry, /** @scrutinizer ignore-type */ $value);
Loading history...
65
66
        if ($this->isFake()) {
0 ignored issues
show
Bug introduced by
It seems like isFake() 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

66
        if ($this->/** @scrutinizer ignore-call */ isFake()) {
Loading history...
67
            $fakeValues = $entry->{$this->getFakeAttribute()} ?? [];
0 ignored issues
show
Bug introduced by
It seems like getFakeAttribute() 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

67
            $fakeValues = $entry->{$this->/** @scrutinizer ignore-call */ getFakeAttribute()} ?? [];
Loading history...
68
69
            if (is_string($fakeValues)) {
70
                $fakeValues = json_decode($fakeValues, true);
71
            }
72
73
            $fakeValues[$this->getRepeatableContainerName()] = empty($processedEntryValues)
74
                                                        ? null
75
                                                        : (isset($entry->getCasts()[$this->getFakeAttribute()])
76
                                                            ? $processedEntryValues
77
                                                            : json_encode($processedEntryValues));
78
79
            $entry->{$this->getFakeAttribute()} = isset($entry->getCasts()[$this->getFakeAttribute()])
80
                                                            ? $fakeValues
81
                                                            : json_encode($fakeValues);
82
83
            return $entry;
84
        }
85
86
        $entry->{$this->getRepeatableContainerName()} = empty($processedEntryValues)
87
                                                        ? null
88
                                                        : (isset($entry->getCasts()[$this->getRepeatableContainerName()])
89
                                                            ? $processedEntryValues
90
                                                            : json_encode($processedEntryValues));
91
92
        return $entry;
93
    }
94
95
    private function processRelationshipRepeatableUploaders(Model $entry)
96
    {
97
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
98
            $entry = $uploader->uploadRelationshipFiles($entry);
99
        }
100
101
        return $entry;
102
    }
103
104
    protected function uploadRelationshipFiles(Model $entry): Model
105
    {
106
        $entryValue = $this->getFilesFromEntry($entry);
107
108
        if ($this->handleMultipleFiles && is_string($entryValue)) {
109
            try {
110
                $entryValue = json_decode($entryValue, true);
111
            } catch (\Exception) {
112
                return $entry;
113
            }
114
        }
115
116
        if ($this->hasDeletedFiles($entryValue)) {
117
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, false);
0 ignored issues
show
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

117
            /** @scrutinizer ignore-call */ 
118
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, false);
Loading history...
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

117
            $entry->{$this->/** @scrutinizer ignore-call */ getAttributeName()} = $this->uploadFiles($entry, false);
Loading history...
118
            $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...
119
        }
120
121
        if ($this->shouldKeepPreviousValueUnchanged($entry, $entryValue)) {
0 ignored issues
show
Bug introduced by
It seems like shouldKeepPreviousValueUnchanged() 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

121
        if ($this->/** @scrutinizer ignore-call */ shouldKeepPreviousValueUnchanged($entry, $entryValue)) {
Loading history...
122
            $entry->{$this->getAttributeName()} = $this->updatedPreviousFiles ?? $this->getEntryOriginalValue($entry);
123
124
            return $entry;
125
        }
126
127
        if ($this->shouldUploadFiles($entryValue)) {
128
            $entry->{$this->getAttributeName()} = $this->uploadFiles($entry, $entryValue);
129
        }
130
131
        return $entry;
132
    }
133
134
    protected function getFilesFromEntry(Model $entry)
135
    {
136
        return $entry->getAttribute($this->getAttributeName());
137
    }
138
139
    protected function getEntryAttributeValue(Model $entry)
140
    {
141
        return $entry->{$this->getAttributeName()};
142
    }
143
144
    protected function getEntryOriginalValue(Model $entry)
145
    {
146
        return $entry->getOriginal($this->getAttributeName());
147
    }
148
149
    protected function shouldUploadFiles($entryValue): bool
150
    {
151
        return true;
152
    }
153
154
    protected function hasDeletedFiles($entryValue): bool
155
    {
156
        return $entryValue === false || $entryValue === null || $entryValue === [null];
157
    }
158
159
    protected function processRepeatableUploads(Model $entry, Collection $values): array
160
    {
161
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
162
            $uploadedValues = $uploader->uploadRepeatableFiles($values->pluck($uploader->getAttributeName())->toArray(), $this->getPreviousRepeatableValues($entry, $uploader));
163
164
            $values = $values->map(function ($item, $key) use ($uploadedValues, $uploader) {
165
                $item[$uploader->getAttributeName()] = $uploadedValues[$key] ?? null;
166
167
                return $item;
168
            });
169
        }
170
171
        return $values->toArray();
172
    }
173
174
    private function retrieveRepeatableFiles(Model $entry): Model
175
    {
176
        if ($this->isRelationship) {
177
            return $this->retrieveRepeatableRelationFiles($entry);
178
        }
179
180
        $repeatableUploaders = app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName());
181
182
        if ($this->attachedToFakeField) {
183
            $values = $entry->{$this->attachedToFakeField};
184
185
            $values = is_string($values) ? json_decode($values, true) : $values;
186
187
            $values[$this->getAttributeName()] = isset($values[$this->getAttributeName()]) ? $this->getValueWithoutPath($values[$this->getAttributeName()]) : null;
0 ignored issues
show
Bug introduced by
It seems like getValueWithoutPath() 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

187
            $values[$this->getAttributeName()] = isset($values[$this->getAttributeName()]) ? $this->/** @scrutinizer ignore-call */ getValueWithoutPath($values[$this->getAttributeName()]) : null;
Loading history...
188
            $entry->{$this->attachedToFakeField} = isset($entry->getCasts()[$this->attachedToFakeField]) ? $values : json_encode($values);
189
190
            return $entry;
191
        }
192
193
        $values = $entry->{$this->getRepeatableContainerName()};
194
        $values = is_string($values) ? json_decode($values, true) : $values;
195
        $values = array_map(function ($item) use ($repeatableUploaders) {
196
            foreach ($repeatableUploaders as $upload) {
197
                $item[$upload->getAttributeName()] = $this->getValuesWithPathStripped($item, $upload);
198
            }
199
200
            return $item;
201
        }, $values ?? []);
202
203
        $entry->{$this->getRepeatableContainerName()} = $values;
204
205
        return $entry;
206
    }
207
208
    private function retrieveRepeatableRelationFiles(Model $entry)
209
    {
210
        switch($this->getRepeatableRelationType()) {
211
            case 'BelongsToMany':
212
            case 'MorphToMany':
213
                $pivotClass = app('crud')->getModel()->{$this->getUploaderSubfield()['baseEntity']}()->getPivotClass();
214
                $pivotFieldName = 'pivot_'.$this->getAttributeName();
215
                $connectedEntry = new $pivotClass([$this->getAttributeName() => $entry->$pivotFieldName]);
216
                $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

216
                $entry->{$pivotFieldName} = $this->/** @scrutinizer ignore-call */ retrieveFiles($connectedEntry)->{$this->getAttributeName()};
Loading history...
217
218
                break;
219
            default:
220
                $entry = $this->retrieveFiles($entry);
221
        }
222
223
        return $entry;
224
    }
225
226
    private function getRepeatableRelationType()
227
    {
228
        return $this->getUploaderField()->getAttributes()['relation_type'];
229
    }
230
231
    private function getUploaderField()
232
    {
233
        return app('crud')->field($this->getRepeatableContainerName());
234
    }
235
236
    private function getUploaderSubfield()
237
    {
238
        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

238
        return collect($this->getUploaderFieldSubfields())->where('name', '===', $this->/** @scrutinizer ignore-call */ getName())->first();
Loading history...
239
    }
240
241
    private function getUploaderFieldSubfields()
242
    {
243
        return $this->getUploaderField()->getAttributes()['subfields'];
244
    }
245
246
    private function deleteRepeatableFiles(Model $entry): void
247
    {
248
        if ($this->isRelationship) {
249
            $this->deleteRelationshipFiles($entry);
250
251
            return;
252
        }
253
254
        if ($this->attachedToFakeField) {
255
            $repeatableValues = $entry->{$this->attachedToFakeField}[$this->getRepeatableContainerName()] ?? null;
256
            $repeatableValues = is_string($repeatableValues) ? json_decode($repeatableValues, true) : $repeatableValues;
257
            $repeatableValues = collect($repeatableValues);
258
        }
259
260
        $repeatableValues ??= collect($entry->{$this->getRepeatableContainerName()});
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $repeatableValues does not seem to be defined for all execution paths leading up to this point.
Loading history...
261
262
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $upload) {
263
            if (! $upload->shouldDeleteFiles()) {
264
                continue;
265
            }
266
            $values = $repeatableValues->pluck($upload->getName())->toArray();
267
            foreach ($values as $value) {
268
                if (! $value) {
269
                    continue;
270
                }
271
272
                if (is_array($value)) {
273
                    foreach ($value as $subvalue) {
274
                        Storage::disk($upload->getDisk())->delete($upload->getPath().$subvalue);
275
                    }
276
277
                    continue;
278
                }
279
280
                Storage::disk($upload->getDisk())->delete($upload->getPath().$value);
281
            }
282
        }
283
    }
284
    /*******************************
285
     * Helper methods
286
     *******************************/
287
288
    /**
289
     * Given two multidimensional arrays/collections, merge them recursively.
290
     */
291
    protected function mergeValuesRecursive(array|Collection $array1, array|Collection $array2): array|Collection
292
    {
293
        $merged = $array1;
294
        foreach ($array2 as $key => &$value) {
295
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
296
                $merged[$key] = $this->mergeValuesRecursive($merged[$key], $value);
297
            } else {
298
                $merged[$key] = $value;
299
            }
300
        }
301
302
        return $merged;
303
    }
304
305
    /**
306
     * Repeatable items send `_order_` parameter in the request.
307
     * This holds the order of the items in the repeatable container.
308
     */
309
    protected function getFileOrderFromRequest(): array
310
    {
311
        $items = CRUD::getRequest()->input('_order_'.$this->getRepeatableContainerName()) ?? [];
312
313
        array_walk($items, function (&$key, $value) {
314
            $requestValue = $key[$this->getName()] ?? null;
315
            $key = $this->handleMultipleFiles ? (is_string($requestValue) ? explode(',', $requestValue) : $requestValue) : $requestValue;
316
        });
317
318
        return $items;
319
    }
320
321
    private function getPreviousRepeatableValues(Model $entry, UploaderInterface $uploader): array
322
    {
323
        $previousValues = $entry->getOriginal($uploader->getRepeatableContainerName());
324
325
        if (! is_array($previousValues)) {
326
            $previousValues = json_decode($previousValues, true);
327
        }
328
329
        if (! empty($previousValues)) {
330
            $previousValues = array_column($previousValues, $uploader->getName());
331
        }
332
333
        return $previousValues ?? [];
334
    }
335
336
    private function getValuesWithPathStripped(array|string|null $item, UploaderInterface $uploader)
337
    {
338
        $uploadedValues = $item[$uploader->getName()] ?? null;
339
        if (is_array($uploadedValues)) {
340
            return array_map(function ($value) use ($uploader) {
341
                return $uploader->getValueWithoutPath($value);
342
            }, $uploadedValues);
343
        }
344
345
        return isset($uploadedValues) ? $uploader->getValueWithoutPath($uploadedValues) : null;
346
    }
347
348
    private function deleteRelationshipFiles(Model $entry): void
349
    {
350
        if (! is_a($entry, Pivot::class, true) &&
351
            ! $entry->relationLoaded($this->getRepeatableContainerName()) && 
352
            method_exists($entry, $this->getRepeatableContainerName())
0 ignored issues
show
Bug introduced by
It seems like $this->getRepeatableContainerName() can also be of type null; however, parameter $method of method_exists() 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

352
            method_exists($entry, /** @scrutinizer ignore-type */ $this->getRepeatableContainerName())
Loading history...
353
            ) { 
354
            $entry->loadMissing($this->getRepeatableContainerName());
355
        }
356
357
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
358
            if ($uploader->shouldDeleteFiles()) {
359
                $uploader->deleteRepeatableRelationFiles($entry);
360
            }
361
        }
362
    }
363
364
    protected function deleteRepeatableRelationFiles(Model $entry)
365
    {
366
        match ($this->getRepeatableRelationType()) {
367
            'BelongsToMany', 'MorphToMany' => $this->deletePivotFiles($entry),
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->deletePivotFiles($entry) targeting Backpack\CRUD\app\Librar...ads::deletePivotFiles() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
368
            default => $this->deleteRelatedFiles($entry),
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->deleteRelatedFiles($entry) targeting Backpack\CRUD\app\Librar...s::deleteRelatedFiles() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
369
        };
370
    }
371
372
    private function deleteRelatedFiles(Model $entry)
373
    {
374
        if (get_class($entry) === get_class(app('crud')->model)) {
0 ignored issues
show
Bug introduced by
app('crud')->model of type string is incompatible with the type object expected by parameter $object of get_class(). ( Ignorable by Annotation )

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

374
        if (get_class($entry) === get_class(/** @scrutinizer ignore-type */ app('crud')->model)) {
Loading history...
375
            $relatedEntries = $entry->{$this->getRepeatableContainerName()} ?? [];
376
        }
377
        
378
        $relatedEntries ??= [$entry];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $relatedEntries does not seem to be defined for all execution paths leading up to this point.
Loading history...
379
380
        foreach ($relatedEntries as $relatedEntry) {
381
            $this->deleteFiles($relatedEntry);
0 ignored issues
show
Bug introduced by
The method deleteFiles() does not exist on Backpack\CRUD\app\Librar...HandleRepeatableUploads. Did you maybe mean deletePivotFiles()? ( Ignorable by Annotation )

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

381
            $this->/** @scrutinizer ignore-call */ 
382
                   deleteFiles($relatedEntry);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
382
        }
383
    }
384
385
    private function deletePivotFiles(Pivot|Model $entry)
386
    {
387
        if (! is_a($entry, Pivot::class, true)) {
388
            $pivots = $entry->{$this->getRepeatableContainerName()};
389
            foreach ($pivots as $pivot) {
390
                $this->deletePivotModelFiles($pivot);
391
            }
392
            return;
393
        }
394
395
        $pivotAttributes = $entry->getAttributes();
396
        $connectedPivot = $entry->pivotParent->{$this->getRepeatableContainerName()}->where(function ($item) use ($pivotAttributes) {
397
            $itemPivotAttributes = $item->pivot->only(array_keys($pivotAttributes));
398
399
            return $itemPivotAttributes === $pivotAttributes;
400
        })->first();
401
402
        if (! $connectedPivot) {
403
            return;
404
        }
405
406
        $this->deletePivotModelFiles($connectedPivot);
407
    }
408
409
    private function deletePivotModelFiles(Pivot|Model $entry)
410
    {
411
        $files = $entry->getOriginal()['pivot_'.$this->getAttributeName()];
412
413
        if (! $files) {
414
            return;
415
        }
416
417
        if ($this->handleMultipleFiles && is_string($files)) {
418
            try {
419
                $files = json_decode($files, true);
420
            } catch (\Exception) {
421
                Log::error('Could not parse files for deletion pivot entry with key: '.$entry->getKey().' and uploader: '.$this->getName());
422
423
                return;
424
            }
425
        }
426
427
        if (is_array($files)) {
428
            foreach ($files as $value) {
429
                $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

429
                $value = Str::start($value, $this->/** @scrutinizer ignore-call */ getPath());
Loading history...
430
                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

430
                Storage::disk($this->/** @scrutinizer ignore-call */ getDisk())->delete($value);
Loading history...
431
            }
432
433
            return;
434
        }
435
436
        $value = Str::start($files, $this->getPath());
437
        Storage::disk($this->getDisk())->delete($value);
438
    }
439
}
440