Passed
Push — master ( 69f8ad...cfdf92 )
by Philippe
05:26 queued 10s
created

Asset::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Spatie\MediaLibrary\Models\Media;
6
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
7
use Thinktomorrow\Locale\Locale;
0 ignored issues
show
Bug introduced by
The type Thinktomorrow\Locale\Locale was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Illuminate\Support\Collection;
9
use Illuminate\Database\Eloquent\Model;
10
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
11
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
12
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
13
use Spatie\MediaLibrary\HasMedia\HasMedia;
14
15
/**
16
 * @property mixed media
17
 */
18
class Asset extends Model implements HasMedia
19
{
20
    use HasMediaTrait;
0 ignored issues
show
introduced by
The trait Spatie\MediaLibrary\HasMedia\HasMediaTrait requires some properties which are not provided by Thinktomorrow\AssetLibrary\Models\Asset: $each, $mediaConversionRegistrations, $forceDeleting, $collection_name
Loading history...
21
22
    private $order;
23
24
    /**
25
     * Attaches this asset instance to the given model and
26
     * sets the type and locale to the given values and
27
     * returns the model with the asset relationship.
28
     *
29
     * @param Model $model
30
     * @param string $type
31
     * @param null|string $locale
32
     * @return Model
33
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
34
     */
35 38
    public function attachToModel(Model $model, $type = '', $locale = null): Model
36
    {
37 38
        if ($model->assets()->get()->contains($this)) {
38 1
            throw AssetUploadException::create();
39
        }
40
41 38
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
0 ignored issues
show
Bug introduced by
The method where() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

41
        $model->assets->/** @scrutinizer ignore-call */ 
42
                        where('pivot.type', $type)->where('pivot.locale', $locale);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
42
43 38
        $locale = $locale ?? config('app.locale');
44
45 38
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
46
47 38
        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 13
    public function getFilename($size = ''): string
63
    {
64 13
        return basename($this->getFileUrl($size));
65
    }
66
67
    /**
68
     * @param string $size
69
     * @return string
70
     */
71 45
    public function getFileUrl($size = ''): string
72
    {
73 45
        $media = $this->getMedia()->first();
74 45
        if($media == null){
75 1
            throw CorruptMediaException::corrupt($this->id);
76
        }
77
78 44
        if (config('assetlibrary.conversionPrefix') && $size != '') {
79
            $conversionName = $media->name.'_'.$size;
80
        } else {
81 44
            $conversionName = $size;
82
        }
83
84 44
        if ($media == null) {
85
            throw CorruptMediaException::corrupt($this->id);
86
        }
87
88 44
        return $media->getUrl($conversionName);
89
    }
90
91
    /**
92
     * Returns the image url or a fallback specific per filetype.
93
     *
94
     * @param string $type
95
     * @return string
96
     */
97 9
    public function getImageUrl($type = ''): string
98
    {
99 9
        if ($this->getMedia()->isEmpty()) {
100 1
            return asset('assets/back/img/other.png');
101
        }
102 8
        $extension = $this->getExtensionType();
103 8
        if ($extension === 'image') {
104 7
            return $this->getFileUrl($type);
105 1
        } elseif ($extension) {
106 1
            return asset('assets/back/img/'.$extension.'.png');
107
        }
108
109 1
        return asset('assets/back/img/other.png');
110
    }
111
112
    /**
113
     * @return bool|string
114
     */
115 3
    public function getExtensionForFilter()
116
    {
117 3
        if ($extension = $this->getExtensionType()) {
118 2
            return $extension;
119
        }
120
121 1
        return '';
122
    }
123
124
    /**
125
     * @return null|string
126
     * @throws CorruptMediaException
127
     */
128 11
    public function getExtensionType(): ?string
129
    {
130 11
        $media = $this->getMedia()->first();
131 11
        if($media == null){
132 1
            throw CorruptMediaException::corrupt($this->id);
133
        }
134
135 10
        $extension = explode('.', $media->file_name);
136 10
        $extension = end($extension);
137
138 10
        if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
139 1
            return 'xls';
140
        }
141 10
        if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
142 9
            return 'image';
143
        }
144 3
        if (strtolower($extension) === 'pdf') {
145 2
            return 'pdf';
146
        }
147
148 2
        return null;
149
    }
