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

Passed
Push — v4dot1 ( bece96 )
by Cristian
10:39 queued 08:03
created

CrudTrait::uploadFileToDisk()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 29

Duplication

Lines 21
Ratio 72.41 %

Importance

Changes 0
Metric Value
cc 8
nc 8
nop 4
dl 21
loc 29
rs 8.2114
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\app\Models\Traits;
4
5
use DB;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Facades\Config;
8
use Traversable;
9
10
//use Backpack\CRUD\app\Models\Traits\HasIdentifiableAttribute;
11
12
trait CrudTrait
13
{
14
    use HasIdentifiableAttribute;
15
16
    public static function hasCrudTrait()
17
    {
18
        return true;
19
    }
20
21
    /*
22
    |--------------------------------------------------------------------------
23
    | Methods for ENUM and SELECT crud fields.
24
    |--------------------------------------------------------------------------
25
    */
26
27
    public static function getPossibleEnumValues($field_name)
28
    {
29
        $default_connection = Config::get('database.default');
30
        $table_prefix = Config::get('database.connections.'.$default_connection.'.prefix');
31
32
        $instance = new static(); // create an instance of the model to be able to get the table name
33
        $connectionName = $instance->getConnectionName();
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() 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...
34
        $type = DB::connection($connectionName)->select(DB::raw('SHOW COLUMNS FROM `'.$table_prefix.$instance->getTable().'` WHERE Field = "'.$field_name.'"'))[0]->Type;
0 ignored issues
show
Bug introduced by
The method getTable() does not exist on Backpack\CRUD\app\Models\Traits\CrudTrait. Did you maybe mean getTableWithPrefix()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
35
        preg_match('/^enum\((.*)\)$/', $type, $matches);
36
        $enum = [];
37
        foreach (explode(',', $matches[1]) as $value) {
38
            $enum[] = trim($value, "'");
39
        }
40
41
        return $enum;
42
    }
43
44
    public static function getEnumValuesAsAssociativeArray($field_name)
45
    {
46
        $instance = new static();
47
        $enum_values = $instance->getPossibleEnumValues($field_name);
48
49
        $array = array_flip($enum_values);
50
51
        foreach ($array as $key => $value) {
52
            $array[$key] = $key;
53
        }
54
55
        return $array;
56
    }
57
58
    /**
59
     * Register aditional types in doctrine schema manager for the current connection.
60
     *
61
     * @return DB
62
     */
63
    public function getConnectionWithExtraTypeMappings()
64
    {
65
        $instance = new self;
66
67
        $conn = DB::connection($instance->getConnectionName());
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() 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...
68
69
        // register the enum, json and jsonb column type, because Doctrine doesn't support it
70
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
71
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('json', 'json_array');
72
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('jsonb', 'json_array');
73
74
        return $conn;
75
    }
76
77
    /**
78
     * Get the model's table name, with the prefix added from the configuration file.
79
     *
80
     * @return string Table name with prefix
81
     */
82
    public function getTableWithPrefix()
83
    {
84
        $prefix = Config::get('database.connections.'.$this->getConnectionName().'.prefix');
0 ignored issues
show
Bug introduced by
It seems like getConnectionName() 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...
85
        $tableName = $this->getTable();
0 ignored issues
show
Bug introduced by
The method getTable() does not exist on Backpack\CRUD\app\Models\Traits\CrudTrait. Did you maybe mean getTableWithPrefix()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
86
87
        return $prefix.$tableName;
88
    }
89
90
    /**
91
     * Get the column type for a certain db column.
92
     *
93
     * @param  string $columnName Name of the column in the db table.
94
     * @return string             Db column type.
95
     */
96
    public function getColumnType($columnName)
97
    {
98
        $conn = $this->getConnectionWithExtraTypeMappings();
99
        $table = $this->getTableWithPrefix();
100
101
        return $conn->getSchemaBuilder()->getColumnType($table, $columnName);
102
    }
103
104
    /**
105
     * Checks if the given column name is nullable.
106
     *
107
     * @param string $column_name The name of the db column.
108
     * @return bool
109
     */
110
    public static function isColumnNullable($column_name)
111
    {
112
        // create an instance of the model to be able to get the table name
113
        $instance = new static();
114
115
        $conn = $instance->getConnectionWithExtraTypeMappings();
116
        $table = $instance->getTableWithPrefix();
117
118
        // MongoDB columns are alway nullable
119
        if ($conn->getConfig()['driver'] === 'mongodb') {
120
            return true;
121
        }
122
123
        try {
124
            // check if the column exists in the database
125
            $column = $conn->getDoctrineColumn($table, $column_name);
126
            // check for NOT NULL
127
            $notNull = $column->getNotnull();
128
            // return the value of nullable (aka the inverse of NOT NULL)
129
            return ! $notNull;
130
        } catch (\Exception $e) {
131
            return true;
132
        }
133
    }
134
135
    /*
136
    |--------------------------------------------------------------------------
137
    | Methods for Fake Fields functionality (used in PageManager).
138
    |--------------------------------------------------------------------------
139
    */
140
141
    /**
142
     * Add fake fields as regular attributes, even though they are stored as JSON.
143
     *
144
     * @param array $columns - the database columns that contain the JSONs
145
     */
146
    public function addFakes($columns = ['extras'])
147
    {
148
        foreach ($columns as $key => $column) {
149
            if (! isset($this->attributes[$column])) {
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...
150
                continue;
151
            }
152
153
            $column_contents = $this->{$column};
154
155
            if ($this->shouldDecodeFake($column)) {
156
                $column_contents = json_decode($column_contents);
157
            }
158
159
            if ((is_array($column_contents) || is_object($column_contents) || $column_contents instanceof Traversable)) {
160
                foreach ($column_contents as $fake_field_name => $fake_field_value) {
161
                    $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...
162
                }
163
            }
164
        }
165
    }
166
167
    /**
168
     * Return the entity with fake fields as attributes.
169
     *
170
     * @param array $columns - the database columns that contain the JSONs
171
     *
172
     * @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...
173
     */
174
    public function withFakes($columns = [])
175
    {
176
        $model = '\\'.get_class($this);
177
178
        $columnCount = ((is_array($columns) || $columns instanceof Countable) ? count($columns) : 0);
0 ignored issues
show
Bug introduced by
The class Backpack\CRUD\app\Models\Traits\Countable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
179
180
        if ($columnCount == 0) {
181
            $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...
182
        }
183
184
        $this->addFakes($columns);
185
186
        return $this;
187
    }
188
189
    /**
190
     * Determine if this fake column should be json_decoded.
191
     *
192
     * @param $column string fake column name
193
     *
194
     * @return bool
195
     */
196
    public function shouldDecodeFake($column)
197
    {
198
        return ! in_array($column, array_keys($this->casts));
0 ignored issues
show
Bug introduced by
The property casts 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...
199
    }
200
201
    /**
202
     * Determine if this fake column should get json_encoded or not.
203
     *
204
     * @param $column string fake column name
205
     *
206
     * @return bool
207
     */
208
    public function shouldEncodeFake($column)
209
    {
210
        return ! in_array($column, array_keys($this->casts));
211
    }
212
213
    /*
214
    |--------------------------------------------------------------------------
215
    | Methods for storing uploaded files (used in CRUD).
216
    |--------------------------------------------------------------------------
217
    */
218
219
    /**
220
     * Handle file upload and DB storage for a file:
221
     * - on CREATE
222
     *     - stores the file at the destination path
223
     *     - generates a name
224
     *     - stores the full path in the DB;
225
     * - on UPDATE
226
     *     - if the value is null, deletes the file and sets null in the DB
227
     *     - if the value is different, stores the different file and updates DB value.
228
     *
229
     * @param string $value            Value for that column sent from the input.
230
     * @param string $attribute_name   Model attribute name (and column in the db).
231
     * @param string $disk             Filesystem disk used to store files.
232
     * @param string $destination_path Path in disk where to store the files.
233
     */
234
    public function uploadFileToDisk($value, $attribute_name, $disk, $destination_path)
235
    {
236
        // if a new file is uploaded, delete the file from the disk
237 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...
238
            $this->{$attribute_name} &&
239
            $this->{$attribute_name} != null) {
240
            \Storage::disk($disk)->delete($this->{$attribute_name});
241
            $this->attributes[$attribute_name] = null;
242
        }
243
244
        // if the file input is empty, delete the file from the disk
245 View Code Duplication
        if (is_null($value) && $this->{$attribute_name} != null) {
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...
246
            \Storage::disk($disk)->delete($this->{$attribute_name});
247
            $this->attributes[$attribute_name] = null;
248
        }
249
250
        // if a new file is uploaded, store it on disk and its filename in the database
251 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...
252
            // 1. Generate a new file name
253
            $file = request()->file($attribute_name);
254
            $new_file_name = md5($file->getClientOriginalName().random_int(1, 9999).time()).'.'.$file->getClientOriginalExtension();
255
256
            // 2. Move the new file to the correct path
257
            $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
258
259
            // 3. Save the complete path to the database
260
            $this->attributes[$attribute_name] = $file_path;
261
        }
