Passed
Push — 0.6 ( fa70f4...7db85c )
by Philippe
06:36
created

Asset::filename()   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
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 41
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
31
    {
32 41
        if ($model->assetRelation()->get()->contains($this)) {
0 ignored issues
show
Bug introduced by
The method assetRelation() 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 */ assetRelation()->get()->contains($this)) {
Loading history...
33 1
            throw AssetUploadException::create();
34
        }
35
36 41
        $locale = $locale ?? config('app.fallback_locale');
37
38 41
        $model->assetRelation()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
39
40 41
        return $model->load('assetRelation');
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

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