Passed
Pull Request — master (#26)
by Philippe
08:53 queued 03:20
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\HasMediaTrait;
10
use Thinktomorrow\AssetLibrary\Interfaces\HasAsset;
11
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
12
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
13
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
14
15
class Asset extends Model implements HasAsset
16
{
17
    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, $media, $collection_name
Loading history...
18
19
    private $order;
20
21
    /**
22
     * Attaches this asset instance to the given model and
23
     * sets the type and locale to the given values and
24
     * returns the model with the asset relationship.
25
     *
26
     * @param HasAsset $model
27
     * @param string $type
28
     * @param null|string $locale
29
     * @return HasAsset
30
     * @throws AssetUploadException
31
     */
32 38
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
33
    {
34 38
        if ($model->assets()->get()->contains($this)) {
0 ignored issues
show
Bug introduced by
The method assets() does not exist on Thinktomorrow\AssetLibrary\Interfaces\HasAsset. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\AssetLibrary\Interfaces\HasAsset. ( Ignorable by Annotation )

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

34
        if ($model->/** @scrutinizer ignore-call */ assets()->get()->contains($this)) {
Loading history...
35 1
            throw AssetUploadException::create();
36
        }
37
38 38
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
39
40 38
        $locale = $locale ?? config('app.fallback_locale');
41
42 38
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
43
44 38
        return $model->load('assets');
0 ignored issues
show
Bug introduced by
The method load() does not exist on Thinktomorrow\AssetLibrary\Interfaces\HasAsset. Since it exists in all sub-types, consider adding an abstract or default implementation to Thinktomorrow\AssetLibrary\Interfaces\HasAsset. ( Ignorable by Annotation )

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

44
        return $model->/** @scrutinizer ignore-call */ load('assets');
Loading history...
45
    }
46
47
    /**
48
     * @return bool
49
     */
50 1
    public function hasFile(): bool
51
    {
52 1
        return (bool) $this->getFileUrl();
53
    }
54
55
    /**
56
     * @param string $size
57
     * @return string
58
     */
59 12
    public function getFilename($size = ''): string
60
    {
61 12
        return basename($this->getFileUrl($size));
62
    }
63
64
    /**
65
     * @param string $size
66
     * @return string
67
     */
68 52
    public function getFileUrl($size = ''): string
69
    {
70 52
        $media = $this->getMedia()->first();
71 52
        if ($media == null) {
72 1
            throw CorruptMediaException::corrupt($this->id);
73
        }
74
75 51
        if ($media == null) {
76
            throw CorruptMediaException::corrupt($this->id);
77
        }
78
79 51
        return $media->getUrl($size);
80
    }
81
82
    /**
83
     * Returns the image url or a fallback specific per filetype.
84
     *
85
     * @param string $type
86
     * @return string
87
     */
88 10
    public function getImageUrl($type = ''): string
89
    {
90 10
        if ($this->getMedia()->isEmpty()) {
91 1
            return asset('assets/back/img/other.png');
92
        }
93 9
        $extension = $this->getExtensionType();
94 9
        if ($extension === 'image') {
95 8
            return $this->getFileUrl($type);
96 1
        } elseif ($extension) {
97 1
            return asset('assets/back/img/'.$extension.'.png');
98
        }
99
100 1
        return asset('assets/back/img/other.png');
101
    }
102
103
    /**
104
     * @return bool|string
105
     */
106 2
    public function getExtensionForFilter()
107
    {
108 2
        if ($extension = $this->getExtensionType()) {
109 2
            return $extension;
110
        }
111
112 1
        return '';
113
    }
114
115
    /**
116
     * @return null|string
117
     * @throws CorruptMediaException
118
     */
119 11
    public function getExtensionType(): ?string
120
    {
121 11
        $media = $this->getMedia()->first();
122 11
        if ($media == null) {
123
            throw CorruptMediaException::corrupt($this->id);
124
        }
125
126 11
        $extension = explode('.', $media->file_name);
127 11
        $extension = end($extension);
128
129 11
        if ($extension) {
130 11
            if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
131 1
                return 'xls';
132
            }
133 11
            if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
134 10
                return 'image';
135
            }
136 3
            if (strtolower($extension) === 'pdf') {
137 2
                return 'pdf';
138
            }
139
        }
140
141 2
        return null;
142
    }
143
144
    /**
145
     * @return string
146
     */
147 2
    public function getMimeType(): string
148
    {
149 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
150
    }
151
152
    /**
153
     * @return bool
154
     */
155 5
    public function isMediaEmpty(): bool
156
    {
157 5
        return $this->getMedia()->isEmpty();
158
    }
159
160
    /**
161
     * @return string
162
     */
163 2
    public function getSize(): string
164
    {
165 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
166
    }
167
168
    /**
169
     * @param string|null $size
170
     * @return string
171
     */
172 3
    public function getDimensions($size = null): string
173
    {
174 3
        if ($this->isMediaEmpty()) {
175 1
            return '';
176
        }
177
178
        //TODO Check the other sizes as well
179 2
        if ($size === 'cropped') {
180 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
181
182 1
            return $dimensions[0].' x'.$dimensions[1];
183
        }
184
185 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
186
    }
187
188
    /**
189
     * Removes one or more assets by their ids.
190
     */
191 5
    public static function remove($imageIds)
192
    {
193 5
        if (is_array($imageIds)) {
194 2
            foreach ($imageIds as $id) {
195 2
                self::removeFile($id);
196
            }
197
        } else {
198 4
            self::removeFile($imageIds);
199
        }
200 5
    }
201
202
    /**
203
     * Removes itself.
204
     */
205 1
    public function removeSelf()
206
    {
207 1
        $this->removeFile($this->id);
208 1
    }
209
210 6
    private static function removeFile($id)
211
    {
212 6
        if (! $id) {
213 1
            return;
214
        }
215
216 5
        $asset = self::find($id)->first();
217
218 5
        $media = $asset->media;
219
220 5
        foreach ($media as $file) {
221 5
            if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
222 5
                return false;
223
            }
224
        }
225 5
        $asset->delete();
226 5
    }
227
228
    /**
229
     * Returns a collection of all the assets in the library.
230
     * @return \Illuminate\Support\Collection
231
     */
232 6
    public static function getAllAssets(): Collection
233
    {
234 6
        return self::all()->sortByDesc('created_at');
235
    }
236
237
    /**
238
     * @return $this
239
     * @throws ConfigException
240
     */
241 2
    public function crop($width, $height, $x, $y)
242
    {
243 2
        if (! config('assetlibrary.allowCropping')) {
244 1
            throw ConfigException::create();
245
        }
246 1
        $this->media[0]->manipulations = [
0 ignored issues
show
Bug introduced by
The property media does not seem to exist on Thinktomorrow\AssetLibrary\Models\Asset. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
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
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
262
     */
263 40
    public function registerMediaConversions(Media $media = null)
264
    {
265 40
        $conversions = config('assetlibrary.conversions');
266
267 40
        foreach ($conversions as $key => $value) {
268 40
            $this->addMediaConversion($key)
269 40
                ->width($value['width'])
270 40
                ->height($value['height'])
271 40
                ->keepOriginalImageFormat()
272 40
                ->optimize();
273
        }
274
275 40
        if (config('assetlibrary.allowCropping')) {
276 1
            $this->addMediaConversion('cropped')
277 1
                ->keepOriginalImageFormat()
278 1
                ->optimize();
279
        }
280 40
    }
281
282 5
    public function setOrder($order)
283
    {
284 5
        $this->order = $order;
285
286 5
        return $this;
287
    }
288
}
289