262
    }
263
264
    /**
265
     * Handle multiple file upload and DB storage:
266
     * - if files are sent
267
     *     - stores the files at the destination path
268
     *     - generates random names
269
     *     - stores the full path in the DB, as JSON array;
270
     * - if a hidden input is sent to clear one or more files
271
     *     - deletes the file
272
     *     - removes that file from the DB.
273
     *
274
     * @param string $value            Value for that column sent from the input.
275
     * @param string $attribute_name   Model attribute name (and column in the db).
276
     * @param string $disk             Filesystem disk used to store files.
277
     * @param string $destination_path Path in disk where to store the files.
278
     */
279
    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...
280
    {
281
        if (! is_array($this->{$attribute_name})) {
282
            $attribute_value = json_decode($this->{$attribute_name}, true) ?? [];
283
        } else {
284
            $attribute_value = $this->{$attribute_name};
285
        }
286
        $files_to_clear = request()->get('clear_'.$attribute_name);
287
288
        // if a file has been marked for removal,
289
        // delete it from the disk and from the db
290
        if ($files_to_clear) {
291
            foreach ($files_to_clear as $key => $filename) {
292
                \Storage::disk($disk)->delete($filename);
293
                $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...
294
                    return $value != $filename;
295
                });
296
            }
297
        }
