Test Setup Failed
Push — 0.9 ( dd36a2 )
by Ben
05:07
created

Asset   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 201
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 54
c 4
b 0
f 1
dl 0
loc 201
rs 9.68
wmc 34

20 Methods

Rating   Name   Duplication   Size   Complexity  
A getHumanReadableSize() 0 3 1
A getSize() 0 3 1
A getData() 0 5 2
A getExtensionType() 0 8 1
A getUrl() 0 3 2
A getPath() 0 3 2
A getImageDimensions() 0 17 4
A isImage() 0 3 1
A hasFile() 0 3 1
A getFileName() 0 5 2
A getImageWidth() 0 3 1
A getExtension() 0 3 1
A url() 0 3 1
A exists() 0 15 4
A hasData() 0 5 2
A filename() 0 3 1
A getMimeType() 0 3 1
A getImageHeight() 0 3 1
A getMediaPropertyValue() 0 7 2
A registerMediaConversions() 0 15 3
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Str;
7
use Illuminate\Support\Facades\DB;
8
use Spatie\MediaLibrary\InteractsWithMedia;
9
use Spatie\MediaLibrary\MediaCollections\Models\Media;
10
use Illuminate\Database\Eloquent\Model;
11
use Spatie\MediaLibrary\HasMedia;
12
13
class Asset extends Model implements HasMedia
14
{
15
    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...
16
17
    /**
18
     * The asset model always has one collection type. Different collection types for
19
     * the owning model are set on the asset model instead of the media model.
20
     */
21
    const MEDIA_COLLECTION = 'default';
22
23
    /**
24
     * Proxy for the data values on the associated pivot. This is the context data
25
     * relevant and unique for each owner - asset relation.
26
     */
27
    public function hasData(string $key): bool
28
    {
29
        if(!$this->pivot) return false;
0 ignored issues
show
Bug introduced by
The property pivot 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...
30
31
        return $this->pivot->hasData($key);
32
    }
33
34
    /**
35
     * Proxy for the data values on the associated pivot. This is the context data
36
     * relevant and unique for each owner - asset relation.
37
     */
38
    public function getData(string $key, $default = null)
39
    {
40
        if(!$this->pivot) return $default;
0 ignored issues
show
Bug introduced by
The property pivot 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...
41
42
        return $this->pivot->getData($key, $default);
43
    }
44
45
    /**
46
     * Return path of the media file. In case the passed conversion
47
     * does not exist, the path to the original is returned.
48
     */
49
    public function getPath($conversionName = ''): ?string
50
    {
51
        return $this->getFirstMediaPath(self::MEDIA_COLLECTION, $conversionName) ?: null;
52
    }
53
54
    /**
55
     * Return url of the media file. In case the passed conversion
56
     * does not exist, the url to the original is returned.
57
     */
58
    public function getUrl(string $conversionName = ''): ?string
59
    {
60
        return $this->getFirstMediaUrl(self::MEDIA_COLLECTION, $conversionName) ?: null;
61
    }
62
63
    /**
64
     * Return filename of the media file. In case the passed conversion
65
     * does not exist, the name to the original is returned.
66
     */
67
    public function getFileName(string $conversionName = ''): ?string
68
    {
69
        if (!$path = $this->getFirstMediaPath(self::MEDIA_COLLECTION, $conversionName)) return null;
70
71
        return basename($path);
72
    }
73
74
    /**
75
     * Checks if the conversion exists. It checks if file
76
     * exists as media record and on the server
77
     */
78
    public function exists(string $conversionName = ''): bool
79
    {
80
        // In case there is no media model attached to our Asset.
81
        if (!$path = $this->getFirstMediaPath(self::MEDIA_COLLECTION, $conversionName)) {
82
            return false;
83
        }
84
85
        // When we specifically check if a conversion exists, we need to explicitly check if the provided path is that of the conversion.
86
        // This is because Media Library falls back to returning the original path if the converted file does not exist.
87
        if ($conversionName) {
88
            $originalPath = $this->getFirstMediaPath(self::MEDIA_COLLECTION, '');
89
            if ($originalPath == $path) return false;
90
        }
91
92
        return file_exists($path);
93
    }
94
95
    public function getSize(): int
96
    {
97
        return $this->getMediaPropertyValue('size', 0);
98
    }
99
100
    public function getHumanReadableSize(): string
101
    {
102
        return $this->getMediaPropertyValue('human_readable_size', '');
103
    }
104
105
    public function getMimeType(): ?string
106
    {
107
        return $this->getMediaPropertyValue('mime_type');
108
    }
109
110
    public function getExtension(): string
111
    {
112
        return $this->getMediaPropertyValue('extension', '');
113
    }
114
115
    public function getExtensionType(): string
116
    {
117
        return match (strtolower($this->getExtension())) {
118
            'xls', 'xlsx', 'numbers', 'sheets' => 'spreadsheet',
119
            'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp' => 'image',
120
            'pdf' => 'pdf',
121
            'mp4', 'webm', 'mpeg', 'mov' => 'video',
122
            default => 'file'
123
        };
124
    }
125
126
    public function isImage(): bool
127
    {
128
        return $this->getExtensionType() == 'image';
129
    }
130
131
    public function getImageWidth(string $conversionName = ''): ?int
132
    {
133
        return $this->getImageDimensions($conversionName)['width'];
134
    }
135
136
    public function getImageHeight(string $conversionName = ''): ?int
137
    {
138
        return $this->getImageDimensions($conversionName)['height'];
139
    }
140
141
    private function getImageDimensions(string $conversionName = ''): array
142
    {
143
        $result = [
144
            'width' => null,
145
            'height' => null,
146
        ];
147
148
        if(!$this->isImage() || !$this->exists($conversionName)) {
149
            return $result;
150
        }
151
152
        if($dimensions = getimagesize($this->getPath($conversionName))) {
153
            $result['width'] = $dimensions[0];
154
            $result['height'] = $dimensions[1];
155
        }
156
157
        return $result;
158
    }
159
160
    private function getMediaPropertyValue(string $property, $default = null)
161
    {
162
        if (!$mediaModel = $this->getFirstMedia(self::MEDIA_COLLECTION)) {
163
            return $default;
164
        }
165
166
        return $mediaModel->{$property};
167
    }
168
169
    /**
170
     * @deprecated Use getFileName instead
171
     */
172
    public function filename($size = ''): string
173
    {
174
        return $this->getFileName($size);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getFileName($size) could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
175
    }
176
177
    /**
178
     * @deprecated use getUrl() instead
179
     */
180
    public function url($size = ''): string
181
    {
182
        return $this->getUrl($size);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getUrl($size) could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
183
    }
184
185
    /**
186
     * @deprecated use exists() instead
187
     */
188
    public function hasFile(): bool
189
    {
190
        return $this->exists();
191
    }
192
193
    /**
194
     * Register the conversions that should be performed.
195
     *
196
     * @param Media|null $media
197
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
198
     */
199
    public function registerMediaConversions(Media $media = null): void
200
    {
201
        $conversions = config('thinktomorrow.assetlibrary.conversions');
202
203
        foreach ($conversions as $key => $value) {
204
            $this->addMediaConversion($key)
205
                ->width($value['width'])
206
                ->height($value['height'])
207
                ->keepOriginalImageFormat();
208
//                ->optimize();
209
        }
210
211
        if (config('thinktomorrow.assetlibrary.allowCropping')) {
212
            $this->addMediaConversion('cropped')
213
                ->keepOriginalImageFormat();
214
//                ->optimize();
215
        }
216
    }
217
}
218