Passed
Push — master ( 7bf00b...1d74eb )
by Philippe
04:55
created

Asset::getSize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Facades\DB;
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\CorruptMediaException;
13
14
class Asset extends Model implements HasMedia
15
{
16
    use HasMediaTrait;
0 ignored issues
show
introduced by
The trait Spatie\MediaLibrary\HasMedia\HasMediaTrait requires some properties which are not provided by Thinktomorrow\AssetLibrary\Asset: $fallbackPath, $each, $mediaConversionRegistrations, $forceDeleting, $fallbackUrl, $media, $collection_name
Loading history...
17
18
    private $order;
0 ignored issues
show
introduced by
The private property $order is not used, and could be removed.
Loading history...
19
20
    /**
21
     * @return bool
22
     */
23 1
    public function hasFile(): bool
24
    {
25 1
        return (bool) $this->url();
26
    }
27
28
    /**
29
     * @param string $size
30
     * @return string
31
     */
32 17
    public function filename($size = ''): string
33
    {
34 17
        return basename($this->url($size));
35
    }
36
37 1
    public function exists(): bool
38
    {
39 1
        return true;
40
    }
41
42
    /**
43
     * @param string $size
44
     * @return string
45
     */
46 50
    public function url($size = ''): string
47
    {
48 50
        $media = $this->getFirstMedia();
49
50 50
        if ($media == null) {
51 1
            return '';
52
        }
53
54 49
        return $media->getUrl($size);
55
    }
56
57
    /**
58
     * @return bool|string
59
     */
60 2
    public function getExtensionForFilter()
61
    {
62 2
        if ($extension = $this->getExtensionType()) {
63 1
            return $extension;
64
        }
65
66 1
        return '';
67
    }
68
69
    /**
70
     * @return null|string
71
     * @throws CorruptMediaException
72
     */
73 2
    public function getExtensionType(): ?string
74
    {
75 2
        $media = $this->getMedia()->first();
76
77 2
        if ($media == null) {
78 1
            throw CorruptMediaException::missingMediaRelation($this->id);
79
        }
80
81 1
        $extension = explode('.', $media->file_name);
82 1
        $extension = end($extension);
83
84 1
        if ($extension) {
85 1
            if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
86 1
                return 'xls';
87
            }
88 1
            if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
89 1
                return 'image';
90
            }
91 1
            if (strtolower($extension) === 'pdf') {
92 1
                return 'pdf';
93
            }
94
        }
95
96 1
        return null;
97
    }
98
99
    /**
100
     * @return string
101
     */
102 2
    public function getMimeType(): string
103
    {
104 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
105
    }
106
107
    /**
108
     * @return bool
109
     */
110 7
    public function isMediaEmpty(): bool
111
    {
112 7
        return $this->getMedia()->isEmpty();
113
    }
114
115
    /**
116
     * @return string
117
     */
118 2
    public function getSize(): string
119
    {
120 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
121
    }
122
123
    /**
124
     * @param string|null $size
125
     * @return string
126
     */
127 3
    public function getDimensions($size = null): string
128
    {
129 3
        if ($this->isMediaEmpty()) {
130 1
            return '';
131
        }
132
133
        //TODO Check the other sizes as well
134 2
        if ($size === 'cropped') {
135 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
136
137 1
            return $dimensions[0].' x'.$dimensions[1];
138
        }
139
140 1
        $dimensions = '';
141 1
        $file_path = public_path($this->url($size??''));
142 1
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
143
144 1
            $imagesize = getimagesize($file_path);
145
146 1
            $dimensions = $imagesize[0].' x '.$imagesize[1];
147
        }
148
149 1
        return $dimensions;
150
    }
151
152
    /**
153
     * @param string|null $size
154
     * @return string
155
     */
156 3
    public function getWidth($size = null): string
157
    {
158 3
        if ($this->isMediaEmpty()) {
159 1
            return '';
160
        }
161
162
        //TODO Check the other sizes as well
163 2
        if ($size === 'cropped') {
164 1
            $width = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
165
166 1
            return $width[0];
167
        }
168
169 1
        $width = '';
170 1
        $file_path = public_path($this->url($size??''));
171 1
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
172
173 1
            $imagesize = getimagesize($file_path);
174
175 1
            $width = $imagesize[0];
176
        }
177
178 1
        return $width;
179
    }
180
181
    /**
182
     * @param string|null $size
183
     * @return string
184
     */
185 3
    public function getHeight($size = null): string
186
    {
187 3
        if ($this->isMediaEmpty()) {
188 1
            return '';
189
        }
190
191
        //TODO Check the other sizes as well
192 2
        if ($size === 'cropped') {
193 1
            $height = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
194
195 1
            return trim($height[1]);
196
        }
197
198 1
        $height = '';
199 1
        $file_path = public_path($this->url($size??''));
200 1
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
201
202 1
            $imagesize = getimagesize($file_path);
203
204 1
            $height = $imagesize[1];
205
        }
206
207 1
        return $height;
208
    }
209
210
211
    /**
212
     * @param UploadedFile $file
0 ignored issues
show
Bug introduced by
The type Thinktomorrow\AssetLibrary\UploadedFile 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...
213
     * @return bool
214
     */
215 3
    private static function isImage($file): bool
216
    {
217 3
        return Str::before($file->mime_type, '/') === 'image';
218
    }
219
220 1
    public function isUsed()
221
    {
222 1
        $pivots = DB::table('asset_pivots')->where('asset_id', $this->id)->where('unused', false)->get();
223
224 1
        return ! $pivots->isEmpty();
225
    }
226
227
    public function isUnused()
228
    {
229
        $pivots = DB::table('asset_pivots')->where('asset_id', $this->id)->where('unused', false)->get();
230
231
        return $pivots->isEmpty();
232
    }
233
234
    /**
235
     * @param $width
236
     * @param $height
237
     * @param $x
238
     * @param $y
239
     * @return $this
240
     * @throws ConfigException
241
     */
242 2
    public function crop($width, $height, $x, $y)
243
    {
244 2
        if (! config('thinktomorrow.assetlibrary.allowCropping')) {
245 1
            throw ConfigException::croppingDisabled();
246
        }
247 1
        $this->media[0]->manipulations = [
0 ignored issues
show
Bug introduced by
The property media does not seem to exist on Thinktomorrow\AssetLibrary\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...
248
            'cropped'   => [
249 1
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
250
            ],
251
        ];
252
253 1
        $this->media[0]->save();
254
255 1
        return $this;
256
    }
257
258
    /**
259
     * Register the conversions that should be performed.
260
     *
261
     * @param Media|null $media
262
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
263
     */
264 49
    public function registerMediaConversions(Media $media = null)
265
    {
266 49
        $conversions = config('thinktomorrow.assetlibrary.conversions');
267
268 49
        foreach ($conversions as $key => $value) {
269 49
            $this->addMediaConversion($key)
270 49
                ->width($value['width'])
271 49
                ->height($value['height'])
272 49
                ->keepOriginalImageFormat()
273 49
                ->optimize();
274
        }
275
276 49
        if (config('thinktomorrow.assetlibrary.allowCropping')) {
277 1
            $this->addMediaConversion('cropped')
278 1
                ->keepOriginalImageFormat()
279 1
                ->optimize();
280
        }
281 49
    }
282
}
283