Passed
Pull Request — master (#26)
by Philippe
08:53 queued 03:20
created

AssetTrait::sortFiles()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 2
crap 2
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 47
    public function assets()
17
    {
18 47
        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
    }
20
21
    /**
22
     * @param string $type
23
     * @param string|null $locale
24
     * @return bool
25
     */
26 4
    public function hasFile($type = '', $locale = null): bool
27
    {
28 4
        $filename = $this->getFilename($type, $locale);
29
30 4
        return (bool) $filename && basename($filename) != 'other.png';
31
    }
32
33
    /**
34
     * @param string $type
35
     * @param string|null $locale
36
     * @return string
37
     */
38 12
    public function getFilename($type = '', $locale = null): string
39
    {
40 12
        return basename($this->getFileUrl($type, '', $locale));
41
    }
42
43
    /**
44
     * @param string $type
45
     * @param string $size
46
     * @param string|null $locale
47
     * @return string
48
     */
49 36
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
50
    {
51 36
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
52 3
            return null;
53
        }
54
55 35
        $locale = $this->normalizeLocaleString($locale);
56
57 35
        $assets = $this->assets->where('pivot.type', $type);
58
59 35
        if ($locale && $assets->count() > 1) {
60 10
            $assets = $assets->where('pivot.locale', $locale);
61
        }
62
63 35
        if ($assets->isEmpty()) {
64 1
            return null;
65
        }
66
67 35
        return $assets->first()->getFileUrl($size);
68
    }
69
70
    /**
71
     * Adds a file to this model, accepts a type and locale to be saved with the file.
72
     *
73
     * @param $file
74
     * @param string $type
75
     * @param string|null $locale
76
     * @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...
77
     * @param bool $keepOriginal
78
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
79
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
80
     */
81 21
    public function addFile($file, $type = '', $locale = null, $filename = null, $keepOriginal = false)
82
    {
83 21
        if (is_iterable($file)) {
84 2
            return $this->addFiles($file, $type, $locale, $keepOriginal);
85
        } else {
86 21
            $locale = $this->normalizeLocaleString($locale);
87
88 21
            if (is_string($file)) {
89 4
                $asset = AssetUploader::uploadFromBase64($file, $filename, $keepOriginal);
90
            } else {
91 17
                $asset = AssetUploader::upload($file, $filename, $keepOriginal);
92
            }
93
94 21
            if ($asset instanceof Asset) {
95 21
                $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

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