Passed
Branch feature/cropping (61215b)
by Philippe
02:36
created

Asset   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 239
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 97.62%

Importance

Changes 4
Bugs 1 Features 1
Metric Value
wmc 34
c 4
b 1
f 1
lcom 2
cbo 5
dl 0
loc 239
ccs 82
cts 84
cp 0.9762
rs 9.2

15 Methods

Rating   Name   Duplication   Size   Complexity  
A attachToModel() 0 10 1
A hasFile() 0 4 1
A getFilename() 0 4 1
A getFileUrl() 0 12 3
A getImageUrl() 0 14 4
A getExtensionForFilter() 0 8 2
A getExtensionType() 0 17 4
A getMimeType() 0 4 2
A isMediaEmpty() 0 4 1
A getSize() 0 4 2
A getDimensions() 0 13 3
A remove() 0 10 3
A getAllAssets() 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 32
    public function getFileUrl($size = ''): string
63
    {
64 32
        $media = $this->getMedia();
65
66 32
        if (config('assetlibrary.conversionPrefix') && $size != '') {
67 1
            $conversionName = $media->first()->name . '_' . $size;
68
        } else {
69 31
            $conversionName = $size;
70
        }
71
72 32
        return $media->first()->getUrl($conversionName);
73
    }
74
75
    /**
76
     * Returns the image url or a fallback specific per filetype.
77
     *
78
     * @param string $type
79
     * @return string
80
     */
81 7
    public function getImageUrl($type = ''): string
82
    {
83 7
        if ($this->getMedia()->isEmpty()) {
84
            return asset('assets/back/img/other.png');
85
        }
86 7
        $extension = $this->getExtensionType();
87 7
        if ($extension === 'image') {
88 6
            return $this->getFileUrl($type);
89 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...
90 1
            return asset('assets/back/img/'.$extension.'.png');
91
        }
92
93 1
        return asset('assets/back/img/other.png');
94
    }
95
96
    /**
97
     * @return bool|string
98
     */
99 1
    public function getExtensionForFilter()
100
    {
101 1
        if ($extension = $this->getExtensionType()) {
102 1
            return $extension;
103
        }
104
105
        return '';
106
    }
107
108
    /**
109
     * @return string|null
110
     */
111 8
    public function getExtensionType(): ?string
112
    {
113 8
        $extension = explode('.', $this->getMedia()[0]->file_name);
114 8
        $extension = end($extension);
115
116 8
        if (in_array($extension, ['xls', 'xlsx', 'numbers', 'sheets'])) {
117 1
            return 'xls';
118
        }
119 8
        if (in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
120 7
            return 'image';
121
        }
122 2
        if ($extension === 'pdf') {
123 2
            return 'pdf';
124
        }
125
126 1
        return null;
127
    }
128
129
    /**
130
     * @return string
131
     */
132 2
    public function getMimeType(): string
133
    {
134 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
135
    }
136
137
    /**
138
     * @return bool
139
     */
140 5
    public function isMediaEmpty(): bool
141
    {
142 5
        return $this->getMedia()->isEmpty();
143
    }
144
145
    /**
146
     * @return string
147
     */
148 2
    public function getSize(): string
149
    {
150 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
151
    }
152
153
    /**
154
     * @param null $size
155
     * @return string
156
     */
157 3
    public function getDimensions($size = null): string
158
    {
159 3
        if($this->isMediaEmpty()) return '';
160
161
        //TODO Check the other sizes as well
162 2
        if($size === 'cropped')
163
        {
164 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
165 1
            return $dimensions[0] . ' x' . $dimensions[1];
166
        }
167
168 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
169
    }
170
171
    /**
172
     * Removes one or more assets by their ids.
173
     * @param $imageIds
174
     */
175 4
    public static function remove($imageIds)
176
    {
177 4
        if (is_array($imageIds)) {
178 1
            foreach ($imageIds as $id) {
179 1
                self::where('id', $id)->first()->delete();
180
            }
181
        } else {
182 3
            self::find($imageIds)->first()->delete();
183
        }
184 4
    }
185
186
    /**
187
     * Returns a collection of all the assets in the library.
188
     * @return \Illuminate\Support\Collection
189
     */
190 3
    public static function getAllAssets(): Collection
191
    {
192 3
        return self::all()->sortByDesc('created_at');
193
    }
194
195
    /**
196
     * @param $width
197
     * @param $height
198
     * @param $x
199
     * @param $y
200
     *
201
     * @return $this
202
     * @throws \Spatie\MediaLibrary\Exceptions\ConfigException
203
     */
204 2
    public function crop($width, $height, $x, $y)
205
    {
206 2
        if(!config('assetlibrary.allowCropping'))
207
        {
208 1
            throw ConfigException::create();
209
        }
210 1
        $this->media[0]->manipulations = [
211
            'cropped'   => [
212 1
                'manualCrop' => $width . ', ' . $height . ', ' . $x . ', ' . $y
213
            ]
214
        ];
215
216 1
        $this->media[0]->save();
217
218 1
        return $this;
219
    }
220
221
    /**
222
     * Register the conversions that should be performed.
223
     *
224
     * @param Media|null $media
225
     */
226 41
    public function registerMediaConversions(Media $media = null): void
227
    {
228 41
        $conversions        = config('assetlibrary.conversions');
229 41
        $conversionPrefix   = config('assetlibrary.conversionPrefix');
230
231 41
        foreach ($conversions as $key => $value) {
232 41
            if ($conversionPrefix) {
233 1
                $conversionName = $media->name.'_'.$key;
234
            } else {
235 41
                $conversionName = $key;
236
            }
237
238 41
            $this->addMediaConversion($conversionName)
239 41
                ->width($value['width'])
240 41
                ->height($value['height'])
241 41
                ->sharpen(15)
242 41
                ->keepOriginalImageFormat()
243 41
                ->optimize();
244
        }
245
246 41
        if(config('assetlibrary.allowCropping'))
247
        {
248 1
            $this->addMediaConversion('cropped')
249 1
                ->sharpen(15)
250 1
                ->keepOriginalImageFormat()
251 1
                ->optimize();
252
        }
253 41
    }
254
}
255