Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#124)
by Owen
04:17
created

CrudTrait::uploadFileToDisk()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 32
Code Lines 15

Duplication

Lines 12
Ratio 37.5 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 8
eloc 15
c 2
b 1
f 0
nc 8
nop 4
dl 12
loc 32
rs 5.3846
1
<?php
2
3
namespace Backpack\CRUD;
4
5
use DB;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Facades\Config;
8
9
trait CrudTrait
10
{
11
    /*
12
    |--------------------------------------------------------------------------
13
    | Methods for ENUM and SELECT crud fields.
14
    |--------------------------------------------------------------------------
15
    */
16
17
    public static function getPossibleEnumValues($field_name)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $field_name 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...
18
    {
19
        $instance = new static(); // create an instance of the model to be able to get the table name
20
        $type = DB::select(DB::raw('SHOW COLUMNS FROM '.Config::get('database.connections.'.env('DB_CONNECTION').'.prefix').$instance->getTable().' WHERE Field = "'.$field_name.'"'))[0]->Type;
0 ignored issues
show
Bug introduced by
It seems like getTable() 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 192 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
        preg_match('/^enum\((.*)\)$/', $type, $matches);
22
        $enum = [];
23
        foreach (explode(',', $matches[1]) as $value) {
24
            $enum[] = trim($value, "'");
25
        }
26
27
        return $enum;
28
    }
29
30
    public static function isColumnNullable($column_name)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $column_name 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...
31
    {
32
        // create an instance of the model to be able to get the table name
33
        $instance = new static();
34
35
        // register the enum column type, because Doctrine doesn't support it
36
        DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 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...
37
38
        return ! DB::connection()->getDoctrineColumn($instance->getTable(), $column_name)->getNotnull();
0 ignored issues
show
Bug introduced by
It seems like getTable() 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...
39
    }
40
41
    /*
42
    |--------------------------------------------------------------------------
43
    | Methods for Fake Fields functionality (used in PageManager).
44
    |--------------------------------------------------------------------------
45
    */
46
47
    /**
48
     * Add fake fields as regular attributes, even though they are stored as JSON.
49
     *
50
     * @param array $columns - the database columns that contain the JSONs
51
     */
52
    public function addFakes($columns = ['extras'])
53
    {
54
        foreach ($columns as $key => $column) {
55
            $column_contents = $this->{$column};
56
57
            if (! is_object($this->{$column})) {
58
                $column_contents = json_decode($this->{$column});
59
            }
60
61
            if (count($column_contents)) {
62
                foreach ($column_contents as $fake_field_name => $fake_field_value) {
63
                    $this->setAttribute($fake_field_name, $fake_field_value);
0 ignored issues
show
Bug introduced by
It seems like setAttribute() 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...
64
                }
65
            }
66
        }
67
    }
68
69
    /**
70
     * Return the entity with fake fields as attributes.
71
     *
72
     * @param array $columns - the database columns that contain the JSONs
73
     *
74
     * @return Model
0 ignored issues
show
Documentation introduced by
Should the return type not be CrudTrait?

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.

Loading history...
75
     */
76
    public function withFakes($columns = [])
77
    {
78
        $model = '\\'.get_class($this);
79
80
        if (! count($columns)) {
81
            $columns = (property_exists($model, 'fakeColumns')) ? $this->fakeColumns : ['extras'];
0 ignored issues
show
Bug introduced by
The property fakeColumns 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...
82
        }
83
84
        $this->addFakes($columns);
85
86
        return $this;
87
    }
88
89
    /*
90
    |--------------------------------------------------------------------------
91
    | Methods for storing uploaded files (used in CRUD).
92
    |--------------------------------------------------------------------------
93
    */
94
95
    /**
96
     * Handle file upload and DB storage for a file:
97
     * - on CREATE
98
     *     - stores the file at the destination path
99
     *     - generates a name
100
     *     - stores the full path in the DB;
101
     * - on UPDATE
102
     *     - if the value is null, deletes the file and sets null in the DB
103
     *     - if the value is different, stores the different file and updates DB value.
104
     *
105
     * @param  [type] $value            Value for that column sent from the input.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
106
     * @param  [type] $attribute_name   Model attribute name (and column in the db).
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
107
     * @param  [type] $disk             Filesystem disk used to store files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
108
     * @param  [type] $destination_path Path in disk where to store the files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
109
     */
110
    public function uploadFileToDisk($value, $attribute_name, $disk, $destination_path)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $attribute_name 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...
Coding Style Naming introduced by
The parameter $destination_path 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...
111
    {
112
        $request = \Request::instance();
113
114
        // if a new file is uploaded, delete the file from the disk
115
        if ($request->hasFile($attribute_name) &&
116
            $this->{$attribute_name} &&
117
            $this->{$attribute_name} != null) {
118
            \Storage::disk($disk)->delete($this->{$attribute_name});
119
            $this->attributes[$attribute_name] = null;
0 ignored issues
show
Bug introduced by
The property attributes 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...
120
        }
121
122
        // if the file input is empty, delete the file from the disk
123
        if (is_null($value) && $this->{$attribute_name} != null) {
124
            \Storage::disk($disk)->delete($this->{$attribute_name});
125
            $this->attributes[$attribute_name] = null;
126
        }
127
128
        // if a new file is uploaded, store it on disk and its filename in the database
129 View Code Duplication
        if ($request->hasFile($attribute_name) && $request->file($attribute_name)->isValid()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
131
            // 1. Generate a new file name
132
            $file = $request->file($attribute_name);
133
            $new_file_name = md5($file->getClientOriginalName().time()).'.'.$file->getClientOriginalExtension();
134
135
            // 2. Move the new file to the correct path
136
            $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
137
138
            // 3. Save the complete path to the database
139
            $this->attributes[$attribute_name] = $file_path;
140
        }
141
    }
142
143
    /**
144
     * Handle multiple file upload and DB storage:
145
     * - if files are sent
146
     *     - stores the files at the destination path
147
     *     - generates random names
148
     *     - stores the full path in the DB, as JSON array;
149
     * - if a hidden input is sent to clear one or more files
150
     *     - deletes the file
151
     *     - removes that file from the DB.
152
     *
153
     * @param  [type] $value            Value for that column sent from the input.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
154
     * @param  [type] $attribute_name   Model attribute name (and column in the db).
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
155
     * @param  [type] $disk             Filesystem disk used to store files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
156
     * @param  [type] $destination_path Path in disk where to store the files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
157
     */
158
    public function uploadMultipleFilesToDisk($value, $attribute_name, $disk, $destination_path)
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style Naming introduced by
The parameter $attribute_name 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...
Coding Style Naming introduced by
The parameter $destination_path 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...
159
    {
160
        $request = \Request::instance();
161
        $attribute_value = (array) $this->{$attribute_name};
162
        $files_to_clear = $request->get('clear_'.$attribute_name);
163
164
        // if a file has been marked for removal,
165
        // delete it from the disk and from the db
166
        if ($files_to_clear) {
167
            $attribute_value = (array) $this->{$attribute_name};
168
            foreach ($files_to_clear as $key => $filename) {
169
                \Storage::disk($disk)->delete($filename);
170
                $attribute_value = array_where($attribute_value, function ($value, $key) use ($filename) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
171
                    return $value != $filename;
172
                });
173
            }
174
        }
175
176
        // if a new file is uploaded, store it on disk and its filename in the database
177 View Code Duplication
        if ($request->hasFile($attribute_name)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
178
            foreach ($request->file($attribute_name) as $file) {
0 ignored issues
show
Bug introduced by
The expression $request->file($attribute_name) of type object<Illuminate\Http\UploadedFile>|array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
179
                if ($file->isValid()) {
180
                    // 1. Generate a new file name
181
                    $new_file_name = md5($file->getClientOriginalName().time()).'.'.$file->getClientOriginalExtension();
182
183
                    // 2. Move the new file to the correct path
184
                    $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
185
186
                    // 3. Add the public path to the database
187
                    $attribute_value[] = $file_path;
188
                }
189
            }
190
        }
191
192
        $this->attributes[$attribute_name] = json_encode($attribute_value);
193
    }
