Test Failed
Pull Request — master (#24)
by Philippe
02:54
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\AssetUploader;
8
9
trait AssetTrait
10
{
11
    use HasMediaTrait;
12
13
    /**
14
     * @return mixed
15
     */
16
    public function assets()
17 37
    {
18
        return $this->morphToMany(Asset::class, 'entity', 'asset_pivots')->withPivot('type', 'locale', 'order')->orderBy('order');
0 ignored issues
show
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...
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

18
        return $this->/** @scrutinizer ignore-call */ morphToMany(Asset::class, 'entity', 'asset_pivots')->withPivot('type', 'locale', 'order')->orderBy('order');
Loading history...
19 37
    }
20
21
    /**
22
     * @param string $type
23
     * @param string|null $locale
24
     * @return bool
25
     */
26
    public function hasFile($type = '', $locale = null): bool
27 4
    {
28
        $filename = $this->getFilename($type, $locale);
29 4
30
        return (bool) $filename && basename($filename) != 'other.png';
31 4
    }
32
33
    /**
34
     * @param string $type
35
     * @param string|null $locale
36
     * @return string
37
     */
38
    public function getFilename($type = '', $locale = null): string
39 6
    {
40
        return basename($this->getFileUrl($type, '', $locale));
41 6
    }
42
43
    /**
44
     * @param string $type
45
     * @param string $size
46
     * @param string|null $locale
47
     * @return string
48
     */
49
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
50 26
    {
51
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
52 26
            return null;
53 2
        }
54
55
        $locale = $this->normalizeLocaleString($locale);
56 26
57
        $assets = $this->assets->where('pivot.type', $type);
58 26
        if ($assets->count() > 1) {
59 26
            $assets = $assets->where('pivot.locale', $locale);
60 9
        }
61
62
        if ($assets->isEmpty()) {
63 26
            return null;
64 1
        }
65
66
        return $assets->first()->getFileUrl($size);
67 26
    }
68
69
    /**
70
     * Adds a file to this model, accepts a type and locale to be saved with the file.
71
     *
72
     * @param $file
73
     * @param string $type
74
     * @param string|null $locale
75
     * @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...
76
     * @param bool $keepOriginal
77
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
78
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
79
     */
80
    public function addFile($file, $type = '', $locale = null, $filename = null, $keepOriginal = false)
81 22
    {
82
        if (is_iterable($file)) {
83 22
            return $this->addFiles($file, $type, $locale, $keepOriginal);
84 2
        } else {
85
            $locale = $this->normalizeLocaleString($locale);
86 22
87
            if (is_string($file)) {
88 22
                $asset = AssetUploader::uploadFromBase64($file, $filename, $keepOriginal);
89 4
            } else {
90
                $asset = AssetUploader::upload($file, $filename, $keepOriginal);
91 18
            }
92
93
            if ($asset instanceof Asset) {
94 22
                $asset->attachToModel($this, $type, $locale);
0 ignored issues
show
Bug introduced by
$this of type Thinktomorrow\AssetLibrary\Traits\AssetTrait is incompatible with the type Illuminate\Database\Eloquent\Model 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

94
                $asset->attachToModel(/** @scrutinizer ignore-type */ $this, $type, $locale);
Loading history...
95 22
            }
96
97
            return $asset;
98 21
        }
99
    }
100
101
    /**
102
     * Adds multiple files to this model, accepts a type and locale to be saved with the file.
103
     *
104
     * @param $files
105
     * @param string $type
106
     * @param string|null $locale
107
     * @param bool $keepOriginal
108
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
109
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
110 7
     */
111
    public function addFiles($files, $type = '', $locale = null, $keepOriginal = false)
112 7
    {
113 7
        $files  = (array) $files;
114
        $locale = $this->normalizeLocaleString($locale);
115 7
        $assets = collect();
116 1
117 1
        foreach ($files as $filename => $file) {
118
            $filename = is_string($filename) ? $filename : '';
119
            $assets->push($this->addFile($file, $type, $locale, $filename, $keepOriginal));
120 6
        }
121 6
122
        return $assets;
123
    }
124 7
125
    /**
126
     * @return mixed
127
     */
128
    public function getAllImages()
129
    {
130
        $images = $this->assets->filter(function ($asset) {
131 1
            return $asset->getExtensionForFilter() === 'image';
132 1
        });
133 1
134
        return $images->sortBy('pivot.order');
135 1
    }
136
137
    /**
138
     * Removes an asset completely.
139
     *
140
     * @param $ids
141
     */
142
    public function deleteAsset($ids): void
143 1
    {
144
        Asset::remove($ids);
145 1
    }
146 1
147
    /**
148
     * Removes all assets completely.
149
     *
150
     * @param $ids
151
     */
152
    public function deleteAllAssets(): void
153
    {
154
        $this->assets->each->delete();
155
    }
156 2
157
    /**
158 2
     * Remove the asset and attaches a new one.
159
     *
160 2
     * @param $replace
161 2
     * @param $with
162
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
163 2
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
164 2
     */
165
    public function replaceAsset($replace, $with)
166
    {
167
        $old = $this->assets()->findOrFail($replace);
168
169
        $this->assets()->detach($old->id);
170
        $old->delete();
171 11
172
        $this->addFile(Asset::findOrFail($with), $old->pivot->type, $old->pivot->locale);
173 11
    }
174
175
    /**
176 11
     * @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...
177
     * @param string|null $locale
178 11
     * @return mixed
179 6
     */
180
    public function getAllFiles($type = null, $locale = null)
181
    {
182 11
        $assets = $this->assets;
183 11
184
        // TODO: we should want to avoid checking locale if null is passed, which indicates locale should not be included in query.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 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...
185
        $locale = $this->normalizeLocaleString($locale);
186 11
187
        if ($type) {
188
            $assets = $assets->where('pivot.type', $type);
189
        }
190
191
        if ($locale) {
192
            $assets = $assets->where('pivot.locale', $locale);
193 2
        }
194
        return $assets->sortBy('pivot.order');
195 2
    }
196 2
197 2
    /**
198 2
     * @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...
199 2
     * @param $sorting
200 2
     */
201
    public function sortFiles($type, $sorting): void
202 2
    {
203 2
        $files = $this->getAllFiles($type);
204
        $files->each(function ($asset) use ($sorting) {
205
            if (in_array($asset->id, $sorting)) {
206
                $pivot = $this->assets->find($asset->id)->pivot;
207
                $pivot->order = array_search($asset->id, $sorting);
208
                $pivot->save();
209 34
            }
210
        });
211 34
    }
212
213 34
    /**
214
     * @param string|null $locale
215
     * @return string
216
     */
217
    private function normalizeLocaleString($locale = null): string
218
    {
219
        $locale = $locale ?? config('app.locale');
220
221
        return $locale;
222
    }
223
}
224