Passed
Pull Request — master (#38)
by Philippe
04:33 queued 46s
created

AssetTrait::deleteAllAssets()   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 0
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
    /**
15
     * @return mixed
16
     */
17 51
    public function assets()
18
    {
19 51
        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

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

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