Completed
Pull Request — master (#38)
by Philippe
05:00
created

AssetTrait::getFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 1
cts 1
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
    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 38
            $model->assets->each(function ($asset) use ($model) {
18
                $model->assets()->updateExistingPivot($asset->id, ['unused'=> true]);
19 38
            });
20
        });
21
    }
22
23
    /**
24
     * @return mixed
25
     */
26
    public function assets()
27 4
    {
28
        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...
29 4
    }
30
31 4
    /**
32
     * @param string $type
33
     * @param string|null $locale
34
     * @return bool
35
     */
36
    public function hasFile($type = '', $locale = null): bool
37
    {
38
        $filename = $this->getFilename($type, $locale);
39 6
40
        return (bool) $filename && basename($filename) != 'other.png';
41 6
    }
42
43
    /**
44
     * @param string $type
45
     * @param string|null $locale
46
     * @return string
47
     */
48
    public function getFilename($type = '', $locale = null): string
49
    {
50 27
        return basename($this->getFileUrl($type, '', $locale));
51
    }
52 27
53 2
    /**
54
     * @param string $type
55
     * @param string $size
56 27
     * @param string|null $locale
57
     * @return string
58 27
     */
59
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
60 27
    {
61 9
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
62
            return null;
63
        }
64 27
65 1
        $locale = $this->normalizeLocaleString($locale);
66
67
        $assets = $this->assets->where('pivot.type', $type);
68 27
69
        if ($locale && $assets->count() > 1) {
70
            $assets = $assets->where('pivot.locale', $locale);
71
        }
72
73
        if ($assets->isEmpty()) {
74
            return null;
75
        }
76
77
        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 22
     *
83
     * @param $file
84 22
     * @param string $type
85 2
     * @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 22
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
88
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
89 22
     */
90 4
    public function addFile($file, $type = '', $locale = null, $filename = null)
91
    {
92 18
        if (is_iterable($file)) {
93
            return $this->addFiles($file, $type, $locale);
94
        } else {
95 22
            $locale = $this->normalizeLocaleString($locale);
96 22
97
            if (is_string($file)) {
98
                $asset = AssetUploader::uploadFromBase64($file, $filename);
99 21
            } else {
100
                $asset = AssetUploader::upload($file, $filename);
101
            }
102
103
            if ($asset instanceof Asset) {
104
                $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
            return $asset;
108
        }
109
    }
110
111 7
    /**
112
     * Adds multiple files to this model, accepts a type and locale to be saved with the file.
113 7
     *
114 7
     * @param $files
115
     * @param string $type
116 7
     * @param string|null $locale
117 1
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
118 1
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
119
     */
120
    public function addFiles($files, $type = '', $locale = null)
121 6
    {
122 6
        $files  = (array) $files;
123
        $locale = $this->normalizeLocaleString($locale);
124
        $assets = collect();
125 7
126
        foreach ($files as $filename => $file) {
127
            $filename = is_string($filename) ? $filename : '';
128
            $assets->push($this->addFile($file, $type, $locale, $filename));
129
        }
130 1
131
        return $assets;
132
    }
133 1
134 1
    /**
135
     * @return mixed
136 1
     */
137
    public function getAllImages()
138
    {
139
        $images = $this->assets->filter(function ($asset) {
140
            return $asset->getExtensionForFilter() === 'image';
141
        });
142
143
        return $images->sortBy('pivot.order');
144 1
    }
145
146 1
    /**
147 1
     * Removes an asset completely.
148
     *
149
     * @param $ids
150
     */
151
    public function deleteAsset($ids): void
152
    {
153
        AssetLibrary::removeByIds($ids);
154
    }
155
156
    /**
157 2
     * Removes all assets completely.
158
     *
159 2
     * @param $ids
160
     */
161 2
    public function deleteAllAssets(): void
162 2
    {
163
        $this->assets->each->delete();
164 2
    }
165 2
166
    /**
167
     * Remove the asset and attaches a new one.
168
     *
169
     * @param $replace
170
     * @param $with
171
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
172 11
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
173
     */
174 11
    public function replaceAsset($replace, $with)
175
    {
176 11
        $old = $this->assets()->findOrFail($replace);
177
178 11
        $this->assets()->detach($old->id);
179 6
        $old->delete();
180
181
        $this->addFile(Asset::findOrFail($with), $old->pivot->type, $old->pivot->locale);
182 11
    }
183 11
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 11
     * @param string|null $locale
187
     * @return mixed
188
     */
189
    public function getAllFiles($type = null, $locale = null)
190
    {
191
        $assets = $this->assets;
192
193 2
        $locale = $this->normalizeLocaleString($locale);
194
195 2
        if ($type) {
0 ignored issues
show
introduced by
$type is of type null, thus it always evaluated to false.
Loading history...
196
            $assets = $assets->where('pivot.type', $type);
197 2
        }
198 2
199 2
        if ($locale) {
200 2
            $assets = $assets->where('pivot.locale', $locale);
201
        }
202 2
203 2
        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 35
     */
210
    public function sortFiles($type, $sorting): void
211 35
    {
212
        $files = $this->getAllFiles($type);
213 35
        $files->each(function ($asset) use ($sorting) {
214
            if (in_array($asset->id, $sorting)) {
215
                $pivot = $this->assets->find($asset->id)->pivot;
216
                $pivot->order = array_search($asset->id, $sorting);
217
                $pivot->save();
218
            }
219
        });
220
    }
221
222
    /**
223
     * @param string|null $locale
224
     * @return string
225
     */
226
    private function normalizeLocaleString($locale = null): string
227
    {
228
        $locale = $locale ?? config('app.fallback_locale');
229
230
        return $locale;
231
    }
232
}
233