Passed
Branch feature/cropping (7d843b)
by Philippe
02:38
created

Asset   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 275
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 98.92%

Importance

Changes 4
Bugs 1 Features 1
Metric Value
wmc 38
lcom 2
cbo 5
dl 0
loc 275
ccs 92
cts 93
cp 0.9892
rs 8.3999
c 4
b 1
f 1

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getFileUrl() 0 16 4
A getImageUrl() 0 14 4
A getExtensionForFilter() 0 8 2
A getMimeType() 0 4 2
A isMediaEmpty() 0 4 1
A getSize() 0 4 2
A getDimensions() 0 13 3
A getAllAssets() 0 4 1
A attachToModel() 0 10 1
A hasFile() 0 4 1
A getFilename() 0 4 1
A getExtensionType() 0 17 4
A remove() 0 10 3
A typeField() 0 10 2
A localeField() 0 4 1
A crop() 0 16 2
B registerMediaConversions() 0 28 4
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Spatie\MediaLibrary\Exceptions\ConfigException;
8
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
9
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
10
use Spatie\MediaLibrary\Media;
11
use Thinktomorrow\Locale\Locale;
12
13
/**
14
 * @property mixed media
15
 */
16
class Asset extends Model implements HasMediaConversions
17
{
18
    use HasMediaTrait;
19
20
    /**
21
     * Attaches this asset instance to the given model and
22
     * sets the type and locale to the given values and
23
     * returns the model with the asset relationship.
24
     *
25
     * @param Model $model
26
     * @param string $type
27
     * @param null|string $locale
28
     * @return Model
29
     */
30 21
    public function attachToModel(Model $model, $type = '', $locale = null): Model
31
    {
32 21
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
33
34 21
        $locale = $locale ?? Locale::getDefault();
35
36 21
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale]);
37
38 21
        return $model->load('assets');
39
    }
40
41
    /**
42
     * @return bool
43
     */
44 1
    public function hasFile(): bool
45
    {
46 1
        return (bool) $this->getFileUrl();
47
    }
48
49
    /**
50
     * @param string $size
51
     * @return string
52
     */
53 10
    public function getFilename($size = ''): string
54
    {
55 10
        return basename($this->getFileUrl($size));
56
    }
57
58
    /**
59
     * @param string $size
60
     * @return string
61
     */
62 33
    public function getFileUrl($size = ''): string
63
    {
64 33
        $media = $this->getMedia();
65
66 33
        if ($media->count() < 1) {
67 1
            return asset('assets/back/img/other.png');
68
        }
69
70 32
        if (config('assetlibrary.conversionPrefix') && $size != '') {
71 1
            $conversionName = $media->first()->name . '_' . $size;
72
        } else {
73 31
            $conversionName = $size;
74
        }
75
76 32
        return $media->first()->getUrl($conversionName);
77
    }
78
79
    /**
80
     * Returns the image url or a fallback specific per filetype.
81
     *
82
     * @param string $type
83
     * @return string
84
     */
85 8
    public function getImageUrl($type = ''): string
86
    {
87 8
        if ($this->getMedia()->isEmpty()) {
88 1
            return asset('assets/back/img/other.png');
89
        }
90 7
        $extension = $this->getExtensionType();
91 7
        if ($extension === 'image') {
92 6
            return $this->getFileUrl($type);
93 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...
94 1
            return asset('assets/back/img/'.$extension.'.png');
95
        }
96
97 1
        return asset('assets/back/img/other.png');
98
    }
99
100
    /**
101
     * @return bool|string
102
     */
103 1
    public function getExtensionForFilter()
104
    {
105 1
        if ($extension = $this->getExtensionType()) {
106 1
            return $extension;
107
        }
108
109
        return '';
110
    }
111
112
    /**
113
     * @return string|null
114
     */
115 8
    public function getExtensionType(): ?string
116
    {
117 8
        $extension = explode('.', $this->getMedia()[0]->file_name);
118 8
        $extension = end($extension);
119
120 8
        if (in_array($extension, ['xls', 'xlsx', 'numbers', 'sheets'])) {
121 1
            return 'xls';
122
        }
123 8
        if (in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
124 7
            return 'image';
125
        }
126 2
        if ($extension === 'pdf') {
127 2
            return 'pdf';
128
        }
129
130 1
        return null;
131
    }
