Passed
Pull Request — master (#24)
by Philippe
03:23
created

AssetTrait::assets()   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\AssetUploader;
8
9
trait AssetTrait
10
{
11
    use HasMediaTrait;
12
13
    /**
14
     * @return mixed
15
     */
16 42
    public function assets()
17
    {
18 42
        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 7
    public function getFilename($type = '', $locale = null): string
39
    {
40 7
        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 31
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
50
    {
51 31
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
52 2
            return null;
53
        }
54
55 31
        $locale = $this->normalizeLocaleString($locale);
56
57 31
        $assets = $this->assets->where('pivot.type', $type);
58 31
        if ($assets->count() > 1) {
59 9
            $assets = $assets->where('pivot.locale', $locale);
60
        }
61
62 31
        if ($assets->isEmpty()) {
63 1
            return null;
64
        }
65
66 31
        return $assets->first()->getFileUrl($size);
67
    }
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 21
    public function addFile($file, $type = '', $locale = null, $filename = null, $keepOriginal = false)
81
    {
82 21
        if (is_iterable($file)) {
83 2
            return $this->addFiles($file, $type, $locale, $keepOriginal);
84
        } else {
85 21
            $locale = $this->normalizeLocaleString($locale);
86
87 21
            if (is_string($file)) {
88 4
                $asset = AssetUploader::uploadFromBase64($file, $filename, $keepOriginal);
89
            } else {
90 17
                $asset = AssetUploader::upload($file, $filename, $keepOriginal);
91
            }
92
93 21
            if ($asset instanceof Asset) {
94 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 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
            }
96
97 20
            return $asset;
98
        }
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
     */
111 7
    public function addFiles($files, $type = '', $locale = null, $keepOriginal = false)
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, $keepOriginal));
120
        }
121
122 7
        return $assets;
123
    }
124
125
    /**
126
     * @return mixed
127
     */
128 1
    public function getAllImages()
129
    {
130
        $images = $this->assets->filter(function ($asset) {
131 1
            return $asset->getExtensionForFilter() === 'image';
132 1
        });
133
134 1
        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
        Asset::remove($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
        // 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 11
        $locale = $this->normalizeLocaleString($locale);
186
187 11
        if ($type) {
188 6
            $assets = $assets->where('pivot.type', $type);
189
        }
190
191 11
        if ($locale) {
192 11
            $assets = $assets->where('pivot.locale', $locale);
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 39
    private function normalizeLocaleString($locale = null): string
218
    {
219 39
        $locale = $locale ?? config('app.locale');
220
221 39
        return $locale;
222
    }
223
}
224