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 — handle-uploads-inside-relation... ( 89fabe...1ba771 )
by Pedro
15:30
created

HandleRepeatableUploads::uploadRepeatableFiles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 3
dl 0
loc 2
rs 10
c 0
b 0
f 0
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\Storage;
10
use Illuminate\Support\Str;
11
12
trait HandleRepeatableUploads
13
{
14
    public bool $handleRepeatableFiles = false;
15
16
    public ?string $repeatableContainerName = null;
17
18
    /*******************************
19
     * Setters - fluently configure the uploader
20
     *******************************/
21
    public function repeats(string $repeatableContainerName): self
22
    {
23
        $this->handleRepeatableFiles = true;
24
25
        $this->repeatableContainerName = $repeatableContainerName;
26
27
        return $this;
28
    }
29
30
    /*******************************
31
     * Getters
32
     *******************************/
33
    public function getRepeatableContainerName(): ?string
34
    {
35
        return $this->repeatableContainerName;
36
    }
37
38
    /*******************************
39
     * Default implementation methods
40
     *******************************/
41
    protected function uploadRepeatableFiles($values, $previousValues, $entry = null)
42
    {
43
    }
44
45
    protected function handleRepeatableFiles(Model $entry): Model
46
    {
47
        $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

47
        $values = collect(CRUD::/** @scrutinizer ignore-call */ getRequest()->get($this->getRepeatableContainerName()));
Loading history...
48
        $files = collect(CRUD::getRequest()->file($this->getRepeatableContainerName()));
49
        $value = $this->mergeValuesRecursive($values, $files);
50
51
        if ($this->isRelationship) {
52
            return $this->uploadRelationshipFiles($entry, $value);
53
        }
54
55
        $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

55
        $entry->{$this->getRepeatableContainerName()} = json_encode($this->processRepeatableUploads($entry, /** @scrutinizer ignore-type */ $value));
Loading history...
56
57
        return $entry;
58
    }
59
60
    private function uploadRelationshipFiles(Model $entry, mixed $value): Model
61
    {
62
        $modelCount = CRUD::get('uploaded_'.$this->getRepeatableContainerName().'_count');
0 ignored issues
show
Bug introduced by
The method get() 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

62
        /** @scrutinizer ignore-call */ 
63
        $modelCount = CRUD::get('uploaded_'.$this->getRepeatableContainerName().'_count');
Loading history...
63
        $value = $value->slice($modelCount, 1)->toArray();
64
65
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
66
            if (array_key_exists($modelCount, $value) && array_key_exists($uploader->getAttributeName(), $value[$modelCount])) {
67
                $entry->{$uploader->getAttributeName()} = $uploader->uploadFiles($entry, $value[$modelCount][$uploader->getAttributeName()]);
68
            }
69
        }
70
71
        return $entry;
72
    }
73
74
    protected function processRepeatableUploads(Model $entry, Collection $values): Collection
75
    {
76
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $uploader) {
77
            $uploadedValues = $uploader->uploadRepeatableFiles($values->pluck($uploader->getAttributeName())->toArray(), $this->getPreviousRepeatableValues($entry, $uploader));
78
79
            $values = $values->map(function ($item, $key) use ($uploadedValues, $uploader) {
80
                $item[$uploader->getAttributeName()] = $uploadedValues[$key] ?? null;
81
82
                return $item;
83
            });
84
        }
85
86
        return $values;
87
    }
88
89
    private function retrieveRepeatableFiles(Model $entry): Model
90
    {
91
        if ($this->isRelationship) {
92
            return $this->retrieveRepeatableRelationFiles($entry);
93
        }
94
95
        $repeatableUploaders = app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName());
96
97
        $values = $entry->{$this->getRepeatableContainerName()};
98
        $values = is_string($values) ? json_decode($values, true) : $values;
99
        $values = array_map(function ($item) use ($repeatableUploaders) {
100
            foreach ($repeatableUploaders as $upload) {
101
                $item[$upload->getAttributeName()] = $this->getValuesWithPathStripped($item, $upload);
102
            }
103
104
            return $item;
105
        }, $values);
106
107
        $entry->{$this->getRepeatableContainerName()} = $values;
108
109
        return $entry;
110
    }
111
112
    private function retrieveRepeatableRelationFiles(Model $entry)
113
    {
114
        switch($this->getRepeatableRelationType()) {
115
            case 'BelongsToMany':
116
            case 'MorphToMany':
117
                $pivotClass = app('crud')->getModel()->{$this->getUploaderSubfield()['baseEntity']}()->getPivotClass();
118
                $pivotFieldName = 'pivot_'.$this->getAttributeName();
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

118
                $pivotFieldName = 'pivot_'.$this->/** @scrutinizer ignore-call */ getAttributeName();
Loading history...
119
                $connectedEntry = new $pivotClass([$this->getAttributeName() => $entry->$pivotFieldName]);
120
                $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

120
                $entry->{$pivotFieldName} = $this->/** @scrutinizer ignore-call */ retrieveFiles($connectedEntry)->{$this->getAttributeName()};
Loading history...
121
122
                break;
123
            default:
124
                $entry = $this->retrieveFiles($entry);
125
        }
126
127
        return $entry;
128
    }
