Passed
Pull Request — master (#24)
by Philippe
03:23
created

AssetUploader::prepareOptions()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 9.9
c 0
b 0
f 0
cc 3
nc 4
nop 3
crap 3
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
     */
23 28
    public static function upload($files, $filename = null, $keepOriginal = false)
24
    {
25 28
        if ($files instanceof Asset) {
26 10
            return $files;
27
        }
28
29 26
        if (is_array($files) || $files instanceof Traversable) {
30 2
            return self::uploadMultiple($files, $keepOriginal);
31
        }
32
33 25
        if (! ($files instanceof File) && ! ($files instanceof UploadedFile)) {
34 1
            return;
35
        }
36
37 24
        $asset = Asset::create();
38
39 24
        return self::uploadToAsset($files, $asset, $filename, $keepOriginal);
40
    }
41
42
    /**
43
     * Uploads the multiple files or assets by creating the
44
     * asset that is needed to upload the files too.
45
     *
46
     * @param $files
47
     * @param boolean $keepOriginal
48
     * @return \Illuminate\Support\Collection
49
     */
50 2
    private static function uploadMultiple($files, $keepOriginal = false)
51
    {
52 2
        $list = collect([]);
53
        collect($files)->each(function ($file) use ($list, $keepOriginal) {
54 2
            if ($file instanceof Asset) {
55 1
                $list->push($file);
56
            } else {
57 2
                $asset = new Asset();
58 2
                $asset->save();
59 2
                $list->push(self::uploadToAsset($file, $asset, null, $keepOriginal));
60
            }
61 2
        });
62
63 2
        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
     *
70
     * @param $file
71
     * @param string|null $filename
72
     * @param bool $keepOriginal
73
     * @return \Illuminate\Support\Collection|null|Asset
74
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
75
     */
76 4
    public static function uploadFromBase64($file, $filename = null, $keepOriginal = false)
77
    {
78 4
        $asset = Asset::create();
79
80 4
        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
     * @param string|null $filename
89
     * @param bool $keepOriginal
90
     * @return \Illuminate\Support\Collection|null|Asset
91
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
92
     */
93 5
    public static function uploadFromUrl($url, $filename = null)
94
    {
95 5
        $asset = Asset::create();
96
97 5
        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
    /**
101
     * Uploads the given file to this instance of asset
102
     * and sets the dimensions as a custom property.
103
     *
104
     * @param $files
105
     * @param Asset $asset
106
     * @param string|null $filename
107
     * @param bool $keepOriginal
108
     * @return null|Asset
109
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
110
     */
111 25
    public static function uploadToAsset($file, $asset, $filename = null, $keepOriginal = false): ?Asset
112
    {
113 25
        $customProps = [];
114 25
        if (self::isImage($file)) {
115 24
            $imagesize = getimagesize($file);
116
117 24
            $customProps['dimensions'] = $imagesize[0].' x '.$imagesize[1];
118
        }
119
120 25
        $fileAdd = $asset->addMedia($file)
121 25
                        ->withCustomProperties($customProps);
122
123 25
        $fileAdd = self::prepareOptions($fileAdd, $keepOriginal, $filename);
124
125 25
        $fileAdd->toMediaCollection();
126
127 25
        return $asset->load('media');
128
    }
129
130
    
131
132
    /**
133
     * Uploads the given file to this instance of asset
134
     * and sets the dimensions as a custom property.
135
     *
136
     * @param $file
137
     * @param Asset $asset
138
     * @param string|null $filename
139
     * @param bool $keepOriginal
140
     * @return null|Asset
141
     * @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 4
        if(!$filename){
149 1
            $extension = substr($file, 11, strpos($file, ';') - 11);
150 1
            $filename  = pathinfo($file, PATHINFO_BASENAME) . '.' . $extension;
151
        }
152
153 4
        $fileAdd = self::prepareOptions($fileAdd, $keepOriginal, $filename);
154
155 4
        $fileAdd->toMediaCollection();
156
157 4
        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 5
    public static function uploadFromUrlToAsset($url, $asset): ?Asset
173
    {
174 5
        $fileAdd = $asset->addMediaFromUrl($url);
175
176 5
        $filename = substr($url, strrpos($url, '/') + 1);
177 5
        $fileAdd->setName($filename);
178
179 5
        $fileAdd = self::prepareOptions($fileAdd, null, $filename);
180
181 5
        $fileAdd->toMediaCollection();
182
        
183 5
        return $asset->load('media');
184
    }
185
    
186
    /**
187
     * @param $file
188
     * @return bool
189
     */
190 25
    private static function isImage($file): bool
191
    {
192 25
        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 33
    private static function prepareOptions($fileAdd, $keepOriginal, $filename): FileAdder
207
    {
208 33
        if ($keepOriginal) {
209 2
            $fileAdd = $fileAdd->preservingOriginal();
210
        }
211
212 33
        if ($filename) {
213 11
            $fileAdd->usingName(substr($filename, 0, strpos($filename, '.')));
214 11
            $fileAdd->usingFileName($filename);
215
        }
216
        
217
        // Sanitize filename by sluggifying the filename without the extension 
218
        $fileAdd->sanitizingFileName(function($filename){
219 33
            $extension = substr($filename, strrpos($filename, '.') + 1);
220 33
            $filename  = substr($filename, 0, strrpos($filename, '.'));
221 33
            $filename  = str_slug($filename).'.'.$extension;
222 33
            return strtolower($filename);
223 33
        });
224
225 33
        return $fileAdd;
226
    }
227
}
228