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 (#382)
by Cristian
03:31
created

CrudTrait::translationEnabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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