Completed
Branch enh/code-cleanup (10b655)
by Philippe
01:26
created

Asset::isImage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Http\File;
7
use Illuminate\Http\UploadedFile;
8
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
9
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
10
use Spatie\MediaLibrary\Media;
11
use Thinktomorrow\Locale\Locale;
12
13
class Asset extends Model implements HasMediaConversions
14
{
15
    use HasMediaTrait;
16
17
    /**
18
     * Attaches this asset instance to the given model and
19
     * sets the type and locale to the given values and
20
     * returns the model with the asset relationship.
21
     *
22
     * @param Model $model
23
     * @param string $type
24
     * @param null|string $locale
25
     * @return Model
26
     */
27
    public function attachToModel(Model $model, $type = '', $locale = null)
28
    {
29
        $asset = $model->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
30
31
        if (! $asset->isEmpty() && $asset->first()->pivot->type !== '') {
32
            $model->assets()->detach($asset->first()->id);
33
        }
34
35
        if (! $locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
36
            $locale = Locale::getDefault();
37
        }
38
39
        $model->assets()->attach($this, ['type' => $type, 'locale' => $locale]);
40
41
        return $model->load('assets');
42
    }
43
44
    public function hasFile()
45
    {
46
        return (bool) $this->getFileUrl('');
47
    }
48
49
    public function getFilename($size = '')
50
    {
51
        return basename($this->getFileUrl($size));
52
    }
53
54
    /**
55
     * @return string
56
     */
57
    public function getFileUrl($size = '')
58
    {
59
        $media = $this->getMedia();
60
61
        if ($media->count() < 1) {
62
            return asset('assets/back/img/other.png');
63
        }
64
65
        if (config('assetlibrary.conversionPrefix') && $size != '') {
66
            $conversionName = $media->first()->name . '_' . $size;
67
        } else {
68
            $conversionName = $size;
69
        }
70
71
        return $media->first()->getUrl($conversionName);
72
    }
73
74
    /**
75
     * Returns the image url or a fallback specific per filetype.
76
     *
77
     * @param string $type
78
     * @return string
79
     */
80
    public function getImageUrl($type = '')
81
    {
82
        if ($this->getMedia()->isEmpty()) {
83
            return asset('assets/back/img/other.png');
84
        }
85
        $extension = $this->getExtensionType();
86
        if ($extension === 'image') {
87
            return $this->getFileUrl($type);
88
        } elseif ($extension) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extension of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
89
            return asset('assets/back/img/'.$extension.'.png');
90
        }
91
92
        return asset('assets/back/img/other.png');
93
    }
94
95
    public function getExtensionForFilter()
96
    {
97
        if ($extension = $this->getExtensionType()) {
98
            return $extension;
99
        }
100
101
        return '';
102
    }
103
104
    public function getExtensionType()
105
    {
106
        $extension = explode('.', $this->getMedia()[0]->file_name);
107
        $extension = end($extension);
108
109
        if (in_array($extension, ['xls', 'xlsx', 'numbers', 'sheets'])) {
110
            return 'xls';
111
        }
112
        if (in_array($extension, ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'])) {
113
            return 'image';
114
        }
115
        if ($extension === 'pdf') {
116
            return 'pdf';
117
        }
118
119
        return false;
120
    }
121
122
    public function getMimeType()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
123
    {
124
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->mime_type;
125
    }
126
127
    public function isMediaEmpty()
128
    {
129
        return $this->getMedia()->isEmpty();
130
    }
131
132
    public function getSize()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
133
    {
134
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->human_readable_size;
135
    }
136
137
    public function getDimensions()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
138
    {
139
        return $this->isMediaEmpty() ? '' : $this->getMedia()[0]->getCustomProperty('dimensions');
140
    }
141
142
    /**
143
     * Removes one or more assets by their ids.
144
     * @param $image_ids
145
     */
146
    public static function remove($image_ids)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $image_ids is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
147
    {
148
        if (is_array($image_ids)) {
149
            foreach ($image_ids as $id) {
150
                self::where('id', $id)->first()->delete();
151
            }
152
        } else {
153
            self::find($image_ids)->first()->delete();
154
        }
155
    }
156
157
    /**
158
     * Returns a collection of all the assets in the library.
159
     * @return \Illuminate\Support\Collection
160
     */
161
    public static function getAllAssets()
162
    {
163
        return self::all()->sortByDesc('created_at');
164
    }
165
166
    /**
167
     * Generates the hidden field that links the file to a specific type.
168
     *
169
     * @param string $type
170
     * @param null $locale
171
     *
172
     * @return string
173
     */
174
    public static function typeField($type = '', $locale = null, $name = 'type')
175
    {
176
        $result = '<input type="hidden" value="'.$type.'" name="';
177
178
        if (! $locale) {
179
            return $result.$name.'">';
180
        }
181
182
        return $result.'trans['.$locale.'][files][]">';
183
    }
184
185
    /**
186
     * Generates the hidden field that links the file to translations.
187
     *
188
     * @param string $locale
189
     *
190
     * @return string
191
     */
192
    public static function localeField($locale = '')
193
    {
194
        return self::typeField($locale, null, 'locale');
195
    }
196
197
    /**
198
     * Register the conversions that should be performed.
199
     *
200
     * @param Media|null $media
201
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
202
     */
203
    public function registerMediaConversions(Media $media = null)
204
    {
205
        $conversions        = config('assetlibrary.conversions');
206
        $conversionPrefix   = config('assetlibrary.conversionPrefix');
207
208
        foreach ($conversions as $key => $value) {
209
            if ($conversionPrefix) {
210
                $conversionName = $media->name.'_'.$key;
211
            } else {
212
                $conversionName = $key;
213
            }
214
215
            $this->addMediaConversion($conversionName)
216
                ->width($value['width'])
217
                ->height($value['height'])
218
                ->sharpen(15)
219
                ->keepOriginalImageFormat()
220
                ->optimize();
221
        }
222
    }
223
}
224