Passed
Push — 0.6 ( 76034f...e546bd )
by Philippe
19:31
created

AssetTrait::getFilename()   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 2
crap 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Traits;
4
5
use Thinktomorrow\AssetLibrary\Models\Asset;
6
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
7
use Thinktomorrow\AssetLibrary\Models\AssetLibrary;
8
use Thinktomorrow\AssetLibrary\Models\AssetUploader;
9
10
trait AssetTrait
11
{
12
    use HasMediaTrait;
13
14 52
    public static function bootAssetTrait()
15
    {
16
        static::deleted(function($model){
0 ignored issues
show
Bug introduced by
The method deleted() does not exist on Thinktomorrow\AssetLibrary\Traits\AssetTrait. Did you maybe mean deleteMedia()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

16
        static::/** @scrutinizer ignore-call */ 
17
                deleted(function($model){

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
17
            $model->assets->each(function($asset) use($model){
18 1
               $model->assets()->updateExistingPivot($asset->id, ['unused'=> true]);
19 1
            });
20 52
        });
21 52
    }
22
23
    /**
24
     * @return mixed
25
     */
26 52
    public function assets()
27
    {
28 52
        return $this->morphToMany(Asset::class, 'entity', 'asset_pivots')->withPivot('type', 'locale', 'order')->orderBy('order');
0 ignored issues
show
Bug introduced by
It seems like morphToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

28
        return $this->/** @scrutinizer ignore-call */ morphToMany(Asset::class, 'entity', 'asset_pivots')->withPivot('type', 'locale', 'order')->orderBy('order');
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
29
    }
30
31
    /**
32
     * @param string $type
33
     * @param string|null $locale
34
     * @return bool
35
     */
36 4
    public function hasFile($type = '', $locale = null): bool
37
    {
38 4
        $filename = $this->getFilename($type, $locale);
39
40 4
        return (bool) $filename && basename($filename) != 'other.png';
41
    }
42
43
    /**
44
     * @param string $type
45
     * @param string|null $locale
46
     * @return string
47
     */
48 13
    public function getFilename($type = '', $locale = null): string
49
    {
50 13
        return basename($this->getFileUrl($type, '', $locale));
51
    }
52
53
    /**
54
     * @param string $type
55
     * @param string $size
56
     * @param string|null $locale
57
     * @return string
58
     */
59 39
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
60
    {
61 39
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
62 3
            return null;
63
        }
64
65 38
        $locale = $this->normalizeLocaleString($locale);
66
67 38
        $assets = $this->assets->where('pivot.type', $type);
68
69 38
        if ($locale && $assets->count() > 1) {
70 10
            $assets = $assets->where('pivot.locale', $locale);
71
        }
72
73 38
        if ($assets->isEmpty()) {
74 1
            return null;
75
        }
76
77 38
        return $assets->first()->getFileUrl($size);
78
    }
79
80
    /**
81
     * Adds a file to this model, accepts a type and locale to be saved with the file.
82
     *
83
     * @param $file
84
     * @param string $type
85
     * @param string|null $locale
86
     * @param null $filename
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $filename is correct as it would always require null to be passed?
Loading history...
87
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
88
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
89
     */
90 23
    public function addFile($file, $type = '', $locale = null, $filename = null)
91
    {
92 23
        if (is_iterable($file)) {
93 2
            return $this->addFiles($file, $type, $locale);
94
        } else {
95 23
            $locale = $this->normalizeLocaleString($locale);
96
97 23
            if (is_string($file)) {
98 5
                $asset = AssetUploader::uploadFromBase64($file, $filename);
99
            } else {
100 18
                $asset = AssetUploader::upload($file, $filename);
101
            }
102
103 23
            if ($asset instanceof Asset) {
104 23
                $asset->attachToModel($this, $type, $locale);
0 ignored issues
show
Bug introduced by
$this of type Thinktomorrow\AssetLibrary\Traits\AssetTrait is incompatible with the type Thinktomorrow\AssetLibrary\Interfaces\HasAsset expected by parameter $model of Thinktomorrow\AssetLibra...\Asset::attachToModel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

104
                $asset->attachToModel(/** @scrutinizer ignore-type */ $this, $type, $locale);
Loading history...
105
            }
106
107 22
            return $asset;
108
        }
109
    }
110
111
    /**
112
     * Adds multiple files to this model, accepts a type and locale to be saved with the file.
113
     *
114
     * @param $files
115
     * @param string $type
116
     * @param string|null $locale
117
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
118
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
119
     */
120 7
    public function addFiles($files, $type = '', $locale = null)
121
    {
122 7
        $files  = (array) $files;
123 7
        $locale = $this->normalizeLocaleString($locale);
124 7
        $assets = collect();
125
126 7
        foreach ($files as $filename => $file) {
127 7
            $filename = is_string($filename) ? $filename : '';
128 7
            $assets->push($this->addFile($file, $type, $locale, $filename));
129
        }
130
131 7
        return $assets;
132
    }
133
134
    /**
135
     * @return mixed
136
     */
137 4
    public function getAllImages()
138
    {
139
        $images = $this->assets->filter(function ($asset) {
140 4
            return $asset->getExtensionForFilter() === 'image';
141 4
        });
142
143 4
        return $images->sortBy('pivot.order');
144
    }
145
146
    /**
147
     * Removes an asset completely.
148
     *
149
     * @param $ids
150
     */
151 1
    public function deleteAsset($ids): void
152
    {
153 1
        AssetLibrary::removeByIds($ids);
154 1
    }
155
156
    /**
157
     * Removes all assets completely.
158
     *
159
     * @param $ids
160
     */
161 1
    public function deleteAllAssets(): void
162
    {
163 1
        $this->assets->each->delete();
164 1
    }
165
166
    /**
167
     * Remove the asset and attaches a new one.
168
     *
169
     * @param $replace
170
     * @param $with
171
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
172
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
173
     */
174 2
    public function replaceAsset($replace, $with)
175
    {
176 2
        $old = $this->assets()->findOrFail($replace);
177
178 2
        $this->assets()->detach($old->id);
179 2
        $old->delete();
180
181 2
        $this->addFile(Asset::findOrFail($with), $old->pivot->type, $old->pivot->locale);
182 2
    }
183
184
    /**
185
     * @param null $type
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $type is correct as it would always require null to be passed?
Loading history...
186
     * @param string|null $locale
187
     * @return mixed
188
     */
189 11
    public function getAllFiles($type = null, $locale = null)
190
    {
191 11
        $assets = $this->assets;
192
193 11
        $locale = $this->normalizeLocaleString($locale);
194
195 11
        if ($type) {
0 ignored issues
show
introduced by
$type is of type null, thus it always evaluated to false.
Loading history...
196 6
            $assets = $assets->where('pivot.type', $type);
197
        }
198
199 11
        if ($locale) {
200 11
            $assets = $assets->where('pivot.locale', $locale);
201
        }
202
203 11
        return $assets->sortBy('pivot.order');
204
    }
205
206
    /**
207
     * @param null $type
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $type is correct as it would always require null to be passed?
Loading history...
208
     * @param $sorting
209
     */
210 2
    public function sortFiles($type, $sorting): void
211
    {
212 2
        $files = $this->getAllFiles($type);
213
        $files->each(function ($asset) use ($sorting) {
214 2
            if (in_array($asset->id, $sorting)) {
215 2
                $pivot = $this->assets->find($asset->id)->pivot;
216 2
                $pivot->order = array_search($asset->id, $sorting);
217 2
                $pivot->save();
218
            }
219 2
        });
220 2
    }
221
222
    /**
223
     * @param string|null $locale
224
     * @return string
225
     */
226 47
    private function normalizeLocaleString($locale = null): string
227
    {
228 47
        $locale = $locale ?? config('app.fallback_locale');
229
230 47
        return $locale;
231
    }
232
}
233