Completed
Pull Request — master (#38)
by Philippe
05:00
created

Asset::getImageUrl()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 4
eloc 8
c 2
b 1
f 0
nc 4
nop 1
dl 0
loc 13
rs 10
ccs 3
cts 3
cp 1
crap 4
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Spatie\MediaLibrary\Models\Media;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
8
use Thinktomorrow\AssetLibrary\Interfaces\HasAsset;
9
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
10
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
11
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
12
13
class Asset extends Model implements HasAsset
14
{
15
    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...
16
17
    private $order;
18
19
    /**
20
     * Attaches this asset instance to the given model and
21
     * sets the type and locale to the given values and
22
     * returns the model with the asset relationship.
23
     *
24
     * @param HasAsset $model
25
     * @param string $type
26
     * @param null|string $locale
27
     * @return HasAsset
28
     * @throws AssetUploadException
29
     */
30
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
31
    {
32
        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

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

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