Passed
Push — master ( 765c1f...eb8479 )
by Philippe
02:18
created

AssetTrait   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 4
dl 0
loc 200
ccs 62
cts 62
cp 1
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A assets() 0 4 1
A hasFile() 0 6 2
A getFilename() 0 4 1
B getFileUrl() 0 19 5
B addFile() 0 21 5
A addFiles() 0 18 4
A getAllImages() 0 8 1
A deleteAsset() 0 4 1
A replaceAsset() 0 7 1
A getAllFiles() 0 8 1
A sortFiles() 0 11 2
A normalizeLocale() 0 6 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 33
    public function assets()
19
    {
20 33
        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 24
    public function getFileUrl($type = '', $size = '', $locale = null): ?string
52
    {
53 24
        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 24
        $locale = $this->normalizeLocale($locale);
58
59 24
        $assets = $this->assets->where('pivot.type', $type);
60 24
        if ($assets->count() > 1) {
61 8
            $assets = $assets->where('pivot.locale', $locale);
62
        }
63
64 24
        if ($assets->isEmpty()) {
65 1
            return null;
66
        }
67
68 24
        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 19
    public function addFile($file, $type = '', $locale = null, $filename = null, $keepOriginal = false): void
83
    {
84 19
        if($file instanceof Traversable || is_array($file))
85
        {
86 2
            $this->addFiles($file, $type, $locale, $keepOriginal);
87
        }else{
88 19
            $locale = $this->normalizeLocale($locale);
89
90 19
            if(is_string($file))
91
            {
92 4
                $asset = AssetUploader::uploadFromBase64($file, $filename, $keepOriginal);
93
            }else{
94 15
                $asset = AssetUploader::upload($file, $filename, $keepOriginal);
95
            }
96
97 19
            if($asset instanceof Asset){
98 19
                $asset->attachToModel($this, $type, $locale);
99
            }
100
        }
101
102 18
    }
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 6
    public function addFiles($files, $type = '', $locale = null, $keepOriginal = false): void
115
    {
116 6
        $files = (array) $files;
117 6
        $locale = $this->normalizeLocale($locale);
118
119 6
        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 5
            foreach($files as $filename => $file)
127
            {
128 5
                $this->addFile($file, $type, $locale, null, $keepOriginal);
129
            }
130
        }
131 6
    }
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
     */
162 1
    public function replaceAsset($replace, $with): void
163
    {
164 1
        $asset = Asset::findOrFail($replace);
165 1
        Asset::remove($replace);
166
167 1
        $this->addFile(Asset::findOrFail($with), $asset->type, $asset->locale);
168 1
    }
169
170
    /**
171
     * @param null $type
172
     * @param string|null $locale
173
     * @return mixed
174
     */
175 7
    public function getAllFiles($type = null, $locale = null)
176
    {
177 7
        $locale = $this->normalizeLocale($locale);
178
179 7
        $files = $this->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
180
181 7
        return $files->sortBy('pivot.order');
182
    }
183
184
    /**
185
     * @param $callback
186
     */
187 1
    public function sortFiles($type = null, $sorting)
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...
188
    {
189 1
        $files = $this->getAllFiles($type);
190
191 1
        $files->each(function($file) use($sorting){
192 1
            if(in_array($file->id, $sorting)){
193 1
                $this->assets()->updateExistingPivot($file->id, ['order' => array_search(3, $sorting)]);
194
            }
195 1
        });
196
197 1
    }
198
199
200
    /**
201
     * @param string|null $locale
202
     * @return string
203
     */
204 30
    private function normalizeLocale($locale = null): string
205
    {
206 30
        $locale = $locale ?? Locale::getDefault();
207
208 30
        return $locale;
209
    }
210
}
211