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 (#1548)
by Oliver
09:29
created

CrudTrait::shouldDecodeFake()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD;
4
5
use DB;
6
use Traversable;
7
use Illuminate\Support\Facades\Config;
8
use Illuminate\Database\Eloquent\Model;
9
10
trait CrudTrait
11
{
12
    /*
13
    |--------------------------------------------------------------------------
14
    | Methods for ENUM and SELECT crud fields.
15
    |--------------------------------------------------------------------------
16
    */
17
18
    public static function getPossibleEnumValues($field_name)
19
    {
20
        $default_connection = Config::get('database.default');
21
        $table_prefix = Config::get('database.connections.'.$default_connection.'.prefix');
22
23
        $instance = new static(); // create an instance of the model to be able to get the table name
24
        $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...
25
        $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
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 169 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...
26
        preg_match('/^enum\((.*)\)$/', $type, $matches);
27
        $enum = [];
28
        foreach (explode(',', $matches[1]) as $value) {
29
            $enum[] = trim($value, "'");
30
        }
31
32
        return $enum;
33
    }
34
35
    public static function getEnumValuesAsAssociativeArray($field_name)
36
    {
37
        $instance = new static();
38
        $enum_values = $instance->getPossibleEnumValues($field_name);
39
40
        $array = array_flip($enum_values);
41
42
        foreach ($array as $key => $value) {
43
            $array[$key] = $key;
44
        }
45
46
        return $array;
47
    }
48
49
    public static function isColumnNullable($column_name)
50
    {
51
        // create an instance of the model to be able to get the table name
52
        $instance = new static();
53
54
        $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...
55
        $table = Config::get('database.connections.'.Config::get('database.default').'.prefix').$instance->getTable();
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...
56
57
        // register the enum, json and jsonb column type, because Doctrine doesn't support it
58
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
59
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('json', 'json_array');
60
        $conn->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('jsonb', 'json_array');
61
62
        return ! $conn->getDoctrineColumn($table, $column_name)->getNotnull();
63
    }
64
65
    /*
66
    |--------------------------------------------------------------------------
67
    | Methods for Fake Fields functionality (used in PageManager).
68
    |--------------------------------------------------------------------------
69
    */
70
71
    /**
72
     * Add fake fields as regular attributes, even though they are stored as JSON.
73
     *
74
     * @param array $columns - the database columns that contain the JSONs
75
     */
76
    public function addFakes($columns = ['extras'])
77
    {
78
        foreach ($columns as $key => $column) {
79
            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...
80
                continue;
81
            }
82
83
            $column_contents = $this->{$column};
84
85
            if ($this->shouldDecodeFake($column)) {
86
                $column_contents = json_decode($column_contents);
87
            }
88
89
            if ((is_array($column_contents) || is_object($column_contents) || $column_contents instanceof Traversable)) {
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...
90
                foreach ($column_contents as $fake_field_name => $fake_field_value) {
91
                    $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...
92
                }
93
            }
94
        }
95
    }
96
97
    /**
98
     * Return the entity with fake fields as attributes.
99
     *
100
     * @param array $columns - the database columns that contain the JSONs
101
     *
102
     * @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...
103
     */
104
    public function withFakes($columns = [])
105
    {
106
        $model = '\\'.get_class($this);
107
108
        if (! count($columns)) {
109
            $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...
110
        }
111
112
        $this->addFakes($columns);
113
114
        return $this;
115
    }
116
117
    /**
118
     * Determine if this fake column should be json_decoded.
119
     *
120
     * @param $column string fake column name
121
     * @return bool
122
     */
123
    public function shouldDecodeFake($column)
124
    {
125
        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...
126
    }
127
128
    /**
129
     * Determine if this fake column should get json_encoded or not.
130
     *
131
     * @param $column string fake column name
132
     * @return bool
133
     */
134
    public function shouldEncodeFake($column)
135
    {
136
        return ! in_array($column, array_keys($this->casts));
137
    }
138
139
    /*
140
    |--------------------------------------------------------------------------
141
    | Methods for storing uploaded files (used in CRUD).
142
    |--------------------------------------------------------------------------
143
    */
144
145
    /**
146
     * Handle file upload and DB storage for a file:
147
     * - on CREATE
148
     *     - stores the file at the destination path
149
     *     - generates a name
150
     *     - stores the full path in the DB;
151
     * - on UPDATE
152
     *     - if the value is null, deletes the file and sets null in the DB
153
     *     - if the value is different, stores the different file and updates DB value.
154
     *
155
     * @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...
156
     * @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...
157
     * @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...
158
     * @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...
159
     */
160
    public function uploadFileToDisk($value, $attribute_name, $disk, $destination_path)
161
    {
162
        $request = \Request::instance();
163
164
        // if a new file is uploaded, delete the file from the disk
165
        if ($request->hasFile($attribute_name) &&
166
            $this->{$attribute_name} &&
167
            $this->{$attribute_name} != null) {
168
            \Storage::disk($disk)->delete($this->{$attribute_name});
169
            $this->attributes[$attribute_name] = null;
170
        }
171
172
        // if the file input is empty, delete the file from the disk
173
        if (is_null($value) && $this->{$attribute_name} != null) {
174
            \Storage::disk($disk)->delete($this->{$attribute_name});
175
            $this->attributes[$attribute_name] = null;
176
        }
177
178
        // if a new file is uploaded, store it on disk and its filename in the database
179 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...
180
            // 1. Generate a new file name
181
            $file = $request->file($attribute_name);
182
            $new_file_name = md5($file->getClientOriginalName().time()).'.'.$file->getClientOriginalExtension();
183
184
            // 2. Move the new file to the correct path
185
            $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
186
187
            // 3. Save the complete path to the database
188
            $this->attributes[$attribute_name] = $file_path;
189
        }
190
    }
