Passed
Push — master ( edfa43...778249 )
by Philippe
11:32
created

AssetTrait::deleteAsset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Traits;
4
5
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
6
use Thinktomorrow\AssetLibrary\Models\Asset;
7
use Thinktomorrow\AssetLibrary\Models\AssetUploader;
8
use Thinktomorrow\Locale\Locale;
9
use Traversable;
10
11
trait AssetTrait
12
{
13
    use HasMediaTrait;
14
15
    /**
16
     * @return mixed
17
     */
18 35
    public function assets()
19
    {
20 35
        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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
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...
21
    }
22
23
    /**
24
     * @param string $type
25
     * @param string|null $locale
26
     * @return bool
27
     */
28 4
    public function hasFile($type = '', $locale = null): bool
29
    {
30 4
        $filename = $this->getFilename($type, $locale);
31
32 4
        return (bool) $filename && basename($filename) != 'other.png';
33
    }
34
35
    /**
36
     * @param string $type
37
     * @param string|null $locale
38
     * @return string
39
     */
40 6
    public function getFilename($type = '', $locale = null): string
41
    {
42 6
        return basename($this->getFileUrl($type, '', $locale));
43
    }
44
45
    /**
46
     * @param string $type
47
     * @param string $size
48
     * @param string|null $locale
49
     * @return string
50
     */
51 25
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
52
    {
53 25
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
0 ignored issues
show
Bug introduced by
The property assets does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
54 2
            return null;
55
        }
56
57 25
        $locale = $this->normalizeLocaleString($locale);
58
59 25
        $assets = $this->assets->where('pivot.type', $type);
60 25
        if ($assets->count() > 1) {
61 9
            $assets = $assets->where('pivot.locale', $locale);
62
        }
63
64 25
        if ($assets->isEmpty()) {
65 1
            return null;
66
        }
67
68 25
        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
78
     * @param bool $keepOriginal
79
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
80
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
81
     */
82 20
    public function addFile($file, $type = '', $locale = null, $filename = null, $keepOriginal = false): void
83
    {
84 20
        if($file instanceof Traversable || is_array($file))
85
        {
86 2
            $this->addFiles($file, $type, $locale, $keepOriginal);
87
        }else{
88 20
            $locale = $this->normalizeLocaleString($locale);
89
90 20
            if(is_string($file))
91
            {
92 4
                $asset = AssetUploader::uploadFromBase64($file, $filename, $keepOriginal);
93
            }else{
94 16
                $asset = AssetUploader::upload($file, $filename, $keepOriginal);
95
            }
96
97 20
            if($asset instanceof Asset){
98 20
                $asset->attachToModel($this, $type, $locale);
99
            }
100
        }
101
102 19
    }
103
104
    /**
105
     * Adds multiple files to this model, accepts a type and locale to be saved with the file.
106
     *
107
     * @param $files
108
     * @param string $type
109
     * @param string|null $locale
110
     * @param bool $keepOriginal
111
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
112
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
113
     */
114 7
    public function addFiles($files, $type = '', $locale = null, $keepOriginal = false): void
115
    {
116 7
        $files = (array) $files;
117 7
        $locale = $this->normalizeLocaleString($locale);
118
119 7
        if(is_string(array_values($files)[0]))
120
        {
121 1
            foreach($files as $filename => $file)
122
            {
123 1
                $this->addFile($file, $type, $locale, $filename, $keepOriginal);
124
            }
125
        }else{
126 6
            foreach($files as $filename => $file)
127
            {
128 6
                $this->addFile($file, $type, $locale, $filename, $keepOriginal);
129
            }
130
        }
131 7
    }
132
133
    /**
134
     * @return mixed
135
     */
136
    public function getAllImages()
137
    {
138 1
        $images = $this->assets->filter(function ($asset) {
139 1
            return $asset->getExtensionForFilter() === 'image';
140 1
        });
141
142 1
        return $images->sortBy('pivot.order');
143
    }
144
145
    /**
146
     * Removes an asset completely.
147
     *
148
     * @param $ids
149
     */
150 1
    public function deleteAsset($ids): void
151
    {
152 1
        Asset::remove($ids);
153 1
    }
154
155
    /**
156
     * Remove the asset and attaches a new one.
157
     *
158
     * @param $replace
159
     * @param $with
160
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
161
     * @throws \Thinktomorrow\AssetLibrary\Exceptions\AssetUploadException
162
     */
163 1
    public function replaceAsset($replace, $with): void
164
    {
165 1
        $asset = Asset::findOrFail($replace);
166 1
        Asset::remove($replace);
167
168 1
        $this->addFile(Asset::findOrFail($with), $asset->type, $asset->locale);
169 1
    }
170
171
    /**
172
     * @param null $type
173
     * @param string|null $locale
174
     * @return mixed
175
     */
176 9
    public function getAllFiles($type = null, $locale = null)
177
    {
178 9
        $locale = $this->normalizeLocaleString($locale);
179
180 9
        $files = $this->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
181
182 9
        return $files->sortBy('pivot.order');
183
    }
184
185
    /**
186
     * @param null $type
187
     * @param $sorting
188
     */
189 2
    public function sortFiles($type = null, $sorting): void
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
190
    {
191 2
        $files = $this->getAllFiles($type);
192 2
        $files->each(function($asset) use($sorting){
193 2
            if(in_array($asset->id, $sorting)){
194 2
                $pivot = $this->assets->find($asset->id)->pivot;
195 2
                $pivot->order = array_search($asset->id, $sorting);
196 2
                $pivot->save();
197
            }
198 2
        });
199 2
    }
200
201
202
    /**
203
     * @param string|null $locale
204
     * @return string
205
     */
206 32
    private function normalizeLocaleString($locale = null): string
207
    {
208 32
        $locale = $locale ?? Locale::getDefault();
209
210 32
        return $locale;
211
    }
212
}
213