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 (#1116)
by Oliver
04:14
created

CrudTrait::shouldEncodeFake()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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