Passed
Pull Request — master (#38)
by Philippe
04:33 queued 46s
created

Asset::removeByIds()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.6111
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5
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 42
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
31
    {
32 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

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