Completed
Push — ft/states ( d9d02a...d4f7ca )
by Ben
45:58 queued 35:27
created

UploadMedia::sortFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 3
1
<?php
2
3
namespace Thinktomorrow\Chief\Media;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Http\UploadedFile;
7
use Thinktomorrow\AssetLibrary\Asset;
8
use Thinktomorrow\AssetLibrary\HasAsset;
9
use Thinktomorrow\AssetLibrary\Application\AddAsset;
10
use Thinktomorrow\AssetLibrary\Application\SortAssets;
11
use Thinktomorrow\AssetLibrary\Application\DetachAsset;
12
use Thinktomorrow\AssetLibrary\Application\ReplaceAsset;
13
use Thinktomorrow\AssetLibrary\Application\AssetUploader;
14
15
class UploadMedia
16
{
17
    /**
18
     * Upload from base64encoded files, usually
19
     * coming from slim upload component
20
     *
21
     * @param HasAsset $model
22
     * @param array $files_by_type
23
     * @param array $files_order_by_type
24
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
25
     */
26 86
    public function fromUploadComponent(HasAsset $model, array $files_by_type, array $files_order_by_type)
27
    {
28 86
        ini_set('memory_limit', '256M');
29 86
        $files_by_type = $this->sanitizeFilesParameter($files_by_type);
30 86
        $files_order_by_type = $this->sanitizeFilesOrderParameter($files_order_by_type);
31 86
        $this->validateParameters($files_by_type, $files_order_by_type);
32
33
        // When no files are uploaded, we still would like to sort our assets duh
34 86
        if (empty($files_by_type)) {
35 70
            foreach ($files_order_by_type as $type => $files) {
36 2
                app(SortAssets::class)->handle($model, $type, $files);
37
            }
38
39 70
            return;
40
        }
41
42 16
        foreach ($files_by_type as $type => $files_by_locale) {
43 16
            foreach ($files_by_locale as $locale => $files) {
44 16
                $this->validateFileUploads($files);
45
                
46 16
                $fileIdsCollection = $files_order_by_type[$type] ?? [];
47
48 16
                $this->addFiles($model, $type, $files, $fileIdsCollection, $locale);
49 16
                $this->replaceFiles($model, $files);
50 16
                $this->removeFiles($model, $files, $type, $locale);
51
            }
52 16
            app(SortAssets::class)->handle($model, $type, $fileIdsCollection ?? []);
53
        }
54 16
    }
55
56 16
    private function addFiles(HasAsset $model, string $type, array $files, array &$files_order, string $locale = null)
57
    {
58 16
        if (!$this->actionExists($files, 'new')) {
59 4
            return;
60
        }
61
62 14
        foreach ($files['new'] as $id => $file) {
63 14
            if (!$file) {
64
                continue;
65
            }
66
            
67 14
            $this->addFile($model, $type, $file, $files_order, $locale);
68
        }
69 14
    }
70
71
    /**
72
     * @param HasAsset $model
73
     * @param array $files
74
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
75
     */
76 16
    private function replaceFiles(HasAsset $model, array $files)
77
    {
78 16
        if (!$this->actionExists($files, 'replace')) {
79 15
            return;
80
        }
81
82 2
        foreach ($files['replace'] as $id => $file) {
83 2
            if (!$file) {
84
                continue;
85
            }
86
87 2
            $asset = AssetUploader::uploadFromBase64(json_decode($file)->output->image, json_decode($file)->output->name);
88 2
            app(ReplaceAsset::class)->handle($model, $id, $asset->id);
89
        }
90 2
    }
91
92
    /**
93
     * @param HasAsset $model
94
     * @param array $files
95
     */
96 16
    private function removeFiles(HasAsset $model, array $files, string $type, string $locale)
97
    {
98 16
        if (!$this->actionExists($files, 'delete')) {
99 14
            return;
100
        }
101
102 3
        foreach ($files['delete'] as $id => $file) {
103 3
            if (!$file) {
104
                continue;
105
            }
106 3
            app(DetachAsset::class)->detach($model, $file, $type, $locale);
107
        }
108 3
    }
109
110 16
    private function actionExists(array $files, string $action)
111
    {
112 16
        return (isset($files[$action]) && is_array($files[$action]) && !empty($files[$action]));
113
    }
114
115 14
    private function addFile(HasAsset $model, string $type, $file, array &$files_order, $locale = null)
116
    {
117 14
        if (isset(json_decode($file)->output)) {
118 8
            $image_name = json_decode($file)->output->name;
119 8
            $asset      = app(AddAsset::class)->add($model, json_decode($file)->output->image, $type, $locale, $this->sluggifyFilename($image_name));
0 ignored issues
show
Unused Code introduced by
The assignment to $asset is dead and can be removed.
Loading history...
120
        } else {
121 7
            if ($file instanceof UploadedFile) {
122 4
                $image_name = $file->getClientOriginalName();
123 4
                $asset      = app(AddAsset::class)->add($model, $file, $type, $locale, $this->sluggifyFilename($image_name));
124
125
                // New files are passed with their filename (instead of their id)
126
                // For new files we will replace the filename with the id.
127 4
                if (false !== ($key = array_search($image_name, $files_order))) {
128 4
                    $files_order[$key] = (string) $asset->id;
129
                }
130
            } else {
131 3
                $file       = Asset::findOrFail($file);
132 3
                $asset      = app(AddAsset::class)->add($model, $file, $type, $locale);
133
            }
134
        }
135 14
    }
136
137
    /**
138
     * @param $filename
139
     * @return string
140
     */
141 11
    private function sluggifyFilename($filename): string
142
    {
143 11
        $extension = substr($filename, strrpos($filename, '.') + 1);
144 11
        $filename  = substr($filename, 0, strrpos($filename, '.'));
145 11
        $filename  = Str::slug($filename) . '.' . $extension;
146
147 11
        return $filename;
148
    }
149
150
    /**
151
     * @param $files
152
     * @throws FileTooBigException
153
     */
154 16
    private function validateFileUploads($files): void
155
    {
156 16
        foreach ($files as $_files) {
157 16
            foreach ($_files as $file) {
158 16
                if ($file instanceof UploadedFile && !$file->isValid()) {
159
                    if ($file->getError() == UPLOAD_ERR_INI_SIZE) {
160
                        throw new FileTooBigException(
0 ignored issues
show
Bug introduced by
The type Thinktomorrow\Chief\Media\FileTooBigException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
161
                            'Cannot upload file because it exceeded the allowed upload_max_filesize: upload_max_filesize is smaller than post size. ' .
162
                            'upload_max_filesize: ' . (int)ini_get('upload_max_filesize') . 'MB, ' .
163 16
                            'post_max_size: ' . (int)(ini_get('post_max_size')) . 'MB'
164
                        );
165
                    }
166
                }
167
            }
168
        }
169 16
    }
170
171 86
    private function validateParameters(array $files_by_type, array $files_order_by_type)
0 ignored issues
show
Unused Code introduced by
The parameter $files_order_by_type 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

171
    private function validateParameters(array $files_by_type, /** @scrutinizer ignore-unused */ array $files_order_by_type)

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...
172
    {
173 86
        $actions = ['new', 'replace', 'delete'];
174 86
        foreach ($files_by_type as $type => $files) {
175 16
            foreach ($files as $locale => $_files) {
176 16
                if (!in_array($locale, config('translatable.locales'))) {
177
                    throw new \InvalidArgumentException('Corrupt file payload. key is expected to be a valid locale [' . implode(',', config('translatable.locales', [])). ']. Instead [' . $locale . '] is given.');
178
                }
179
180 16
                if (!is_array($_files)) {
181
                    throw new \InvalidArgumentException('A valid files entry should be an array of files, key with either [new, replace or delete]. Instead a ' . gettype($_files) . ' is given.');
182
                }
183
184 16
                foreach ($_files as $action => $file) {
185 16
                    if (!in_array($action, $actions)) {
186 16
                        throw new \InvalidArgumentException('A valid files entry should have a key of either ['.implode(',', $actions).']. Instead ' . $action . ' is given.');
187
                    }
188
                }
189
            }
190
        }
191 86
    }
192
193 86
    private function sanitizeFilesParameter(array $files_by_type): array
194
    {
195 86
        $defaultLocale = config('app.fallback_locale');
196
197 86
        foreach ($files_by_type as $type => $files) {
198 16
            foreach ($files as $locale => $_files) {
199 16
                if (!in_array($locale, config('translatable.locales'))) {
200 10
                    unset($files_by_type[$type][$locale]);
201
202 10
                    if (!isset($files_by_type[$type][$defaultLocale])) {
203 10
                        $files_by_type[$type][$defaultLocale] = [];
204
                    }
205
206 16
                    $files_by_type[$type][$defaultLocale][$locale] = $_files;
207
                }
208
            }
209
        }
210
211 86
        return $files_by_type;
212
    }
213
214 86
    private function sanitizeFilesOrderParameter(array $files_order_by_locale): array
215
    {
216 86
        foreach ($files_order_by_locale as $locale => $fileIdsCollection) {
217 2
            foreach ($fileIdsCollection as $type => $commaSeparatedFileIds) {
218 2
                $type = str_replace("files-", "", $type);
219 2
                $files_order_by_type[$type][] = explode(',', $commaSeparatedFileIds);
220 2
                $files_order_by_type[$type] = collect($files_order_by_type)->flatten()->unique()->toArray();
221
            }
222
        }
223
224 86
        return $files_order_by_type ?? $files_order_by_locale;
225
    }
226
}
227