132
133
    /**
134
     * @return string
135
     */
136 2
    public function getMimeType(): string
137
    {
138 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
139
    }
140
141
    /**
142
     * @return bool
143
     */
144 5
    public function isMediaEmpty(): bool
145
    {
146 5
        return $this->getMedia()->isEmpty();
147
    }
148
149
    /**
150
     * @return string
151
     */
152 2
    public function getSize(): string
153
    {
154 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
155
    }
156
157
    /**
158
     * @param null $size
159
     * @return string
160
     */
161 3
    public function getDimensions($size = null): string
162
    {
163 3
        if($this->isMediaEmpty()) return '';
164
165
        //TODO Check the other sizes as well
166 2
        if($size === 'cropped')
167
        {
168 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
169 1
            return $dimensions[0] . ' x' . $dimensions[1];
170
        }
171
172 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
173
    }
174
175
    /**
176
     * Removes one or more assets by their ids.
177
     * @param $imageIds
178
     */
179 4
    public static function remove($imageIds)
180
    {
181 4
        if (is_array($imageIds)) {
182 1
            foreach ($imageIds as $id) {
183 1
                self::where('id', $id)->first()->delete();
184
            }
185
        } else {
186 3
            self::find($imageIds)->first()->delete();
187
        }
188 4
    }
189
190
    /**
191
     * Returns a collection of all the assets in the library.
192
     * @return \Illuminate\Support\Collection
193
     */
194 3
    public static function getAllAssets(): Collection
195
    {
196 3
        return self::all()->sortByDesc('created_at');
197
    }
198
199
    /**
200
     * Generates the hidden field that links the file to a specific type.
201
     *
202
     * @param string $type
203
     * @param null $locale
204
     *
205
     * @param string $name
206
     * @return string
207
     */
208 3
    public static function typeField($type = '', $locale = null, $name = 'type'): string
209
    {
210 3
        $result = '<input type="hidden" value="'.$type.'" name="';
211
212 3
        if (! $locale) {
213 3
            return $result.$name.'">';
214
        }
215
216 1
        return $result.'trans['.$locale.'][files][]">';
217
    }
218
219
    /**
220
     * Generates the hidden field that links the file to translations.
221
     *
222
     * @param string $locale
223
     *
224
     * @return string
225
     */
226 1
    public static function localeField($locale = ''): string
227
    {
228 1
        return self::typeField($locale, null, 'locale');
229
    }
230
231
    /**
232
     * @param $width
233
     * @param $height
234
     * @param $x
235
     * @param $y
236
     *
237
     * @return $this
238
     * @throws \Spatie\MediaLibrary\Exceptions\ConfigException
239
     */
240 2
    public function crop($width, $height, $x, $y)
241
    {
242 2
        if(!config('assetlibrary.allowCropping'))
243
        {
244 1
            throw ConfigException::create();
245
        }
246 1
        $this->media[0]->manipulations = [
247
            'cropped'   => [
248 1
                'manualCrop' => $width . ', ' . $height . ', ' . $x . ', ' . $y
249
            ]
250
        ];
251
252 1
        $this->media[0]->save();
253
254 1
        return $this;
255
    }
256
257
    /**
258
     * Register the conversions that should be performed.
259
     *
260
     * @param Media|null $media
261
     */
262 41
    public function registerMediaConversions(Media $media = null): void
263
    {
264 41
        $conversions        = config('assetlibrary.conversions');
265 41
        $conversionPrefix   = config('assetlibrary.conversionPrefix');
266
267 41
        foreach ($conversions as $key => $value) {
268 41
            if ($conversionPrefix) {
269 1
                $conversionName = $media->name.'_'.$key;
270
            } else {
271 41
                $conversionName = $key;
272
            }
273
274 41
            $this->addMediaConversion($conversionName)
275 41
                ->width($value['width'])
276 41
                ->height($value['height'])
277 41
                ->sharpen(15)
278 41
                ->keepOriginalImageFormat()
279 41
                ->optimize();
280
        }
281
282 41
        if(config('assetlibrary.allowCropping'))
283
        {
284 1
            $this->addMediaConversion('cropped')
285 1
                ->sharpen(15)
286 1
                ->keepOriginalImageFormat()
287 1
                ->optimize();
288
        }
289 41
    }
290
}
291