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

AssetUploader::upload()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.0061

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
ccs 17
cts 18
cp 0.9444
rs 8.439
cc 6
eloc 18
nc 4
nop 3
crap 6.0061
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 51
    public static function upload($files, $filename = null, $keepOriginal = false)
22
    {
23 51
        $list = collect([]);
24
25 51
        if ($files instanceof Asset) {
26 10
            return $files;
27 51
        } elseif (is_array($files)) {
28 3
            collect($files)->each(function ($file) use ($list, $keepOriginal, $filename) {
29 3
                if ($file instanceof Asset) {
30
                    $list->push($file);
31
                } else {
32 3
                    $asset = new Asset();
33 3
                    $asset->save();
34 3
                    $list->push(self::uploadToAsset($file, $asset, $filename, $keepOriginal));
35
                }
36 3
            });
37
38 3
            return $list;
39
        }
40
41 48
        $asset = new Asset();
42 48
        $asset->save();
43
44 48
        if (! ($files instanceof File) && ! ($files instanceof UploadedFile)) {
45 1
            return;
46
        }
47
48 47
        return self::uploadToAsset($files, $asset, $filename, $keepOriginal);
49
    }
50
51
    /**
52
     * Uploads the file/files or asset by creating the
53
     * asset that is needed to upload the files too.
54
     *
55
     * @param $file
56
     * @param string|null $filename
57
     * @param bool $keepOriginal
58
     * @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...
59
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
60
     * @internal param array|string $files
61
     */
62 4
    public static function uploadFromBase64($file, $filename = null, $keepOriginal = false)
63
    {
64 4
        $asset = new Asset();
65 4
        $asset->save();
66
67 4
        return self::uploadBase64ToAsset($file, $asset, $filename, $keepOriginal);
68
    }
69
70
    /**
71
     * Uploads the given file to this instance of asset
72
     * and sets the dimensions as a custom property.
73
     *
74
     * @param $files
75
     * @param Asset $asset
76
     * @param string|null $filename
77
     * @param bool $keepOriginal
78
     * @return null|Asset
79
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
80
     */
81 50
    public static function uploadToAsset($files, $asset, $filename = null, $keepOriginal = false): ?Asset
82
    {
83 50
        $customProps = [];
84 50
        if (self::isImage($files)) {
85 47
            $customProps['dimensions'] = getimagesize($files)[0].' x '.getimagesize($files)[1];
86
        }
87
88 50
        $fileAdd    = $asset->addMedia($files)->withCustomProperties($customProps);
89 50
        if ($keepOriginal) {
90 1
            $fileAdd = $fileAdd->preservingOriginal();
91
        }
92
93 50
        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...
94
        {
95 1
            $fileAdd->setName(substr($filename, 0, strpos($filename, '.')));
96 1
            $fileAdd->setFileName($filename);
97
        }
98
99 50
        $fileAdd->toMediaCollection();
100
101 50
        return $asset->load('media');
102
    }
103
104
    /**
105
     * Uploads the given file to this instance of asset
106
     * and sets the dimensions as a custom property.
107
     *
108
     * @param $file
109
     * @param Asset $asset
110
     * @param string|null $filename
111
     * @param bool $keepOriginal
112
     * @return null|Asset
113
     * @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
114
     * @internal param $files
115
     */
116 4
    public static function uploadBase64ToAsset($file, $asset, $filename = null, $keepOriginal = false): ?Asset
117
    {
118
        //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...
119
//        $customProps = [];
120
//        $customProps['dimensions'] = getimagesize($file)[0].' x '.getimagesize($file)[1];
121
122
//        $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...
123 4
        $fileAdd    = $asset->addMediaFromBase64($file);
124 4
        if ($keepOriginal) {
125 1
            $fileAdd = $fileAdd->preservingOriginal();
126
        }
127
128 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...
129
        {
130 3
            $fileAdd->setName(substr($filename, 0, strpos($filename, '.')));
131 3
            $fileAdd->setFileName($filename);
132
        }else{
133 1
            $extension = substr($file, 11, strpos($file,';')-11);
134 1
            $filename = pathinfo($file, PATHINFO_BASENAME);
135 1
            $fileAdd->setName($filename);
136 1
            $fileAdd->setFileName($filename.'.'.$extension);
137
        }
138
139 4
        $fileAdd->toMediaCollection();
140
141 4
        return $asset->load('media');
142
    }
143
144
    /**
145
     * @param $file
146
     * @return bool
147
     */
148 50
    private static function isImage($file): bool
149
    {
150 50
        return str_before($file->getMimetype(), '/') === 'image';
151
    }
152
}
153