Passed
Push — master ( 765c1f...eb8479 )
by Philippe
02:18
created

Asset::uploadToAsset()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 20
ccs 11
cts 11
cp 1
rs 8.8571
cc 5
eloc 11
nc 5
nop 2
crap 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A Asset::getFilename() 0 4 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
8
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
9
use Spatie\MediaLibrary\Media;
10
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
11
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
12
use Thinktomorrow\Locale\Locale;
13
14
/**
15
 * @property mixed media
16
 */
17
class Asset extends Model implements HasMediaConversions
18
{
19
    use HasMediaTrait;
20
21
    private $order;
22
23
    /**
24
     * Attaches this asset instance to the given model and
25
     * sets the type and locale to the given values and
26
     * returns the model with the asset relationship.
27
     *
28
     * @param Model $model
29
     * @param string $type
30
     * @param null|string $locale
31
     * @return Model
32
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
33
     */
34 33
    public function attachToModel(Model $model, $type = '', $locale = null): Model
35
    {
36 33
        if($model->assets()->get()->contains($this))
37
        {
38 1
            throw AssetUploadException::create();
39
        }
40
41 33
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
42
43 33
        $locale = $locale ?? Locale::getDefault();
44
45 33
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
46
47 33
        return $model->load('assets');
48
    }
49
50
    /**
51
     * @return bool
52
     */
53 1
    public function hasFile(): bool
54
    {
55 1
        return (bool) $this->getFileUrl();
56
    }
57
58
    /**
59
     * @param string $size
60
     * @return string
61
     */
62 12
    public function getFilename($size = ''): string
63
    {
64 12
        return basename($this->getFileUrl($size));
65
    }
66
67
    /**
68
     * @param string $size
69
     * @return string
70
     */
71 41
    public function getFileUrl($size = ''): string
72
    {
73 41
        $media = $this->getMedia()->first();
74
75 41
        if (config('assetlibrary.conversionPrefix') && $size != '') {
76 1
            $conversionName = $media->name . '_' . $size;
77
        } else {
78 40
            $conversionName = $size;
79
        }
80
81 41
        return $media->getUrl($conversionName);
82
    }
83
84
    /**
85
     * Returns the image url or a fallback specific per filetype.
86
     *
87
     * @param string $type
88
     * @return string
89
     */
90 9
    public function getImageUrl($type = ''): string
91
    {
92 9
        if ($this->getMedia()->isEmpty()) {
93 1
            return asset('assets/back/img/other.png');
94
        }
95 8
        $extension = $this->getExtensionType();
96 8
        if ($extension === 'image') {
97 7
            return $this->getFileUrl($type);
98 1
        } elseif ($extension) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extension of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
99 1
            return asset('assets/back/img/'.$extension.'.png');
100
        }
101
102 1
        return asset('assets/back/img/other.png');
103
    }
104
105
    /**
106
     * @return bool|string
107
     */
108 2
    public function getExtensionForFilter()
109
    {
110 2
        if ($extension = $this->getExtensionType()) {
111 2
            return $extension;
112
        }
113
114 1
        return '';
115
    }
116
117
    /**
118
     * @return string|null
119
     */
120 10
    public function getExtensionType(): ?string
121
    {
122 10
        $extension = explode('.', $this->getMedia()[0]->file_name);
123 10
        $extension = end($extension);
124
125 10
        if (in_array($extension, ['xls', 'xlsx', 'numbers', 'sheets'])) {
126 1
            return 'xls';
127
        }
128 10
        if (in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
129 9
            return 'image';
130
        }
131 3
        if ($extension === 'pdf') {
132 2
            return 'pdf';
133
        }
134
135 2
        return null;
136
    }
137
138
    /**
139
     * @return string
140
     */
141 2
    public function getMimeType(): string
142
    {
143 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
144
    }
145
146
    /**
147
     * @return bool
148
     */
149 5
    public function isMediaEmpty(): bool
150
    {
151 5
        return $this->getMedia()->isEmpty();
152
    }
153
154
    /**
155
     * @return string
156
     */
157 2
    public function getSize(): string
158
    {
159 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
160
    }
161
162
    /**
163
     * @param null $size
164
     * @return string
165
     */
166 3
    public function getDimensions($size = null): string
167
    {
168 3
        if($this->isMediaEmpty()) return '';
169
170
        //TODO Check the other sizes as well
171 2
        if($size === 'cropped')
172
        {
173 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
174 1
            return $dimensions[0] . ' x' . $dimensions[1];
175
        }
176
177 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
178
    }
179
180
    /**
181
     * Removes one or more assets by their ids.
182
     * @param $imageIds
183
     */
184 5
    public static function remove($imageIds)
185
    {
186 5
        if (is_array($imageIds)) {
187 2
            foreach ($imageIds as $id) {
188 2
                if(!$id) continue;
189
190 2
                self::where('id', $id)->first()->delete();
191
            }
192
        } else {
193 4
            if(!$imageIds) return;
194
195 3
            self::find($imageIds)->first()->delete();
196
        }
197 5
    }
198
199
    /**
200
     * Returns a collection of all the assets in the library.
201
     * @return \Illuminate\Support\Collection
202
     */
203 4
    public static function getAllAssets(): Collection
204
    {
205 4
        return self::all()->sortByDesc('created_at');
206
    }
207
208
    /**
209
     * @param $width
210
     * @param $height
211
     * @param $x
212
     * @param $y
213
     * @return $this
214
     * @throws ConfigException
215
     */
216 2
    public function crop($width, $height, $x, $y)
217
    {
218 2
        if(!config('assetlibrary.allowCropping'))
219
        {
220 1
            throw ConfigException::create();
221
        }
222 1
        $this->media[0]->manipulations = [
223
            'cropped'   => [
224 1
                'manualCrop' => $width . ', ' . $height . ', ' . $x . ', ' . $y
225
            ]
226
        ];
227
228 1
        $this->media[0]->save();
229
230 1
        return $this;
231
    }
232
233
    /**
234
     * Register the conversions that should be performed.
235
     *
236
     * @param Media|null $media
237
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
238
     */
239 54
    public function registerMediaConversions(Media $media = null): void
240
    {
241 54
        $conversions        = config('assetlibrary.conversions');
242 54
        $conversionPrefix   = config('assetlibrary.conversionPrefix');
243
244 54
        foreach ($conversions as $key => $value) {
245 54
            if ($conversionPrefix) {
246 1
                $conversionName = $media->name.'_'.$key;
247
            } else {
248 54
                $conversionName = $key;
249
            }
250
251 54
            $this->addMediaConversion($conversionName)
252 54
                ->width($value['width'])
253 54
                ->height($value['height'])
254 54
                ->sharpen(15)
255 54
                ->keepOriginalImageFormat()
256 54
                ->optimize();
257
        }
258
259 54
        if(config('assetlibrary.allowCropping'))
260
        {
261 1
            $this->addMediaConversion('cropped')
262 1
                ->sharpen(15)
263 1
                ->keepOriginalImageFormat()
264 1
                ->optimize();
265
        }
266 54
    }
267
268 5
    public function setOrder($order)
269
    {
270 5
        $this->order = $order;
271 5
        return $this;
272
    }
273
}
274