Test Failed
Pull Request — master (#24)
by Philippe
02:54
created

Asset::remove()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
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\HasMedia;
10
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
11
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
12
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
13
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
14
15
/**
16
 * @property mixed media
17
 */
18
class Asset extends Model implements HasMedia
19
{
20
    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, $collection_name
Loading history...
21
22
    private $order;
23
24
    /**
25
     * Attaches this asset instance to the given model and
26
     * sets the type and locale to the given values and
27
     * returns the model with the asset relationship.
28
     *
29
     * @param Model $model
30
     * @param string $type
31
     * @param null|string $locale
32
     * @return Model
33
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
34 37
     */
35
    public function attachToModel(Model $model, $type = '', $locale = null): Model
36 37
    {
37 1
        if ($model->assets()->get()->contains($this)) {
38
            throw AssetUploadException::create();
39
        }
40 37
41
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
0 ignored issues
show
Bug introduced by
The method where() does not exist on null. ( Ignorable by Annotation )

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

41
        $model->assets->/** @scrutinizer ignore-call */ 
42
                        where('pivot.type', $type)->where('pivot.locale', $locale);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
42 37
43
        $locale = $locale ?? config('app.locale');
44 37
45
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
46 37
47
        return $model->load('assets');
48
    }
49
50
    /**
51
     * @return bool
52 1
     */
53
    public function hasFile(): bool
54 1
    {
55
        return (bool) $this->getFileUrl();
56
    }
57
58
    /**
59
     * @param string $size
60
     * @return string
61 13
     */
62
    public function getFilename($size = ''): string
63 13
    {
64
        return basename($this->getFileUrl($size));
65
    }
66
67
    /**
68
     * @param string $size
69
     * @return string
70 46
     */
71
    public function getFileUrl($size = ''): string
72 46
    {
73
        $media = $this->getMedia()->first();
74 46
75 1
        if ($media == null) {
76
            throw CorruptMediaException::corrupt($this->id);
77 45
        }
78
79
        return $media->getUrl($size);
80 46
    }
81 1
82
    /**
83
     * Returns the image url or a fallback specific per filetype.
84 45
     *
85
     * @param string $type
86
     * @return string
87
     */
88
    public function getImageUrl($type = ''): string
89
    {
90
        if ($this->getMedia()->isEmpty()) {
91
            return asset('assets/back/img/other.png');
92
        }
93 9
        $extension = $this->getExtensionType();
94
        if ($extension === 'image') {
95 9
            return $this->getFileUrl($type);
96 1
        } elseif ($extension) {
97
            return asset('assets/back/img/'.$extension.'.png');
98 8
        }
99 8
100 7
        return asset('assets/back/img/other.png');
101 1
    }
102 1
103
    /**
104
     * @return bool|string
105 1
     */
106
    public function getExtensionForFilter()
107
    {
108
        if ($extension = $this->getExtensionType()) {
109
            return $extension;
110
        }
111 2
112
        return '';
113 2
    }
114 2
115
    /**
116
     * @return string|null
117 1
     */
118
    public function getExtensionType(): ?string
119
    {
120
        $extension = explode('.', $this->getMedia()[0]->file_name);
121
        $extension = end($extension);
122
123 10
        if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
124
            return 'xls';
125 10
        }
126 10
        if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
127
            return 'image';
128 10
        }
129 1
        if (strtolower($extension) === 'pdf') {
130
            return 'pdf';
131 10
        }
132 9
133
        return null;
134 3
    }
135 2
136
    /**
137
     * @return string
138 2
     */
139
    public function getMimeType(): string
140
    {
141
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
142
    }
143
144 2
    /**
145
     * @return bool
146 2
     */
147
    public function isMediaEmpty(): bool
148
    {
149
        return $this->getMedia()->isEmpty();
150
    }
151
152 5
    /**
153
     * @return string
154 5
     */
155
    public function getSize(): string
156
    {
157
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
158
    }
159
160 2
    /**
161
     * @param null $size
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $size is correct as it would always require null to be passed?
Loading history...
162 2
     * @return string
163
     */
164
    public function getDimensions($size = null): string
165
    {
166
167
        if ($this->isMediaEmpty()) {
168
            return '';
169 3
        }
170
171 3
        //TODO Check the other sizes as well
172 1
        if ($size === 'cropped') {
173
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
174
175
            return $dimensions[0].' x'.$dimensions[1];
176 2
        }
177 1
178
        return $this->getMedia()[0]->getCustomProperty('dimensions');
179 1
    }
180
181
    /**
182 1
     * Removes one or more assets by their ids.
183
     * @param $imageIds
184
     */
185
    public static function remove($imageIds)
186
    {
187
        if (is_array($imageIds)) {
188
            foreach ($imageIds as $id) {
189 5
                self::removeFile($id);
190
            }
191 5
        } else {
192 2
            self::removeFile($imageIds);
193 2
        }
194 1
    }
195
196
    /**
197 1
     * Removes itself.
198 1
     */
199
    public function removeSelf()
200 1
    {
201 1
        $this->removeFile($this->id);
202 1
    }
203
204
    private static function removeFile($id)
205
    {
206 2
        if (! $id) {
207
            return;
208
        }
209 4
210 1
        $asset = self::find($id)->first();
211
212
        $media = $asset->media;
213 3
214 3
        foreach ($media as $file) {
215
            if (! is_file(public_path($file->getUrl())) || ! is_writable(public_path($file->getUrl()))) {
216 3
                return false;
217 3
            }
218 3
        }
219
        $asset->delete();
220
    }
221
222 3
    /**
223
     * Returns a collection of all the assets in the library.
224 5
     * @return \Illuminate\Support\Collection
225
     */
226
    public static function getAllAssets(): Collection
227
    {
228
        return self::all()->sortByDesc('created_at');
229
    }
230 6
231
    /**
232 6
     * @param $width
233
     * @param $height
234
     * @param $x
235
     * @param $y
236
     * @return $this
237
     * @throws ConfigException
238
     */
239
    public function crop($width, $height, $x, $y)
240
    {
241
        if (! config('assetlibrary.allowCropping')) {
242
            throw ConfigException::create();
243 2
        }
244
        $this->media[0]->manipulations = [
245 2
            'cropped'   => [
246 1
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
247
            ],
248 1
        ];
249
250 1
        $this->media[0]->save();
251
252
        return $this;
253
    }
254 1
255
    /**
256 1
     * Register the conversions that should be performed.
257
     *
258
     * @param Media|null $media
259
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
260
     */
261
    public function registerMediaConversions(Media $media = null): void
262
    {
263
        $conversions = config('assetlibrary.conversions');
264
265 61
        foreach ($conversions as $key => $value) {
266
            $this->addMediaConversion($key)
267 61
                ->width($value['width'])
268 61
                ->height($value['height'])
269
                ->sharpen(15)
270 61
                ->keepOriginalImageFormat()
271 61
                ->optimize();
272 1
        }
273
274 61
        if (config('assetlibrary.allowCropping')) {
275
            $this->addMediaConversion('cropped')
276
                ->sharpen(15)
277 61
                ->keepOriginalImageFormat()
278 61
                ->optimize();
279 61
        }
280 61
    }
281 61
282 61
    public function setOrder($order)
283
    {
284
        $this->order = $order;
285 61
286 1
        return $this;
287 1
    }
288
}
289