Passed
Pull Request — master (#26)
by Philippe
05:42
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\Interfaces\HasAsset;
12
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
13
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
14
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
15
16
class Asset extends Model implements HasAsset
17
{
18
    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...
19
20
    private $order;
21
22
    /**
23
     * Attaches this asset instance to the given model and
24
     * sets the type and locale to the given values and
25
     * returns the model with the asset relationship.
26
     *
27
     * @param HasAsset $model
28
     * @param string $type
29
     * @param null|string $locale
30
     * @return HasAsset
31
     * @throws AssetUploadException
32
     */
33 38
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
34
    {
35 38
        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

35
        if ($model->/** @scrutinizer ignore-call */ assets()->get()->contains($this)) {
Loading history...
36 1
            throw AssetUploadException::create();
37
        }
38
39 38
        $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
40
41 38
        $locale = $locale ?? config('app.fallback_locale');
42
43 38
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale, 'order' => $this->order]);
44
45 38
        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

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