298
299
        // if a new file is uploaded, store it on disk and its filename in the database
300 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...
301
            foreach (request()->file($attribute_name) as $file) {
302
                if ($file->isValid()) {
303
                    // 1. Generate a new file name
304
                    $new_file_name = md5($file->getClientOriginalName().random_int(1, 9999).time()).'.'.$file->getClientOriginalExtension();
305
306
                    // 2. Move the new file to the correct path
307
                    $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
308
309
                    // 3. Add the public path to the database
310
                    $attribute_value[] = $file_path;
311
                }
312
            }
313
        }
314
315
        $this->attributes[$attribute_name] = json_encode($attribute_value);
316
    }
317
318
    /*
319
    |--------------------------------------------------------------------------
320
    | Methods for working with translatable models.
321
    |--------------------------------------------------------------------------
322
    */
323
324
    /**
325
     * Get the attributes that were casted in the model.
326
     * Used for translations because Spatie/Laravel-Translatable
327
     * overwrites the getCasts() method.
328
     *
329
     * @return self
330
     */
331
    public function getCastedAttributes()
332
    {
333
        return parent::getCasts();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getCasts() instead of getCastedAttributes()). Are you sure this is correct? If so, you might want to change this to $this->getCasts().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
334
    }
335
336
    /**
337
     * Check if a model is translatable.
338
     * All translation adaptors must have the translationEnabledForModel() method.
339
     *
340
     * @return bool
341
     */
342
    public function translationEnabled()
343
    {
344
        if (method_exists($this, 'translationEnabledForModel')) {
345
            return $this->translationEnabledForModel();
0 ignored issues
show
Bug introduced by
The method translationEnabledForModel() does not exist on Backpack\CRUD\app\Models\Traits\CrudTrait. Did you maybe mean translationEnabled()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
346
        }
347
348
        return false;
349
    }
350
}
351