Passed
Pull Request — master (#24)
by Philippe
03:23
created

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