194
195
    /**
196
     * Handle image upload and DB storage for a image:
197
     * - on CREATE
198
     *     - stores the image at the destination path
199
     *     - generates a name
200
     *     - creates image variations
201
     *     - stores json object into database with variations and paths
202
     * - on UPDATE
203
     *     - if the value is null, deletes the file and sets null in the DB
204
     *     - if the value is different, stores the different file and updates DB value.
205
     *
206
     * @param  [type] $value            Value for that column sent from the input.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
207
     * @param  [type] $attribute_name   Model attribute name (and column in the db).
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
208
     * @param  [type] $disk             Filesystem disk used to store files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
209
     * @param  [type] $destination_path Path in disk where to store the files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
210
     * @param  [type] $variations       Array of variations and their dimensions
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
211
     */
212
    public function uploadImageToDisk($value, $attribute_name, $disk, $destination_path, $variations = null)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $attribute_name 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...
Coding Style Naming introduced by
The parameter $destination_path 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...
213
    {
214
        if (! $variations || ! is_array($variations)) {
215
            $variations = ['original' => null, 'thumb' => [150, 150]];
216
        }
217
218
        //Needed for the original image
219
        if (! array_key_exists('original', $variations)) {
220
            $variations['original'] = null;
221
        }
222
223
        //Needed for admin thumbnails
224
        if (! array_key_exists('thumb', $variations)) {
225
            $variations['thumb'] = [150, 150];
226
        }
227
228
        $request = \Request::instance();
229
230
        //We need to setup the disk paths as they're handled differently
231
        //depending if you need a public path or internal storage
232
        $disk_config = config('filesystems.disks.'.$disk);
233
        $disk_root = $disk_config['root'];
234
235
        //if the disk is public, we need to know the public path
236 View Code Duplication
        if ($disk_config['visibility'] == 'public') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237
            $public_path = str_replace(public_path(), '', $disk_root);
238
        } else {
239
            $public_path = $disk_root;
240
        }
