Asset   B
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 271
Duplicated Lines 0 %

Test Coverage

Coverage 96.97%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 87
dl 0
loc 271
ccs 96
cts 99
cp 0.9697
rs 8.8798
c 4
b 0
f 1
wmc 44

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getExtensionForFilter() 0 7 2
A url() 0 9 2
A exists() 0 3 1
A filename() 0 3 1
A hasFile() 0 3 2
A getSize() 0 3 2
B getExtensionType() 0 29 7
A getHeight() 0 23 5
A getWidth() 0 23 5
A isMediaEmpty() 0 3 1
A isImage() 0 3 1
A crop() 0 14 2
A getDimensions() 0 23 6
A getMimeType() 0 3 2
A isUsed() 0 5 1
A registerMediaConversions() 0 16 3
A isUnused() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Asset often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Asset, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Thinktomorrow\AssetLibrary;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Facades\DB;
7
use Spatie\MediaLibrary\InteractsWithMedia;
8
use Spatie\MediaLibrary\MediaCollections\Models\Media;
9
use Illuminate\Database\Eloquent\Model;
10
use Spatie\MediaLibrary\HasMedia;
11
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
12
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
13
14
class Asset extends Model implements HasMedia
15
{
16
    use InteractsWithMedia;
0 ignored issues
show
introduced by
The trait Spatie\MediaLibrary\InteractsWithMedia requires some properties which are not provided by Thinktomorrow\AssetLibrary\Asset: $fallbackPath, $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 ($this->getFirstMediaPath() && file_exists($this->getFirstMediaPath()));
26
    }
27
28
    /**
29
     * @param string $size
30
     * @return string
31
     */
32 17
    public function filename($size = ''): string
33
    {
34 17
        return basename($this->getFirstMediaPath('default', $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
        // Remove any appends (query)
85 1
        if(strpos($extension, '?')) {
86 1
            $extension = substr($extension, 0, strpos($extension, '?'));
87
        }
88 1
89 1
        if ($extension) {
90
            if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
91 1
                return 'xls';
92 1
            }
93
            if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
94
                return 'image';
95
            }
96 1
            if (strtolower($extension) === 'pdf') {
97
                return 'pdf';
98
            }
99
        }
100
101
        return null;
102 2
    }
103
104 2
    /**
105
     * @return string
106
     */
107
    public function getMimeType(): string
108
    {
109
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
110 7
    }
111
112 7
    /**
113
     * @return bool
114
     */
115
    public function isMediaEmpty(): bool
116
    {
117
        return $this->getMedia()->isEmpty();
118 2
    }
119
120 2
    /**
121
     * @return string
122
     */
123
    public function getSize(): string
124
    {
125
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
126
    }
127 3
128
    /**
129 3
     * @param string|null $size
130 1
     * @return string
131
     */
132
    public function getDimensions($size = null): string
133
    {
134 2
        if ($this->isMediaEmpty()) {
135 1
            return '';
136
        }
137 1
138
        //TODO Check the other sizes as well
139
        if ($size === 'cropped') {
140 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
141 1
142 1
            return $dimensions[0].' x'.$dimensions[1];
143
        }
144 1
145
        $dimensions = '';
146 1
        $file_path = $this->getFirstMediaPath('default', $size??'');
147
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
148
149 1
            if($imagesize = getimagesize($file_path)) {
150
                $dimensions = $imagesize[0].' x '.$imagesize[1];
151
            }
152
        }
153
154
        return $dimensions;
155
    }
156 3
157
    /**
158 3
     * @param string|null $size
159 1
     * @return string
160
     */
161
    public function getWidth($size = null): string
162
    {
163 2
        if ($this->isMediaEmpty()) {
164 1
            return '';
165
        }
166 1
167
        //TODO Check the other sizes as well
168
        if ($size === 'cropped') {
169 1
            $width = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
170 1
171 1
            return $width[0];
172
        }
173 1
174
        $width = '';
175 1
        $file_path = $this->getFirstMediaPath('default', $size??'');
176
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
177
178 1
            $imagesize = getimagesize($file_path);
179
180
            $width = $imagesize[0];
181
        }
182
183
        return $width;
184
    }
185 3
186
    /**
187 3
     * @param string|null $size
188 1
     * @return string
189
     */
190
    public function getHeight($size = null): string
191
    {
192 2
        if ($this->isMediaEmpty()) {
193 1
            return '';
194
        }
195 1
196
        //TODO Check the other sizes as well
197
        if ($size === 'cropped') {
198 1
            $height = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
199 1
200 1
            return trim($height[1]);
201
        }
202 1
203
        $height = '';
204 1
        $file_path = $this->getFirstMediaPath('default', $size??'');
205
        if (self::isImage($this->getMedia()[0]) && file_exists($file_path)) {
206
207 1
            $imagesize = getimagesize($file_path);
208
209
            $height = $imagesize[1];
210
        }
211
212
        return $height;
213
    }
214
215 3
216
    /**
217 3
     * @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...
218
     * @return bool
219
     */
220 1
    private static function isImage($file): bool
221
    {
222 1
        return Str::before($file->mime_type, '/') === 'image';
223
    }
224 1
225
    public function isUsed()
226
    {
227
        $pivots = DB::table('asset_pivots')->where('asset_id', $this->id)->where('unused', false)->get();
228
229
        return ! $pivots->isEmpty();
230
    }
231
232
    public function isUnused()
233
    {
234
        $pivots = DB::table('asset_pivots')->where('asset_id', $this->id)->where('unused', false)->get();
235
236
        return $pivots->isEmpty();
237
    }
238
239
    /**
240
     * @param $width
241
     * @param $height
242 2
     * @param $x
243
     * @param $y
244 2
     * @return $this
245 1
     * @throws ConfigException
246
     */
247 1
    public function crop($width, $height, $x, $y)
248
    {
249 1
        if (! config('thinktomorrow.assetlibrary.allowCropping')) {
250
            throw ConfigException::croppingDisabled();
251
        }
252
        $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...
253 1
            'cropped'   => [
254
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
255 1
            ],
256
        ];
257
258
        $this->media[0]->save();
259
260
        return $this;
261
    }
262
263
    /**
264 49
     * Register the conversions that should be performed.
265
     *
266 49
     * @param Media|null $media
267
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
268 49
     */
269 49
    public function registerMediaConversions(Media $media = null): void
270 49
    {
271 49
        $conversions = config('thinktomorrow.assetlibrary.conversions');
272 49
273 49
        foreach ($conversions as $key => $value) {
274
            $this->addMediaConversion($key)
275
                ->width($value['width'])
276 49
                ->height($value['height'])
277 1
                ->keepOriginalImageFormat()
278 1
                ->optimize();
279 1
        }
280
281 49
        if (config('thinktomorrow.assetlibrary.allowCropping')) {
282
            $this->addMediaConversion('cropped')
283
                ->keepOriginalImageFormat()
284
                ->optimize();
285
        }
286
    }
287
}
288