Completed
Pull Request — master (#38)
by Philippe
08:29 queued 04:23
created

AssetUploader::prepareOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 2
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Traversable;
6
use Illuminate\Support\Str;
7
use Illuminate\Http\UploadedFile;
8
use Illuminate\Support\Collection;
9
use Illuminate\Database\Eloquent\Model;
10
use Spatie\MediaLibrary\FileAdder\FileAdder;
11
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded;
12
13
class AssetUploader extends Model
14
{
15
    /**
16
     * Uploads the file/files or asset by creating the
17
     * asset that is needed to upload the files too.
18
     *
19
     * @param Asset|Traversable|array|Collection|UploadedFile $files
20
     * @param string|null $filename
21
     * @param bool $
0 ignored issues
show
Documentation Bug introduced by
The doc comment $ at position 0 could not be parsed: Unknown type name '$' at position 0 in $.
Loading history...
22
     * @return Collection|null|Asset
23
     * @throws FileCannotBeAdded
24
     */
25 33
    public static function upload($files, $filename = null)
26
    {
27 33
        if ($files instanceof Asset) {
28 10
            return $files;
29
        }
30
31 31
        if (is_array($files) || $files instanceof Traversable) {
32 3
            return self::uploadMultiple($files);
33
        }
34
35 30
        if (! ($files instanceof UploadedFile)) {
36 1
            return;
37
        }
38
39 29
        return self::uploadToAsset($files, Asset::create(), $filename);
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 Asset|Traversable|array $files
47
     * @return Collection
48
     */
49 3
    private static function uploadMultiple($files)
50
    {
51 3
        $list = collect([]);
52
        collect($files)->each(function ($file) use ($list) {
53 3
            if ($file instanceof Asset) {
54 2
                $list->push($file);
55
            } else {
56 3
                $asset = new Asset();
57 3
                $asset->save();
58 3
                $list->push(self::uploadToAsset($file, $asset, null));
59
            }
60 3
        });
61
62 3
        return $list;
63
    }
64
65
    /**
66
     * Uploads the file/files or asset by creating the
67
     * asset that is needed to upload the files too.
68
     *
69
     * @param string $file
70
     * @param string|null $filename
71
     * @return Collection|null|Asset
72
     * @throws FileCannotBeAdded
73
     */
74 5
    public static function uploadFromBase64($file, $filename = null)
75
    {
76 5
        return self::uploadBase64ToAsset($file, Asset::create(), $filename);
77
    }
78
79
    /**
80
     * Uploads the url by creating the
81
     * asset that is needed to upload the files too.
82
     *
83
     * @param string $url
84
     * @return Asset
85
     * @throws FileCannotBeAdded
86
     */
87 11
    public static function uploadFromUrl($url)
88
    {
89 11
        return self::uploadFromUrlToAsset($url, Asset::create());
90
    }
91
92
    /**
93
     * Uploads the given file to this instance of asset
94
     * and sets the dimensions as a custom property.
95
     *
96
     * @param UploadedFile $file
97
     * @param Asset $asset
98
     * @param string|null $filename
99
     * @return null|Asset
100
     * @throws FileCannotBeAdded
101
     */
102 30
    public static function uploadToAsset($file, $asset, $filename = null): ?Asset
103
    {
104 30
        $customProps = [];
105 30
        if (self::isImage($file)) {
106 28
            $imagesize = getimagesize($file);
107
108 28
            $customProps['dimensions'] = $imagesize[0].' x '.$imagesize[1];
109
        }
110
111 30
        $fileAdd = $asset->addMedia($file)
112 30
                        ->withCustomProperties($customProps);
113
114 30
        $fileAdd = self::prepareOptions($fileAdd, $filename);
115
116 30
        $fileAdd->withResponsiveImages()->toMediaCollection();
117
118 30
        return $asset->load('media');
119
    }
120
121
    /**
122
     * Uploads the given file to this instance of asset
123
     * and sets the dimensions as a custom property.
124
     *
125
     * @param string $file
126
     * @param Asset $asset
127
     * @param string|null $filename
128
     * @return null|Asset
129
     * @throws FileCannotBeAdded
130
     * @internal param $files
131
     */
132 5
    public static function uploadBase64ToAsset($file, $asset, $filename = null): ?Asset
133
    {
134 5
        $fileAdd = $asset->addMediaFromBase64($file);
135
136 5
        if (! $filename) {
137 1
            $extension = substr($file, 11, strpos($file, ';') - 11);
138 1
            $filename  = pathinfo($file, PATHINFO_BASENAME).'.'.$extension;
139
        }
140
141 5
        $fileAdd = self::prepareOptions($fileAdd, $filename);
142
143 5
        $fileAdd->toMediaCollection();
144
145 5
        return $asset->load('media');
146
    }
147
148
    /**
149
     * Uploads the given file to this instance of asset
150
     * and sets the dimensions as a custom property.
151
     *
152
     * @param string $url
153
     * @param Asset $asset
154
     * @return Asset
155
     * @throws FileCannotBeAdded
156
     */
157 11
    public static function uploadFromUrlToAsset($url, $asset): Asset
158
    {
159 11
        $fileAdd = $asset->addMediaFromUrl($url);
160
161 11
        $filename = substr($url, strrpos($url, '/') + 1);
162 11
        $fileAdd->setName($filename);
163
164 11
        $fileAdd = self::prepareOptions($fileAdd, $filename);
165
166 11
        $fileAdd->toMediaCollection();
167
168 11
        return $asset->load('media');
169
    }
170
171
    /**
172
     * @param UploadedFile $file
173
     * @return bool
174
     */
175 30
    private static function isImage($file): bool
176
    {
177 30
        return Str::before($file->getMimetype() ?? '', '/') === 'image';
178
    }
179
180
    /**
181
     * Set the possible options on the fileAdder. This includes preserveOriginal
182
     * and filename.
183
     *
184
     * @param FileAdder $fileAdd
185
     * @param string|null $filename
186
     * @return FileAdder
187
     * @throws FileCannotBeAdded
188
     */
189 45
    private static function prepareOptions($fileAdd, $filename): FileAdder
190
    {
191 45
        if ($filename) {
192 18
            $fileAdd->usingName(substr($filename, 0, strpos($filename, '.')));
193 18
            $fileAdd->usingFileName($filename);
194
        }
195
196 45
        $fileAdd->preservingOriginal();
197
198
        // Sanitize filename by sluggifying the filename without the extension
199
        $fileAdd->sanitizingFileName(function ($filename) {
200 45
            $extension = substr($filename, strrpos($filename, '.') + 1);
201 45
            $filename  = substr($filename, 0, strrpos($filename, '.'));
202 45
            $filename  = Str::slug($filename).'.'.$extension;
203
204 45
            return strtolower($filename);
205 45
        });
206
207 45
        return $fileAdd;
208
    }
209
}
210