Passed
Push — master ( 5adbae...738a99 )
by Philippe
05:20 queued 02:50
created

AssetUploader::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 1
Bugs 0 Features 0
Metric Value
c 1
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
9
class AssetUploader extends Model
10
{
11
    /**
12
     * Uploads the file/files or asset by creating the
13
     * asset that is needed to upload the files too.
14
     *
15
     * @param $files
16
     * @param string|null $filename
17
     * @param bool $keepOriginal
18
     * @return \Illuminate\Support\Collection|null|Asset
19
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
20
     */
21 53
    public static function upload($files, $filename = null, $keepOriginal = false)
22
    {
23 53
        if ($files instanceof Asset) {
24 10
            return $files;
25
        }
26
27 53
        if (is_array($files)) {
28 3
            return self::uploadMultiple($files, $keepOriginal);
29
        }
30
31 50
        if (! ($files instanceof File) && ! ($files instanceof UploadedFile)) {
32 1
            return;
33
        }
34
35 49
        $asset = new Asset();
36 49
        $asset->save();
37
38 49
        return self::uploadToAsset($files, $asset, $filename, $keepOriginal);
39
    }
40
41 3
    private static function uploadMultiple($files, $keepOriginal = false)
42
    {
43 3
        $list = collect([]);
44 3
        collect($files)->each(function ($file) use ($list, $keepOriginal) {
45 3
            if ($file instanceof Asset) {
46
                $list->push($file);
47
            } else {
48 3
                $asset = new Asset();
49 3
                $asset->save();
50 3
                $list->push(self::uploadToAsset($file, $asset, null, $keepOriginal));
51
            }
52 3
        });
53
54 3
        return $list;
55
    }
56
57
    /**
58
     * Uploads the file/files or asset by creating the
59
     * asset that is needed to upload the files too.
60
     *
61
     * @param $file
62
     * @param string|null $filename
63
     * @param bool $keepOriginal
64
     * @return \Illuminate\Support\Collection|null|Asset
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use null|Asset.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
65
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
66
     * @internal param array|string $files
67
     */
68 4
    public static function uploadFromBase64($file, $filename = null, $keepOriginal = false)
69
    {
70 4
        $asset = new Asset();
71 4
        $asset->save();
72
73 4
        return self::uploadBase64ToAsset($file, $asset, $filename, $keepOriginal);
74
    }
75
76
    /**
77
     * Uploads the given file to this instance of asset
78
     * and sets the dimensions as a custom property.
79
     *
80
     * @param $files
81
     * @param Asset $asset
82
     * @param string|null $filename
83
     * @param bool $keepOriginal
84
     * @return null|Asset
85
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
86
     */
87 52
    public static function uploadToAsset($files, $asset, $filename = null, $keepOriginal = false): ?Asset
88
    {
89 52
        $customProps = [];
90 52
        if (self::isImage($files)) {
91 49
            $customProps['dimensions'] = getimagesize($files)[0].' x '.getimagesize($files)[1];
92
        }
93
94 52
        $fileAdd    = $asset->addMedia($files)->withCustomProperties($customProps);
95 52
        if ($keepOriginal) {
96 1
            $fileAdd = $fileAdd->preservingOriginal();
97
        }
98
99 52
        if($filename)
0 ignored issues
show
Bug Best Practice introduced by
The expression $filename of type string|null is loosely compared to true; 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...
100
        {
101 4
            $fileAdd->setName(substr($filename, 0, strpos($filename, '.')));
102 4
            $fileAdd->setFileName($filename);
103
        }
104
105 52
        $fileAdd->toMediaCollection();
106
107 52
        return $asset->load('media');
108
    }
109
110
    /**
111
     * Uploads the given file to this instance of asset
112
     * and sets the dimensions as a custom property.
113
     *
114
     * @param $file
115
     * @param Asset $asset
116
     * @param string|null $filename
117
     * @param bool $keepOriginal
118
     * @return null|Asset
119
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
120
     * @internal param $files
121
     */
122 4
    public static function uploadBase64ToAsset($file, $asset, $filename = null, $keepOriginal = false): ?Asset
123
    {
124
        //TODO find a way to save the dimensions for base64 uploads
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
//        $customProps = [];
126
//        $customProps['dimensions'] = getimagesize($file)[0].' x '.getimagesize($file)[1];
127
128
//        $fileAdd    = $asset->addMediaFromBase64($file)->withCustomProperties($customProps);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
129 4
        $fileAdd    = $asset->addMediaFromBase64($file);
130 4
        if ($keepOriginal) {
131 1
            $fileAdd = $fileAdd->preservingOriginal();
132
        }
133
134 4
        if($filename)
0 ignored issues
show
Bug Best Practice introduced by
The expression $filename of type string|null is loosely compared to true; 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...
135
        {
136 3
            $fileAdd->setName(substr($filename, 0, strpos($filename, '.')));
137 3
            $fileAdd->setFileName($filename);
138
        }else{
139 1
            $extension = substr($file, 11, strpos($file,';')-11);
140 1
            $filename = pathinfo($file, PATHINFO_BASENAME);
141 1
            $fileAdd->setName($filename);
142 1
            $fileAdd->setFileName($filename.'.'.$extension);
143
        }
144
145 4
        $fileAdd->toMediaCollection();
146
147 4
        return $asset->load('media');
148
    }
149
150
    /**
151
     * @param $file
152
     * @return bool
153
     */
154 52
    private static function isImage($file): bool
155
    {
156 52
        return str_before($file->getMimetype(), '/') === 'image';
157
    }
158
}
159