Passed
Push — 0.6 ( 548853...aeb83d )
by Philippe
09:22
created

Asset   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 225
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 68
dl 0
loc 225
ccs 79
cts 79
cp 1
rs 9.84
c 0
b 0
f 0
wmc 32

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getSize() 0 3 2
A getMimeType() 0 3 2
A isMediaEmpty() 0 3 1
A getDimensions() 0 14 3
A getExtensionForFilter() 0 7 2
A crop() 0 14 2
A attachToModel() 0 13 2
A getImageUrl() 0 13 4
A getFilename() 0 3 1
A hasFile() 0 3 1
A registerMediaConversions() 0 16 3
A getExtensionType() 0 24 6
A getFileUrl() 0 9 2
A setOrder() 0 5 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Illuminate\Support\Collection;
6
use Spatie\MediaLibrary\Models\Media;
7
use Illuminate\Database\Eloquent\Model;
8
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
9
use Thinktomorrow\AssetLibrary\Interfaces\HasAsset;
10
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
11
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
12
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
13
14
class Asset extends Model implements HasAsset
15
{
16
    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...
17
18
    private $order;
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 HasAsset $model
26
     * @param string $type
27
     * @param null|string $locale
28
     * @return HasAsset
29
     * @throws AssetUploadException
30
     */
31 42
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
32
    {
33 42
        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

33
        if ($model->/** @scrutinizer ignore-call */ assets()->get()->contains($this)) {
Loading history...
34 1
            throw AssetUploadException::create();
35
        }
36
37 42
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
38
39 42
        $locale = $locale ?? config('app.fallback_locale');
40
41 42
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
42
43 42
        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

43
        return $model->/** @scrutinizer ignore-call */ load('assets');
Loading history...
44
    }
45
46
    /**
47
     * @return bool
48
     */
49 1
    public function hasFile(): bool
50
    {
51 1
        return (bool) $this->getFileUrl();
52
    }
53
54
    /**
55
     * @param string $size
56
     * @return string
57
     */
58 12
    public function getFilename($size = ''): string
59
    {
60 12
        return basename($this->getFileUrl($size));
61
    }
62
63
    /**
64
     * @param string $size
65
     * @return string
66
     */
67 54
    public function getFileUrl($size = ''): string
68
    {
69 54
        $media = $this->getMedia()->first();
70
71 54
        if ($media == null) {
72 1
            throw CorruptMediaException::corrupt($this->id);
73
        }
74
75 53
        return $media->getUrl($size);
76
    }
77
78
    /**
79
     * Returns the image url or a fallback specific per filetype.
80
     *
81
     * @param string $type
82
     * @return string
83
     */
84 10
    public function getImageUrl($type = ''): string
85
    {
86 10
        if ($this->getMedia()->isEmpty()) {
87 2
            return asset('assets/back/img/other.png');
88
        }
89 9
        $extension = $this->getExtensionType();
90 9
        if ($extension === 'image') {
91 8
            return $this->getFileUrl($type);
92 1
        } elseif ($extension) {
93 1
            return asset('assets/back/img/'.$extension.'.png');
94
        }
95
96 1
        return asset('assets/back/img/other.png');
97
    }
98
99
    /**
100
     * @return bool|string
101
     */
102 6
    public function getExtensionForFilter()
103
    {
104 6
        if ($extension = $this->getExtensionType()) {
105 5
            return $extension;
106
        }
107
108 1
        return '';
109
    }
110
111
    /**
112
     * @return null|string
113
     * @throws CorruptMediaException
114
     */
115 15
    public function getExtensionType(): ?string
116
    {
117 15
        $media = $this->getMedia()->first();
118
119 15
        if ($media == null) {
120 1
            throw CorruptMediaException::corrupt($this->id);
121
        }
122
123 14
        $extension = explode('.', $media->file_name);
124 14
        $extension = end($extension);
125
126 14
        if ($extension) {
127 14
            if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
128 1
                return 'xls';
129
            }
130 14
            if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
131 13
                return 'image';
132
            }
133 3
            if (strtolower($extension) === 'pdf') {
134 2
                return 'pdf';
135
            }
136
        }
137
138 2
        return null;
139
    }
140
141
    /**
142
     * @return string
143
     */
144 2
    public function getMimeType(): string
145
    {
146 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
147
    }
148
149
    /**
150
     * @return bool
151
     */
152 5
    public function isMediaEmpty(): bool
153
    {
154 5
        return $this->getMedia()->isEmpty();
155
    }
156
157
    /**
158
     * @return string
159
     */
160 2
    public function getSize(): string
161
    {
162 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
163
    }
164
165
    /**
166
     * @param string|null $size
167
     * @return string
168
     */
169 3
    public function getDimensions($size = null): string
170
    {
171 3
        if ($this->isMediaEmpty()) {
172 1
            return '';
173
        }
174
175
        //TODO Check the other sizes as well
176 2
        if ($size === 'cropped') {
177 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
178
179 1
            return $dimensions[0].' x'.$dimensions[1];
180
        }
181
182 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
183
    }
184
185
    /**
186
     * @param $width
187
     * @param $height
188
     * @param $x
189
     * @param $y
190
     * @return $this
191
     * @throws ConfigException
192
     */
193 2
    public function crop($width, $height, $x, $y)
194
    {
195 2
        if (! config('assetlibrary.allowCropping')) {
196 1
            throw ConfigException::create();
197
        }
198 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...
199
            'cropped'   => [
200 1
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
201
            ],
202
        ];
203
204 1
        $this->media[0]->save();
205
206 1
        return $this;
207
    }
208
209
    /**
210
     * Register the conversions that should be performed.
211
     *
212
     * @param Media|null $media
213
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
214
     */
215 48
    public function registerMediaConversions(Media $media = null)
216
    {
217 48
        $conversions = config('assetlibrary.conversions');
218
219 48
        foreach ($conversions as $key => $value) {
220 48
            $this->addMediaConversion($key)
221 48
                ->width($value['width'])
222 48
                ->height($value['height'])
223 48
                ->keepOriginalImageFormat()
224 48
                ->optimize();
225
        }
226
227 48
        if (config('assetlibrary.allowCropping')) {
228 1
            $this->addMediaConversion('cropped')
229 1
                ->keepOriginalImageFormat()
230 1
                ->optimize();
231
        }
232 48
    }
233
234 15
    public function setOrder($order)
235
    {
236 15
        $this->order = $order;
237
238 15
        return $this;
239
    }
240
}
241