191
192
    /**
193
     * Handle multiple file upload and DB storage:
194
     * - if files are sent
195
     *     - stores the files at the destination path
196
     *     - generates random names
197
     *     - stores the full path in the DB, as JSON array;
198
     * - if a hidden input is sent to clear one or more files
199
     *     - deletes the file
200
     *     - removes that file from the DB.
201
     *
202
     * @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...
203
     * @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...
204
     * @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...
205
     * @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...
206
     */
207
    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...
208
    {
209
        $request = \Request::instance();
210
        $attribute_value = (array) $this->{$attribute_name};
211
        $files_to_clear = $request->get('clear_'.$attribute_name);
212
213
        // if a file has been marked for removal,
214
        // delete it from the disk and from the db
215
        if ($files_to_clear) {
216
            $attribute_value = (array) $this->{$attribute_name};
217
            foreach ($files_to_clear as $key => $filename) {
218
                \Storage::disk($disk)->delete($filename);
219
                $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...
220
                    return $value != $filename;
221
                });
222
            }
223
        }
224
225
        // if a new file is uploaded, store it on disk and its filename in the database
226 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...
227
            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...
228
                if ($file->isValid()) {
229
                    // 1. Generate a new file name
230
                    $new_file_name = md5($file->getClientOriginalName().time()).'.'.$file->getClientOriginalExtension();
231
232
                    // 2. Move the new file to the correct path
233
                    $file_path = $file->storeAs($destination_path, $new_file_name, $disk);
234
235
                    // 3. Add the public path to the database
236
                    $attribute_value[] = $file_path;
237
                }
238
            }
239
        }
240
241
        $this->attributes[$attribute_name] = json_encode($attribute_value);
242
    }
243
244
    /*
245
    |--------------------------------------------------------------------------
246
    | Methods for working with translatable models.
247
    |--------------------------------------------------------------------------
248
    */
249
250
    /**
251
     * Get the attributes that were casted in the model.
252
     * Used for translations because Spatie/Laravel-Translatable
253
     * overwrites the getCasts() method.
254
     *
255
     * @return [type] [description]
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...
256
     */
257
    public function getCastedAttributes()
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...
258
    {
259
        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...
260
    }
261
262
    /**
263
     * Check if a model is translatable.
264
     * All translation adaptors must have the translationEnabledForModel() method.
265
     *
266
     * @return bool
267
     */
268
    public function translationEnabled()
269
    {
270
        if (method_exists($this, 'translationEnabledForModel')) {
271
            return $this->translationEnabledForModel();
0 ignored issues
show
Bug introduced by
The method translationEnabledForModel() does not exist on Backpack\CRUD\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...
272
        }
273
274
        return false;
275
    }
276
}
277