Test Failed
Pull Request — master (#24)
by Philippe
02:54
created

AssetUploader::prepareOptions()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 20
ccs 0
cts 0
cp 0
rs 9.9
c 0
b 0
f 0
cc 3
nc 4
nop 3
crap 12
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Traversable;
6
use Illuminate\Http\File;
7
use Illuminate\Http\UploadedFile;
8
use Illuminate\Database\Eloquent\Model;
9
use Spatie\MediaLibrary\FileAdder\FileAdder;
10
11
class AssetUploader extends Model
12
{
13
    /**
14
     * Uploads the file/files or asset by creating the
15
     * asset that is needed to upload the files too.
16
     *
17
     * @param $files
18
     * @param string|null $filename
19
     * @param bool $keepOriginal
20
     * @return \Illuminate\Support\Collection|null|Asset
21
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
22 58
     */
23
    public static function upload($files, $filename = null, $keepOriginal = false)
24 58
    {
25 11
        if ($files instanceof Asset) {
26
            return $files;
27
        }
28 58
29 4
        if (is_array($files) || $files instanceof Traversable) {
30
            return self::uploadMultiple($files, $keepOriginal);
31
        }
32 55
33 1
        if (! ($files instanceof File) && ! ($files instanceof UploadedFile)) {
34
            return;
35
        }
36 54
37 54
        $asset = Asset::create();
38
39 54
        return self::uploadToAsset($files, $asset, $filename, $keepOriginal);
40
    }
41
42 4
    /**
43
     * Uploads the multiple files or assets by creating the
44 4
     * asset that is needed to upload the files too.
45 4
     *
46 4
     * @param $files
47 1
     * @param boolean $keepOriginal
48
     * @return \Illuminate\Support\Collection
49 4
     */
50 4
    private static function uploadMultiple($files, $keepOriginal = false)
51 4
    {
52
        $list = collect([]);
53 4
        collect($files)->each(function ($file) use ($list, $keepOriginal) {
54
            if ($file instanceof Asset) {
55 4
                $list->push($file);
56
            } else {
57
                $asset = new Asset();
58
                $asset->save();
59
                $list->push(self::uploadToAsset($file, $asset, null, $keepOriginal));
60
            }
61
        });
62
63
        return $list;
64
    }
65
66
    /**
67
     * Uploads the file/files or asset by creating the
68
     * asset that is needed to upload the files too.
69 4
     *
70
     * @param $file
71 4
     * @param string|null $filename
72 4
     * @param bool $keepOriginal
73
     * @return \Illuminate\Support\Collection|null|Asset
74 4
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
75
     */
76
    public static function uploadFromBase64($file, $filename = null, $keepOriginal = false)
77
    {
78
        $asset = Asset::create();
79
80
        return self::uploadBase64ToAsset($file, $asset, $filename, $keepOriginal);
81
    }
82
83
    /**
84
     * Uploads the url by creating the
85
     * asset that is needed to upload the files too.
86
     *
87
     * @param $file
88 57
     * @param string|null $filename
89
     * @param bool $keepOriginal
90 57
     * @return \Illuminate\Support\Collection|null|Asset
91 57
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
92 54
     */
93
    public static function uploadFromUrl($url, $filename = null)
94
    {
95 57
        $asset = Asset::create();
96 57
97 1
        return self::uploadFromUrlToAsset($url, $asset, $filename);
0 ignored issues
show
Unused Code introduced by
The call to Thinktomorrow\AssetLibra...:uploadFromUrlToAsset() has too many arguments starting with $filename. ( Ignorable by Annotation )

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

97
        return self::/** @scrutinizer ignore-call */ uploadFromUrlToAsset($url, $asset, $filename);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
98
    }
99
100 57
    /**
101 4
     * Uploads the given file to this instance of asset
102 4
     * and sets the dimensions as a custom property.
103
     *
104
     * @param $files
105 57
     * @param Asset $asset
106
     * @param string|null $filename
107 57
     * @param bool $keepOriginal
108
     * @return null|Asset
109
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
110
     */
111
    public static function uploadToAsset($file, $asset, $filename = null, $keepOriginal = false): ?Asset
112
    {
113
        $customProps = [];
114
        if (self::isImage($file)) {
115
            $imagesize = getimagesize($file);
116
117
            $customProps['dimensions'] = $imagesize[0].' x '.$imagesize[1];
118
        }
119
120
        $fileAdd = $asset->addMedia($file)
121
                        ->withCustomProperties($customProps);
122 4
123
        $fileAdd = self::prepareOptions($fileAdd, $keepOriginal, $filename);
124
125
        $fileAdd->toMediaCollection();
126
127
        return $asset->load('media');
128
    }
129 4
130 4
    
131 1
132
    /**
133
     * Uploads the given file to this instance of asset
134 4
     * and sets the dimensions as a custom property.
135 3
     *
136 3
     * @param $file
137
     * @param Asset $asset
138 1
     * @param string|null $filename
139 1
     * @param bool $keepOriginal
140 1
     * @return null|Asset
141 1
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
142
     * @internal param $files
143
     */
144 4
    public static function uploadBase64ToAsset($file, $asset, $filename = null, $keepOriginal = false): ?Asset
145
    {
146 4
        $fileAdd = $asset->addMediaFromBase64($file);
147
148
        if(!$filename){
149
            $extension = substr($file, 11, strpos($file, ';') - 11);
150
            $filename  = pathinfo($file, PATHINFO_BASENAME) . '.' . $extension;
151
        }
152
153 57
        $fileAdd = self::prepareOptions($fileAdd, $keepOriginal, $filename);
154
155 57
        $fileAdd->toMediaCollection();
156
157
        return $asset->load('media');
158
    }
159
160
    /**
161
     * Uploads the given file to this instance of asset
162
     * and sets the dimensions as a custom property.
163
     *
164
     * @param $file
165
     * @param Asset $asset
166
     * @param string|null $filename
167
     * @param bool $keepOriginal
168
     * @return null|Asset
169
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
170
     * @internal param $files
171
     */
172
    public static function uploadFromUrlToAsset($url, $asset): ?Asset
173
    {
174
        $fileAdd = $asset->addMediaFromUrl($url);
175
176
        $filename = substr($url, strrpos($url, '/') + 1);
177
        $fileAdd->setName($filename);
178
179
        $fileAdd = self::prepareOptions($fileAdd, null, $filename);
180
181
        $fileAdd->toMediaCollection();
182
        
183
        return $asset->load('media');
184
    }
185
    
186
    /**
187
     * @param $file
188
     * @return bool
189
     */
190
    private static function isImage($file): bool
191
    {
192
        return str_before($file->getMimetype(), '/') === 'image';
193
    }
194
195
    /**
196
     * Set the possible options on the fileAdder. This includes preserveOriginal
197
     * and filename.
198
     *
199
     * @param $files
200
     * @param Asset $asset
201
     * @param string|null $filename
202
     * @param bool $keepOriginal
203
     * @return null|Asset
204
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
205
     */
206
    private static function prepareOptions($fileAdd, $keepOriginal, $filename): FileAdder
207
    {
208
        if ($keepOriginal) {
209
            $fileAdd = $fileAdd->preservingOriginal();
210
        }
211
212
        if ($filename) {
213
            $fileAdd->usingName(substr($filename, 0, strpos($filename, '.')));
214
            $fileAdd->usingFileName($filename);
215
        }
216
        
217
        // Sanitize filename by sluggifying the filename without the extension 
218
        $fileAdd->sanitizingFileName(function($filename){
219
            $extension = substr($filename, strrpos($filename, '.') + 1);
220
            $filename  = substr($filename, 0, strrpos($filename, '.'));
221
            $filename  = str_slug($filename).'.'.$extension;
222
            return strtolower($filename);
223
        });
224
225
        return $fileAdd;
226
    }
227
}
228