Passed
Branch feature/cropping (1e92b5)
by Philippe
05:22
created

Asset::hasFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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