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
Pull Request — main (#5233)
by Cristian
35:41 queued 20:44
created

getRepeatableContainerName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
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)
0 ignored issues
show
Unused Code introduced by
The parameter $entry is not used and could be removed. ( Ignorable by Annotation )

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

41
    protected function uploadRepeatableFiles($values, $previousValues, /** @scrutinizer ignore-unused */ $entry = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $previousValues is not used and could be removed. ( Ignorable by Annotation )

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

41
    protected function uploadRepeatableFiles($values, /** @scrutinizer ignore-unused */ $previousValues, $entry = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $values is not used and could be removed. ( Ignorable by Annotation )

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

41
    protected function uploadRepeatableFiles(/** @scrutinizer ignore-unused */ $values, $previousValues, $entry = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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) && isset($value[$modelCount][$uploader->getName()])) {
67
                $entry->{$uploader->getName()} = $uploader->uploadFiles($entry, $value[$modelCount][$uploader->getName()]);
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->getName())->toArray(), $this->getPreviousRepeatableValues($entry, $uploader));
78
79
            $values = $values->map(function ($item, $key) use ($uploadedValues, $uploader) {
80
                $item[$uploader->getName()] = $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->retrieveFiles($entry);
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

92
            return $this->/** @scrutinizer ignore-call */ retrieveFiles($entry);
Loading history...
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->getName()] = $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 deleteRepeatableFiles(Model $entry): void
113
    {
114
        if ($this->isRelationship) {
115
            $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

115
            $this->/** @scrutinizer ignore-call */ 
116
                   deleteFiles($entry);
Loading history...
116
117
            return;
118
        }
119
120
        $repeatableValues = collect($entry->{$this->getName()});
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

120
        $repeatableValues = collect($entry->{$this->/** @scrutinizer ignore-call */ getName()});
Loading history...
121
        foreach (app('UploadersRepository')->getRepeatableUploadersFor($this->getRepeatableContainerName()) as $upload) {
122
            if (! $upload->shouldDeleteFiles()) {
123
                continue;
124
            }
125
            $values = $repeatableValues->pluck($upload->getName())->toArray();
126
            foreach ($values as $value) {
127
                if (! $value) {
128
                    continue;
129
                }
130
131
                if (is_array($value)) {
132
                    foreach ($value as $subvalue) {
133
                        Storage::disk($upload->getDisk())->delete($upload->getPath().$subvalue);
134
                    }
135
136
                    continue;
137
                }
138
139
                Storage::disk($upload->getDisk())->delete($upload->getPath().$value);
140
            }
141
        }
142
    }
143
    /*******************************
144
     * Helper methods
145
     *******************************/
146
147
    /**
148
     * Given two multidimensional arrays/collections, merge them recursively.
149
     */
150
    protected function mergeValuesRecursive(array|Collection $array1, array|Collection $array2): array|Collection
151
    {
152
        $merged = $array1;
153
        foreach ($array2 as $key => &$value) {
154
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
155
                $merged[$key] = $this->mergeValuesRecursive($merged[$key], $value);
156
            } else {
157
                $merged[$key] = $value;
158
            }
159
        }
160
161
        return $merged;
162
    }
163
164
    /**
165
     * Repeatable items send `_order_` parameter in the request.
166
     * This holds the order of the items in the repeatable container.
167
     */
168
    protected function getFileOrderFromRequest(): array
169
    {
170
        $items = CRUD::getRequest()->input('_order_'.$this->getRepeatableContainerName()) ?? [];
171
172
        array_walk($items, function (&$key, $value) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed. ( Ignorable by Annotation )

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

172
        array_walk($items, function (&$key, /** @scrutinizer ignore-unused */ $value) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
173
            $requestValue = $key[$this->getName()] ?? null;
174
            $key = $this->handleMultipleFiles ? (is_string($requestValue) ? explode(',', $requestValue) : $requestValue) : $requestValue;
175
        });
176
177
        return $items;
178
    }
179
180
    private function getPreviousRepeatableValues(Model $entry, UploaderInterface $uploader): array
181
    {
182
        $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

182
        $previousValues = json_decode(/** @scrutinizer ignore-type */ $entry->getOriginal($uploader->getRepeatableContainerName()), true);
Loading history...
183
184
        if (! empty($previousValues)) {
185
            $previousValues = array_column($previousValues, $uploader->getName());
186
        }
187
188
        return $previousValues ?? [];
189
    }
190
191
    private function getValuesWithPathStripped(array|string|null $item, UploaderInterface $upload)
192
    {
193
        $uploadedValues = $item[$upload->getName()] ?? null;
194
        if (is_array($uploadedValues)) {
195
            return array_map(function ($value) use ($upload) {
196
                return Str::after($value, $upload->getPath());
197
            }, $uploadedValues);
198
        }
199
200
        return isset($uploadedValues) ? Str::after($uploadedValues, $upload->getPath()) : null;
201
    }
202
}
203