Passed
Pull Request — master (#26)
by Philippe
05:12
created

Asset::removeFile()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

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