129
130
    private function getRepeatableRelationType()
131
    {
132
        return $this->getUploaderField()->getAttributes()['relation_type'];
133
    }
134
135
    private function getUploaderField()
136
    {
137
        return app('crud')->field($this->getRepeatableContainerName());
138
    }
139
140
    private function getUploaderSubfield()
141
    {
142
        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

142
        return collect($this->getUploaderFieldSubfields())->where('name', '===', $this->/** @scrutinizer ignore-call */ getName())->first();
Loading history...
143
    }
144
145
    private function getUploaderFieldSubfields()
146
    {
147
        return $this->getUploaderField()->getAttributes()['subfields'];
148
    }
149
150
    private function deleteRepeatableFiles(Model $entry): void
151
    {
152
        if ($this->isRelationship) {
153
            $this->deleteRelationshipFiles($entry);
154
            return;
155
        }
156
157
        $repeatableValues = collect($entry->{$this->getName()});
158
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $upload) {
159
            if (! $upload->shouldDeleteFiles()) {
160
                continue;
161
            }
162
            $values = $repeatableValues->pluck($upload->getName())->toArray();
163
            foreach ($values as $value) {
164
                if (! $value) {
165
                    continue;
166
                }
167
168
                if (is_array($value)) {
169
                    foreach ($value as $subvalue) {
170
                        Storage::disk($upload->getDisk())->delete($upload->getPath().$subvalue);
171
                    }
172
173
                    continue;
174
                }
175
176
                Storage::disk($upload->getDisk())->delete($upload->getPath().$value);
177
            }
178
        }
179
    }
180
    /*******************************
181
     * Helper methods
182
     *******************************/
183
184
    /**
185
     * Given two multidimensional arrays/collections, merge them recursively.
186
     */
187
    protected function mergeValuesRecursive(array|Collection $array1, array|Collection $array2): array|Collection
188
    {
189
        $merged = $array1;
190
        foreach ($array2 as $key => &$value) {
191
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
192
                $merged[$key] = $this->mergeValuesRecursive($merged[$key], $value);
193
            } else {
194
                $merged[$key] = $value;
195
            }
196
        }
197
198
        return $merged;
199
    }
200
201
    /**
202
     * Repeatable items send `_order_` parameter in the request.
203
     * This holds the order of the items in the repeatable container.
204
     */
205
    protected function getFileOrderFromRequest(): array
206
    {
207
        $items = CRUD::getRequest()->input('_order_'.$this->getRepeatableContainerName()) ?? [];
208
209
        array_walk($items, function (&$key, $value) {
210
            $requestValue = $key[$this->getName()] ?? null;
211
            $key = $this->handleMultipleFiles ? (is_string($requestValue) ? explode(',', $requestValue) : $requestValue) : $requestValue;
212
        });
213
214
        return $items;
215
    }
216
217
    private function getPreviousRepeatableValues(Model $entry, UploaderInterface $uploader): array
218
    {
219
        $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

219
        $previousValues = json_decode(/** @scrutinizer ignore-type */ $entry->getOriginal($uploader->getRepeatableContainerName()), true);
Loading history...
220
221
        if (! empty($previousValues)) {
222
            $previousValues = array_column($previousValues, $uploader->getName());
223
        }
224
225
        return $previousValues ?? [];
226
    }
227
228
    private function getValuesWithPathStripped(array|string|null $item, UploaderInterface $upload)
229
    {
230
        $uploadedValues = $item[$upload->getName()] ?? null;
231
        if (is_array($uploadedValues)) {
232
            return array_map(function ($value) use ($upload) {
233
                return Str::after($value, $upload->getPath());
234
            }, $uploadedValues);
235
        }
236
237
        return isset($uploadedValues) ? Str::after($uploadedValues, $upload->getPath()) : null;
238
    }
239
240
    private function deleteRelationshipFiles(Model $entry) : void
241
    {
242
        if (in_array($this->getRepeatableRelationType(), ['BelongsToMany', 'MorphToMany'])) {
243
            $pivotAttributes = $entry->getAttributes();
244
            $connectedPivot = $entry->pivotParent->{$this->getRepeatableContainerName()}->where(function ($item) use ($pivotAttributes) {
245
                $itemPivotAttributes = $item->pivot->only(array_keys($pivotAttributes));
246
247
                return $itemPivotAttributes === $pivotAttributes;
248
            })->first();
249
250
            if (! $connectedPivot) {
251
                return;
252
            }
253
254
            $files = $connectedPivot->getOriginal()['pivot_'.$this->getAttributeName()];
255
256
            if (! $files) {
257
                return;
258
            }
259
260
            if (is_array($files)) {
261
                foreach ($files as $value) {
262
                    $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

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

263
                    Storage::disk($this->/** @scrutinizer ignore-call */ getDisk())->delete($value);
Loading history...
264
                }
265
266
                return;
267
            }
268
269
            $value = Str::start($files, $this->getPath());
270
            Storage::disk($this->getDisk())->delete($value);
271
272
            return;
273
        }
274
275
        $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

275
        $this->/** @scrutinizer ignore-call */ 
276
               deleteFiles($entry);
Loading history...
276
    }
277
}
278