241
242
        // if a new file is uploaded, delete the file from the disk
243
        if (($request->hasFile($attribute_name) || starts_with($value, 'data:image')) && $this->{$attribute_name}) {
244 View Code Duplication
            foreach ($variations as $variant => $dimensions) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
                $variant_name = str_replace('-original', '-'.$variant, $this->{$attribute_name});
246
                \Storage::disk($disk)->delete($variant_name);
247
            }
248
            $this->attributes[$attribute_name] = null;
249
        }
250
251
        // if the file input is empty, delete the file from the disk
252
        if (empty($value)) {
253 View Code Duplication
            foreach ($variations as $variant => $dimensions) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
254
                $variant_name = str_replace('-original', '-'.$variant, $this->{$attribute_name});
255
                \Storage::disk($disk)->delete($variant_name);
256
            }
257
258
            return $this->attributes[$attribute_name] = null;
259
        }
260
261
        // if a new file is uploaded, store it on disk and its filename in the database
262
        if ($request->hasFile($attribute_name) && $request->file($attribute_name)->isValid()) {
263
264
            // 1. Generate a new file name
265
            $file = $request->file($attribute_name);
266
            $new_file_name = md5($file->getClientOriginalName().time());
267
            $new_file = $new_file_name.'.'.$file->getClientOriginalExtension();
268
269
            // 2. Move the new file to the correct path
270
            $file_path = $file->storeAs($destination_path, $new_file, $disk);
271
            $image_variations = [];
272
273
            // 3. but only if they have the ability to crop/handle images
274
            if (class_exists('\Intervention\Image\ImageManagerStatic')) {
275
                $img = \Intervention\Image\ImageManagerStatic::make($file);
276
                foreach ($variations as $variant => $dimensions) {
277
                    $variant_name = $new_file_name.'-'.$variant.'.'.$file->getClientOriginalExtension();
278
                    $variant_file = $destination_path.'/'.$variant_name;
279
280 View Code Duplication
                    if ($dimensions) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
281
                        $width = $dimensions[0];
282
                        $height = $dimensions[1];
283
284
                        if ($img->width() > $width || $img->height() > $height) {
285
                            $img->resize($width, $height, function ($constraint) {
286
                                $constraint->aspectRatio();
287
                            })
288
                            ->save($disk_root.'/'.$variant_file);
289
                        } else {
290
                            $img->save($disk_root.'/'.$variant_file);
291
                        }
292
293
                        $image_variations[$variant] = $public_path.'/'.$variant_file;
294
                    } else {
295
                        $image_variations['original'] = $public_path.'/'.$file_path;
296
                    }
297
                }
298
            } else {
299
                $image_variations['original'] = $public_path.'/'.$file_path;
300
                $image_variations['thumb'] = $public_path.'/'.$file_path;
301
            }