150
151
    /**
152
     * @return string
153
     */
154 2
    public function getMimeType(): string
155
    {
156 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
157
    }
158
159
    /**
160
     * @return bool
161
     */
162 5
    public function isMediaEmpty(): bool
163
    {
164 5
        return $this->getMedia()->isEmpty();
165
    }
166
167
    /**
168
     * @return string
169
     */
170 2
    public function getSize(): string
171
    {
172 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
173
    }
174
175
    /**
176
     * @param null $size
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $size is correct as it would always require null to be passed?
Loading history...
177
     * @return string
178
     */
179 3
    public function getDimensions($size = null): string
180
    {
181 3
        if ($this->isMediaEmpty()) {
182 1
            return '';
183
        }
184
185
        //TODO Check the other sizes as well
186 2
        if ($size === 'cropped') {
0 ignored issues
show
introduced by
The condition $size === 'cropped' is always false.
Loading history...
187 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
188
189 1
            return $dimensions[0].' x'.$dimensions[1];
190
        }
191
192 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
193
    }
194
195
    /**
196
     * Removes one or more assets by their ids.
197
     * @param $imageIds
198
     */
199 5
    public static function remove($imageIds)
200
    {
201 5
        if (is_array($imageIds)) {
202 2
            foreach ($imageIds as $id) {
203 2
                if (! $id) {
204 1
                    continue;
205
                }
206
207 1
                $asset = self::where('id', $id)->first();
208 1
                $media = $asset->media;
209
210 1
                foreach ($media as $file) {
211 1
                    if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
212 1
                        return;
213
                    }
214
                }
215
216 2
                $asset->delete();
217
            }
218
        } else {
219 4
            if (! $imageIds) {
220 1
                return;
221
            }
222
223 3
            $asset = self::find($imageIds)->first();
224 3
            $media = $asset->media;
225
226 3
            foreach ($media as $file) {
227 3
                if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
228 3
                    return;
229
                }
230
            }
231
232 3
            self::find($imageIds)->first()->delete();
233
        }
234 5
    }
235
236
    /**
237
     * Returns a collection of all the assets in the library.
238
     * @return \Illuminate\Support\Collection
239
     */
240 6
    public static function getAllAssets(): Collection
241
    {
242 6
        return self::all()->sortByDesc('created_at');
243
    }
244
245
    /**
246
     * @param $width
247
     * @param $height
248
     * @param $x
249
     * @param $y
250
     * @return $this
251
     * @throws ConfigException
252
     */
253 2
    public function crop($width, $height, $x, $y)
254
    {
255 2
        if (! config('assetlibrary.allowCropping')) {
256 1
            throw ConfigException::create();
257
        }
258 1
        $this->media[0]->manipulations = [
259
            'cropped'   => [
260 1
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
261
            ],
262
        ];
263
264 1
        $this->media[0]->save();
265
266 1
        return $this;
267
    }
268
269
    /**
270
     * Register the conversions that should be performed.
271
     *
272
     * @param Media|null $media
273
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
274
     */
275 61
    public function registerMediaConversions(Media $media = null)
276
    {
277 61
        $conversions        = config('assetlibrary.conversions');
278
279 61
        foreach ($conversions as $key => $value) {
280
281 61
            $conversionName = $key;
282
283 61
            $this->addMediaConversion($conversionName)
284 61
                ->width($value['width'])
285 61
                ->height($value['height'])
286 61
                ->keepOriginalImageFormat()
287 61
                ->optimize();
288
        }
289
290 61
        if (config('assetlibrary.allowCropping')) {
291 1
            $this->addMediaConversion('cropped')
292 1
                ->keepOriginalImageFormat()
293 1
                ->optimize();
294
        }
295 61
    }
296
297 4
    public function setOrder($order)
298
    {
299 4
        $this->order = $order;
300
301 4
        return $this;
302
    }
303
}
304