Passed
Push — master ( 9c66f6...3bb44a )
by Philippe
07:58
created

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