302
303
            // 3. Save the complete path to the database
304
            $this->attributes[$attribute_name] = $image_variations['original'];
305
        } elseif (starts_with($value, 'data:image')) {
306
            $img = \Intervention\Image\ImageManagerStatic::make($value);
307
            $new_file_name = md5($value.time());
308
309
            if (! \Illuminate\Support\Facades\File::exists($disk_root.'/'.trim($destination_path, '/'))) {
310
                \Illuminate\Support\Facades\File::makeDirectory($disk_root.'/'.trim($destination_path, '/'), 0775, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
311
            }
312
313
            foreach ($variations as $variant => $dimensions) {
314
                switch ($img->mime()) {
315
                    case 'image/bmp':
316
                    case 'image/ief':
317
                    case 'image/jpeg':
318
                    case 'image/pipeg':
319
                    case 'image/tiff':
320
                    case 'image/x-jps':
321
                        $extension = '.jpg';
322
                        break;
323
                    case 'image/gif':
324
                        $extension = '.gif';
325
                        break;
326
                    case 'image/x-icon':
327
                    case 'image/png':
328
                        $extension = '.png';
329
                        break;
330
                    default:
331
                        $extension = '.jpg';
332
                        break;
333
                }
334
335
                $variant_name = $new_file_name.'-'.$variant.$extension;
336
                $variant_file = $destination_path.'/'.$variant_name;
337
338 View Code Duplication
                if ($dimensions) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
339
                    $width = $dimensions[0];
340
                    $height = $dimensions[1];
341
342
                    if ($img->width() > $width || $img->height() > $height) {
343
                        $img->resize($width, $height, function ($constraint) {
344
                            $constraint->aspectRatio();
345
                        })
346
                        ->save($disk_root.'/'.$variant_file);
347
                    } else {
348
                        $img->save($disk_root.'/'.$variant_file);
349
                    }
350
351
                    $image_variations[$variant] = $public_path.'/'.$variant_file;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$image_variations was never initialized. Although not strictly required by PHP, it is generally a good practice to add $image_variations = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
352
                } else {
353
                    $img->save($disk_root.'/'.$variant_file);
354
                    $image_variations['original'] = $variant_file;
0 ignored issues
show
Bug introduced by
The variable $image_variations does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
355
                }
356
            }
357
358
            $this->attributes[$attribute_name] = $image_variations['original'];
359
        }
360
    }
361
362
    /**
363
     * Handles the retrieval of an image by variant:.
364
     *
365
     * @param  [type] $attribute        Name of the attribute within the model that contains the json
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
366
     * @param  [type] $variant          Name of the variant you want to extract
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
367
     * @param  [type] $disk             Filesystem disk used to store files.
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
368
     */
369
    public function getUploadedImageFromDisk($attribute, $variant = 'original', $disk = null)
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...
Unused Code introduced by
The parameter $attribute is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
370
    {
371
        $image = $this->attributes['image'];
372
        $url = null;
373
        if (! empty($image)) {
374
            $image_variant = str_replace('-original', '-'.$variant, $image);
375
376
            if ($disk) {
377
                $disk_config = config('filesystems.disks.'.$disk);
378
                $disk_root = $disk_config['root'];
379
380
                //if the disk is public, we need to know the public path
381 View Code Duplication
                if ($disk_config['visibility'] == 'public') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
382
                    $public_path = str_replace(public_path(), '', $disk_root);
383
                } else {
384
                    $public_path = $disk_root;
385
                }
386
387
                if (\Storage::disk($disk)->exists($image_variant)) {
388
                    $url = asset($public_path.'/'.$image_variant);
389
                } else {
390
                    $url = asset($public_path.'/'.trim($image, '/'));
391
                }
392
            } else {
393
                if (\Storage::exists($image_variant)) {
0 ignored issues
show
Bug introduced by
The method exists() does not seem to exist on object<Illuminate\Contracts\Filesystem\Factory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
394
                    $url = \Storage::url(trim($image_variant, '/'));
0 ignored issues
show
Bug introduced by
The method url() does not seem to exist on object<Illuminate\Contracts\Filesystem\Factory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
395
                } else {
396
                    $url = url($image);
397
                }
398
            }
399
        }
400
401
        return $url;
402
    }
403
}
404