Completed
Pull Request — master (#38)
by Philippe
08:29 queued 04:23
created

Asset::filename()   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
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Spatie\MediaLibrary\Models\Media;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
8
use Thinktomorrow\AssetLibrary\Interfaces\HasAsset;
9
use Thinktomorrow\AssetLibrary\Exceptions\ConfigException;
10
use Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException;
11
use Thinktomorrow\AssetLibrary\Exceptions\CorruptMediaException;
12
13
class Asset extends Model implements HasAsset
14
{
15
    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: $fallbackPath, $each, $mediaConversionRegistrations, $forceDeleting, $fallbackUrl, $media, $collection_name
Loading history...
16
17
    private $order;
18
19
    /**
20
     * Attaches this asset instance to the given model and
21
     * sets the type and locale to the given values and
22
     * returns the model with the asset relationship.
23
     *
24
     * @param HasAsset $model
25
     * @param string $type
26
     * @param null|string $locale
27
     * @return HasAsset
28
     * @throws AssetUploadException
29
     */
30 42
    public function attachToModel(HasAsset $model, $type = '', $locale = null): HasAsset
31
    {
32 42
        if ($model->assetRelation()->get()->contains($this)) {
0 ignored issues
show
Bug introduced by
The method assetRelation() 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

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

40
        return $model->/** @scrutinizer ignore-call */ load('assetRelation');
Loading history...
41
    }
42
43
    /**
44
     * @return bool
45
     */
46 1
    public function hasFile(): bool
47
    {
48 1
        return (bool) $this->url();
49
    }
50
51
    /**
52
     * @param string $size
53
     * @return string
54
     */
55 17
    public function filename($size = ''): string
56
    {
57 17
        return basename($this->url($size));
58
    }
59
60
    /**
61
     * @param string $size
62
     * @return string
63
     */
64 51
    public function url($size = ''): string
65
    {
66 51
        $media = $this->getMedia()->first();
67
68 51
        if ($media == null) {
69 1
            throw CorruptMediaException::corrupt($this->id);
70
        }
71
72 50
        return $media->getUrl($size);
73
    }
74
75
    /**
76
     * @return bool|string
77
     */
78 2
    public function getExtensionForFilter()
79
    {
80 2
        if ($extension = $this->getExtensionType()) {
81 1
            return $extension;
82
        }
83
84 1
        return '';
85
    }
86
87
    /**
88
     * @return null|string
89
     * @throws CorruptMediaException
90
     */
91 2
    public function getExtensionType(): ?string
92
    {
93 2
        $media = $this->getMedia()->first();
94
95 2
        if ($media == null) {
96 1
            throw CorruptMediaException::corrupt($this->id);
97
        }
98
99 1
        $extension = explode('.', $media->file_name);
100 1
        $extension = end($extension);
101
102 1
        if ($extension) {
103 1
            if (in_array(strtolower($extension), ['xls', 'xlsx', 'numbers', 'sheets'])) {
104 1
                return 'xls';
105
            }
106 1
            if (in_array(strtolower($extension), ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
107 1
                return 'image';
108
            }
109 1
            if (strtolower($extension) === 'pdf') {
110 1
                return 'pdf';
111
            }
112
        }
113
114 1
        return null;
115
    }
116
117
    /**
118
     * @return string
119
     */
120 2
    public function getMimeType(): string
121
    {
122 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
123
    }
124
125
    /**
126
     * @return bool
127
     */
128 5
    public function isMediaEmpty(): bool
129
    {
130 5
        return $this->getMedia()->isEmpty();
131
    }
132
133
    /**
134
     * @return string
135
     */
136 2
    public function getSize(): string
137
    {
138 2
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
139
    }
140
141
    /**
142
     * @param string|null $size
143
     * @return string
144
     */
145 3
    public function getDimensions($size = null): string
146
    {
147 3
        if ($this->isMediaEmpty()) {
148 1
            return '';
149
        }
150
151
        //TODO Check the other sizes as well
152 2
        if ($size === 'cropped') {
153 1
            $dimensions = explode(',', $this->getMedia()[0]->manipulations['cropped']['manualCrop']);
154
155 1
            return $dimensions[0].' x'.$dimensions[1];
156
        }
157
158 1
        return $this->getMedia()[0]->getCustomProperty('dimensions');
159
    }
160
161
    /**
162
     * @param $width
163
     * @param $height
164
     * @param $x
165
     * @param $y
166
     * @return $this
167
     * @throws ConfigException
168
     */
169 2
    public function crop($width, $height, $x, $y)
170
    {
171 2
        if (! config('assetlibrary.allowCropping')) {
172 1
            throw ConfigException::create();
173
        }
174 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...
175
            'cropped'   => [
176 1
                'manualCrop' => $width.', '.$height.', '.$x.', '.$y,
177
            ],
178
        ];
179
180 1
        $this->media[0]->save();
181
182 1
        return $this;
183
    }
184
185
    /**
186
     * Register the conversions that should be performed.
187
     *
188
     * @param Media|null $media
189
     * @throws \Spatie\Image\Exceptions\InvalidManipulation
190
     */
191 48
    public function registerMediaConversions(Media $media = null)
192
    {
193 48
        $conversions = config('assetlibrary.conversions');
194
195 48
        foreach ($conversions as $key => $value) {
196 48
            $this->addMediaConversion($key)
197 48
                ->width($value['width'])
198 48
                ->height($value['height'])
199 48
                ->keepOriginalImageFormat()
200 48
                ->optimize();
201
        }
202
203 48
        if (config('assetlibrary.allowCropping')) {
204 1
            $this->addMediaConversion('cropped')
205 1
                ->keepOriginalImageFormat()
206 1
                ->optimize();
207
        }
208 48
    }
209
210 14
    public function setOrder($order)
211
    {
212 14
        $this->order = $order;
213
214 14
        return $this;
215
    }
216
}
217