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 (#710)
by Cristian
07:14
created

Read   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 310
Duplicated Lines 0 %

Coupling/Cohesion

Components 6
Dependencies 0

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 310
rs 7.6
wmc 40
lcom 6
cbo 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A getEntry() 0 9 2
A autoEagerLoadRelationshipColumns() 0 8 2
A getEntries() 0 13 2
C getEntriesWithConditions() 0 47 8
A getColumnQuery() 0 12 4
A getFields() 0 16 3
A hasUploadFields() 0 9 3
A enableDetailsRow() 0 4 1
A disableDetailsRow() 0 4 1
A setDefaultPageLength() 0 4 1
A getDefaultPageLength() 0 14 3
A enableAjaxTable() 0 4 1
A ajaxTable() 0 4 1
A getRowViews() 0 9 2
A getCellView() 0 20 4
A enableExportButtons() 0 4 1
A exportButtons() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like Read often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Read, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Backpack\CRUD\PanelTraits;
4
5
trait Read
6
{
7
    /*
8
    |--------------------------------------------------------------------------
9
    |                                   READ
10
    |--------------------------------------------------------------------------
11
    */
12
13
    /**
14
     * Find and retrieve an entry in the database or fail.
15
     *
16
     * @param  [int] The id of the row in the db to fetch.
17
     *
18
     * @return [Eloquent Collection] The row in the db.
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent 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...
19
     */
20
    public function getEntry($id)
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...
21
    {
22
        if (! $this->entry) {
23
            $this->entry = $this->model->findOrFail($id);
0 ignored issues
show
Bug introduced by
The property entry 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...
Bug introduced by
The property model 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...
24
            $this->entry = $this->entry->withFakes();
25
        }
26
27
        return $this->entry;
28
    }
29
30
    /**
31
     * Make the query JOIN all relationships used in the columns, too,
32
     * so there will be less database queries overall.
33
     */
34
    public function autoEagerLoadRelationshipColumns()
35
    {
36
        $relationships = $this->getColumnsRelationships();
0 ignored issues
show
Bug introduced by
It seems like getColumnsRelationships() 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...
37
38
        if (count($relationships)) {
39
            $this->with($relationships);
0 ignored issues
show
Bug introduced by
It seems like with() 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...
40
        }
41
    }
42
43
    /**
44
     * Get all entries from the database.
45
     *
46
     * @return [Collection of your model]
0 ignored issues
show
Documentation introduced by
The doc-type Collection">[Collection 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...
47
     */
48
    public function getEntries()
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...
49
    {
50
        $this->autoEagerLoadRelationshipColumns();
51
52
        $entries = $this->query->get();
0 ignored issues
show
Bug introduced by
The property query 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...
53
54
        // add the fake columns for each entry
55
        foreach ($entries as $key => $entry) {
56
            $entry->addFakes($this->getFakeColumnsAsArray());
0 ignored issues
show
Bug introduced by
It seems like getFakeColumnsAsArray() 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...
57
        }
58
59
        return $entries;
60
    }
61
62
    /**
63
     * Get all entries from the database with conditions.
64
     *
65
     * @param string $length the number of records requested
0 ignored issues
show
Documentation introduced by
Should the type for parameter $length not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
66
     * @param string $skip how many to skip
0 ignored issues
show
Documentation introduced by
Should the type for parameter $skip not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
67
     * @param string $orderBy the column to order by
0 ignored issues
show
Documentation introduced by
Should the type for parameter $orderBy not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
68
     * @param string $orderDirection how to order asc/desc
69
     * @param string $filter what string to filter the name by
0 ignored issues
show
Documentation introduced by
Should the type for parameter $filter not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
70
     *
71
     * @return [Collection of your model]
0 ignored issues
show
Documentation introduced by
The doc-type Collection">[Collection 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...
72
     */
73
    public function getEntriesWithConditions(
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...
74
        $length = null,
75
        $skip = 0,
76
        $orderBy = null,
77
        $orderDirection = 'asc',
78
        $filter = null
79
    ) {
80
        $modifiers = 0;
81
82
        if ($filter !== null) {
83
            $modifiers = 1;
84
            $entries = $this->query->where(function ($query) use ($filter) {
85
                foreach ($this->columns as $column) {
0 ignored issues
show
Bug introduced by
The property columns 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...
86
                    if ($this->getColumnQuery($column) !== null) {
87
                        $query->orWhere(
88
                            $this->getColumnQuery($column),
89
                            'like',
90
                            '%'.$filter.'%'
91
                        );
92
                    }
93
                }
94
            });
95
        }
96
97
        if ($length !== null) {
98
            $modifiers = 1;
99
            $entries = $this->query->skip($skip)->take($length);
100
        }
101
102
        if ($orderBy !== null) {
103
            $modifiers = 1;
104
            $entries = $this->query->orderBy($orderBy, $orderDirection);
105
        }
106
107
        if ($modifiers == 0) {
108
            $entries = $this->query->get();
109
        } else {
110
            $entries = $entries->get();
0 ignored issues
show
Bug introduced by
The variable $entries does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
111
        }
112
113
        // add the fake columns for each entry
114
        foreach ($entries as $key => $entry) {
115
            $entry->addFakes($this->getFakeColumnsAsArray());
0 ignored issues
show
Bug introduced by
It seems like getFakeColumnsAsArray() 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...
116
        }
117
118
        return $entries;
119
    }
120
121
    /**
122
     * Receives a filter and tries to get all the columns to be filtered by that filter *Work in progress*.
123
     *
124
     * @param $column
125
     * @return null|string
126
     */
127
    private function getColumnQuery($column)
128
    {
129
        if (isset($column['type']) && $column['type'] == 'model_function') {
130
            return;
131
        }
132
133
        if (is_array($column)) {
134
            return $column['name'];
135
        }
136
137
        return Model::resolveConnection()->getQueryGrammar()->wrap($column);
138
    }
139
140
    /**
141
     * Get the fields for the create or update forms.
142
     *
143
     * @param  [form] create / update / both - defaults to 'both'
144
     * @param  [integer] the ID of the entity to be edited in the Update form
145
     *
146
     * @return [array] all the fields that need to be shown and their information
0 ignored issues
show
Documentation introduced by
The doc-type [array] 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...
147
     */
148
    public function getFields($form, $id = false)
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...
149
    {
150
        switch (strtolower($form)) {
151
            case 'create':
152
                return $this->getCreateFields();
0 ignored issues
show
Bug introduced by
It seems like getCreateFields() 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...
153
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
154
155
            case 'update':
156
                return $this->getUpdateFields($id);
0 ignored issues
show
Bug introduced by
It seems like getUpdateFields() 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...
157
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
158
159
            default:
160
                return $this->getCreateFields();
0 ignored issues
show
Bug introduced by
It seems like getCreateFields() 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...
161
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
162
        }
163
    }
164
165
    /**
166
     * Check if the create/update form has upload fields.
167
     * Upload fields are the ones that have "upload" => true defined on them.
168
     * @param  [form] create / update / both - defaults to 'both'
169
     * @param  [id] id of the entity - defaults to false
170
     * @return bool
171
     */
172
    public function hasUploadFields($form, $id = false)
173
    {
174
        $fields = $this->getFields($form, $id);
175
        $upload_fields = array_where($fields, function ($value, $key) {
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...
176
            return isset($value['upload']) && $value['upload'] == true;
177
        });
178
179
        return count($upload_fields) ? true : false;
180
    }
181
182
    /**
183
     * Enable the DETAILS ROW functionality:.
184
     *
185
     * In the table view, show a plus sign next to each entry.
186
     * When clicking that plus sign, an AJAX call will bring whatever content you want from the EntityCrudController::showDetailsRow($id) and show it to the user.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 162 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...
187
     */
188
    public function enableDetailsRow()
189
    {
190
        $this->details_row = true;
0 ignored issues
show
Bug introduced by
The property details_row 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...
191
    }
192
193
    /**
194
     * Disable the DETAILS ROW functionality:.
195
     */
196
    public function disableDetailsRow()
197
    {
198
        $this->details_row = false;
199
    }
200
201
    /**
202
     * Set the number of rows that should be show on the table page (list view).
203
     */
204
    public function setDefaultPageLength($value)
205
    {
206
        $this->default_page_length = $value;
0 ignored issues
show
Bug introduced by
The property default_page_length 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...
207
    }
208
209
    /**
210
     * Get the number of rows that should be show on the table page (list view).
211
     */
212
    public function getDefaultPageLength()
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...
213
    {
214
        // return the custom value for this crud panel, if set using setPageLength()
215
        if ($this->default_page_length) {
216
            return $this->default_page_length;
217
        }
218
219
        // otherwise return the default value in the config file
220
        if (config('backpack.crud.default_page_length')) {
221
            return config('backpack.crud.default_page_length');
222
        }
223
224
        return 25;
225
    }
226
227
    /*
228
    |--------------------------------------------------------------------------
229
    |                                AJAX TABLE
230
    |--------------------------------------------------------------------------
231
    */
232
233
    /**
234
     * Tell the list view to use AJAX for loading multiple rows.
235
     */
236
    public function enableAjaxTable()
237
    {
238
        $this->ajax_table = true;
0 ignored issues
show
Bug introduced by
The property ajax_table 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...
239
    }
240
241
    /**
242
     * Check if ajax is enabled for the table view.
243
     * @return bool
244
     */
245
    public function ajaxTable()
246
    {
247
        return $this->ajax_table;
248
    }
249
250
    /**
251
     * Get the HTML of the cells in a table row, for a certain DB entry.
252
     * @param  Entity $entry A db entry of the current entity;
253
     * @return array         Array of HTML cell contents.
254
     */
255
    public function getRowViews($entry)
256
    {
257
        $response = [];
258
        foreach ($this->columns as $key => $column) {
259
            $response[] = $this->getCellView($column, $entry);
260
        }
261
262
        return $response;
263
    }
264
265
    /**
266
     * Get the HTML of a cell, using the column types.
267
     * @param  array $column
268
     * @param  Entity $entry A db entry of the current entity;
269
     * @return HTML
270
     */
271
    public function getCellView($column, $entry)
272
    {
273
        if (! isset($column['type'])) {
274
            return \View::make('crud::columns.text')->with('crud', $this)->with('column', $column)->with('entry',
275
                $entry)->render();
276
        } else {
277
            if (view()->exists('vendor.backpack.crud.columns.'.$column['type'])) {
278
                return \View::make('vendor.backpack.crud.columns.'.$column['type'])->with('crud',
279
                    $this)->with('column', $column)->with('entry', $entry)->render();
280
            } else {
281
                if (view()->exists('crud::columns.'.$column['type'])) {
282
                    return \View::make('crud::columns.'.$column['type'])->with('crud', $this)->with('column',
283
                        $column)->with('entry', $entry)->render();
284
                } else {
285
                    return \View::make('crud::columns.text')->with('crud', $this)->with('column',
286
                        $column)->with('entry', $entry)->render();
287
                }
288
            }
289
        }
290
    }
291
292
    /*
293
    |--------------------------------------------------------------------------
294
    |                                EXPORT BUTTONS
295
    |--------------------------------------------------------------------------
296
    */
297
298
    /**
299
     * Tell the list view to show the DataTables export buttons.
300
     */
301
    public function enableExportButtons()
302
    {
303
        $this->export_buttons = true;
0 ignored issues
show
Bug introduced by
The property export_buttons 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...
304
    }
305
306
    /**
307
     * Check if export buttons are enabled for the table view.
308
     * @return bool
309
     */
310
    public function exportButtons()
311
    {
312
        return $this->export_buttons;
313
    }
314
}
315