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

CrudPanel::getRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
ccs 0
cts 1
cp 0
crap 2
1
<?php
2
3
namespace Backpack\CRUD;
4
5
use Backpack\CRUD\PanelTraits\Read;
6
use Backpack\CRUD\PanelTraits\Tabs;
7
use Backpack\CRUD\PanelTraits\Query;
8
use Backpack\CRUD\PanelTraits\Views;
9
use Backpack\CRUD\PanelTraits\Access;
10
use Backpack\CRUD\PanelTraits\Create;
11
use Backpack\CRUD\PanelTraits\Delete;
12
use Backpack\CRUD\PanelTraits\Errors;
13
use Backpack\CRUD\PanelTraits\Fields;
14
use Backpack\CRUD\PanelTraits\Search;
15
use Backpack\CRUD\PanelTraits\Update;
16
use Backpack\CRUD\PanelTraits\AutoSet;
17
use Backpack\CRUD\PanelTraits\Buttons;
18
use Backpack\CRUD\PanelTraits\Columns;
19
use Backpack\CRUD\PanelTraits\Filters;
20
use Backpack\CRUD\PanelTraits\Reorder;
21
use Backpack\CRUD\PanelTraits\AutoFocus;
22
use Backpack\CRUD\PanelTraits\FakeFields;
23
use Backpack\CRUD\PanelTraits\FakeColumns;
24
use Illuminate\Database\Eloquent\Collection;
25
use Backpack\CRUD\PanelTraits\RequiredFields;
26
use Backpack\CRUD\PanelTraits\ViewsAndRestoresRevisions;
27
28
class CrudPanel
0 ignored issues
show
Coding Style introduced by
The property $entity_name is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $entity_name_plural is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $reorder_label is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $reorder_max_level is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $details_row is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $export_buttons is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $create_fields is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $update_fields is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $db_column_types is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $default_page_length is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $page_length_menu is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
29
{
30
    use Create, Read, Search, Update, Delete, Errors, Reorder, Access, Columns, Fields, Query, Buttons, AutoSet, FakeFields, FakeColumns, ViewsAndRestoresRevisions, AutoFocus, Filters, Tabs, Views, RequiredFields;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 213 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...
31
32
    // --------------
33
    // CRUD variables
34
    // --------------
35
    // These variables are passed to the CRUD views, inside the $crud variable.
36
    // All variables are public, so they can be modified from your EntityCrudController.
37
    // All functions and methods are also public, so they can be used in your EntityCrudController to modify these variables.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 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...
38
39
    // TODO: translate $entity_name and $entity_name_plural by default, with english fallback
40
41
    public $model = "\App\Models\Entity"; // what's the namespace for your entity's model
42
    public $route; // what route have you defined for your entity? used for links.
43
    public $entity_name = 'entry'; // what name will show up on the buttons, in singural (ex: Add entity)
44
    public $entity_name_plural = 'entries'; // what name will show up on the buttons, in plural (ex: Delete 5 entities)
45
    public $request;
46
47
    public $access = ['list', 'create', 'update', 'delete'/* 'revisions', reorder', 'show', 'details_row' */];
48
49
    public $reorder = false;
50
    public $reorder_label = false;
51
    public $reorder_max_level = 3;
52
53
    public $details_row = false;
54
    public $export_buttons = false;
55
56
    public $columns = []; // Define the columns for the table view as an array;
57
    public $create_fields = []; // Define the fields for the "Add new entry" view as an array;
58
    public $update_fields = []; // Define the fields for the "Edit entry" view as an array;
59
60
    public $query;
61
    public $entry;
62
    public $buttons;
63
    public $db_column_types = [];
64
    public $default_page_length = false;
65
    public $page_length_menu = false;
66
67
    // TONE FIELDS - TODO: find out what he did with them, replicate or delete
68
    public $sort = [];
69
70
    // The following methods are used in CrudController or your EntityCrudController to manipulate the variables above.
71 159
72
    public function __construct()
73 159
    {
74 159
        $this->setErrorDefaults();
75 159
        $this->initButtons();
76
    }
77
78
    // ------------------------------------------------------
79
    // BASICS - model, route, entity_name, entity_name_plural
80
    // ------------------------------------------------------
81
82
    /**
83
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
84
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
85
     *
86
     * @param string $model_namespace Full model namespace. Ex: App\Models\Article]
87
     *
88
     * @throws \Exception in case the model does not exist
89 159
     */
90
    public function setModel($model_namespace)
0 ignored issues
show
Coding Style Naming introduced by
The parameter $model_namespace is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
91 159
    {
92 1
        if (! class_exists($model_namespace)) {
93
            throw new \Exception('This model does not exist.', 404);
94
        }
95 159
96 159
        $this->model = new $model_namespace();
0 ignored issues
show
Documentation Bug introduced by
It seems like new $model_namespace() of type object is incompatible with the declared type string of property $model.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
97 159
        $this->query = $this->model->select('*');
98 159
        $this->entry = null;
99
    }
100
101
    /**
102
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function;.
103
     *
104
     * @return [Eloquent Collection]
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...
105 159
     */
106
    public function getModel()
107 159
    {
108
        return $this->model;
109
    }
110
111
    /**
112
     * Get the database connection, as specified in the .env file or overwritten by the property on the model.
113 3
     */
114
    private function getSchema()
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...
115 3
    {
116
        return \Schema::setConnection($this->getModel()->getConnection());
0 ignored issues
show
Bug introduced by
The method getConnection cannot be called on $this->getModel() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
117
    }
118
119
    /**
120
     * Set the route for this CRUD.
121
     * Ex: admin/article.
122
     *
123
     * @param [string] Route name.
124
     * @param [array] Parameters.
125
     */
126
    public function setRoute($route)
127
    {
128
        $this->route = $route;
129
    }
130
131
    /**
132
     * Set the route for this CRUD using the route name.
133
     * Ex: admin.article.
134
     *
135
     * @param [string] Route name.
136
     * @param [array] Parameters.
137 1
     */
138
    public function setRouteName($route, $parameters = [])
139 1
    {
140
        $complete_route = $route.'.index';
141 1
142 1
        if (! \Route::has($complete_route)) {
143
            throw new \Exception('There are no routes for this route name.', 404);
144
        }
145
146
        $this->route = route($complete_route, $parameters);
147
        $this->initButtons();
148
    }
149
150
    /**
151
     * Get the current CrudController route.
152
     *
153
     * Can be defined in the CrudController with:
154
     * - $this->crud->setRoute(config('backpack.base.route_prefix').'/article')
155
     * - $this->crud->setRouteName(config('backpack.base.route_prefix').'.article')
156
     * - $this->crud->route = config('backpack.base.route_prefix')."/article"
157
     *
158
     * @return [string]
0 ignored issues
show
Documentation introduced by
The doc-type [string] 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 getRoute()
161
    {
162
        return $this->route;
163
    }
164
165
    /**
166
     * Set the entity name in singular and plural.
167
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
168
     *
169
     * @param [string] Entity name, in singular. Ex: article
170
     * @param [string] Entity name, in plural. Ex: articles
171
     */
172
    public function setEntityNameStrings($singular, $plural)
173
    {
174
        $this->entity_name = $singular;
175
        $this->entity_name_plural = $plural;
176
    }
177
178
    // -----------------------------------------------
179
    // ACTIONS - the current operation being processed
180
    // -----------------------------------------------
181
182
    /**
183
     * Get the action being performed by the controller,
184
     * including middleware names, route name, method name,
185
     * namespace, prefix, etc.
186
     *
187
     * @return string The EntityCrudController route action array.
188
     */
189
    public function getAction()
190
    {
191 2
        return $this->request->route()->getAction();
192 2
    }
193 2
194
    /**
195
     * Get the full name of the controller method
196
     * currently being called (including namespace).
197
     *
198
     * @return string The EntityCrudController full method name with namespace.
199
     */
200
    public function getActionName()
201
    {
202
        return $this->request->route()->getActionName();
203
    }
204
205
    /**
206
     * Get the name of the controller method
207
     * currently being called.
208
     *
209
     * @return string The EntityCrudController method name.
210
     */
211
    public function getActionMethod()
212
    {
213
        return $this->request->route()->getActionMethod();
214
    }
215
216
    /**
217
     * Check if the controller method being called
218
     * matches a given string.
219
     *
220
     * @param  string $methodName   Name of the method (ex: index, create, update)
221
     * @return bool                 Whether the condition is met or not.
222
     */
223
    public function actionIs($methodName)
224
    {
225
        return $methodName === $this->getActionMethod();
226
    }
227
228
    // ----------------------------------
229
    // Miscellaneous functions or methods
230
    // ----------------------------------
231
232
    /**
233
     * Return the first element in an array that has the given 'type' attribute.
234
     *
235
     * @param string $type
236
     * @param array  $array
237
     *
238
     * @return array
239
     */
240
    public function getFirstOfItsTypeInArray($type, $array)
241
    {
242
        return array_first($array, function ($item) use ($type) {
243
            return $item['type'] == $type;
244
        });
245
    }
246
247
    // ------------
248
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
249
    // ------------
250
    //
251
    // TODO:
252
    // - figure out if they are really needed
253
    // - comments inside the function to explain how they work
254
    // - write docblock for them
255
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
256
257
    public function sync($type, $fields, $attributes)
258
    {
259
        if (! empty($this->{$type})) {
260
            $this->{$type} = array_map(function ($field) use ($fields, $attributes) {
261
                if (in_array($field['name'], (array) $fields)) {
262
                    $field = array_merge($field, $attributes);
263
                }
264
265
                return $field;
266
            }, $this->{$type});
267 9
        }
268
    }
269 9
270
    /**
271 9
     * @deprecated No longer used by internal code and not recommended.
272 9
     */
273
    public function setSort($items, $order)
274
    {
275 9
        $this->sort[$items] = $order;
276 9
    }
277
278
    /**
279 9
     * @deprecated No longer used by internal code and not recommended.
280 9
     */
281 9
    public function sort($items)
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...
282
    {
283 9
        if (array_key_exists($items, $this->sort)) {
284
            $elements = [];
285
286
            foreach ($this->sort[$items] as $item) {
287
                if (is_numeric($key = array_search($item, array_column($this->{$items}, 'name')))) {
288
                    $elements[] = $this->{$items}[$key];
289
                }
290
            }
291
292
            return $this->{$items} = array_merge($elements, array_filter($this->{$items}, function ($item) use ($items) {
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...
293
                return ! in_array($item['name'], $this->sort[$items]);
294
            }));
295
        }
296
297
        return $this->{$items};
298
    }
299
300
    /**
301
     * Get the Eloquent Model name from the given relation definition string.
302
     *
303
     * @example For a given string 'company' and a relation between App/Models/User and App/Models/Company, defined by a
304
     *          company() method on the user model, the 'App/Models/Company' string will be returned.
305
     *
306
     * @example For a given string 'company.address' and a relation between App/Models/User, App/Models/Company and
307
     *          App/Models/Address defined by a company() method on the user model and an address() method on the
308
     *          company model, the 'App/Models/Address' string will be returned.
309
     *
310
     * @param string $relationString Relation string. A dot notation can be used to chain multiple relations.
311
     * @param int $length Optionally specify the number of relations to omit from the start of the relation string. If
0 ignored issues
show
Documentation introduced by
Should the type for parameter $length not be integer|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...
312
     *        the provided length is negative, then that many relations will be omitted from the end of the relation
313
     *        string.
314
     * @param \Illuminate\Database\Eloquent\Model $model Optionally specify a different model than the one in the crud object.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $model not be \Illuminate\Database\Eloquent\Model|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...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 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...
315
     *
316
     * @return string Relation model name.
317
     */
318
    public function getRelationModel($relationString, $length = null, $model = null)
319
    {
320
        $relationArray = explode('.', $relationString);
321
322
        if (! isset($length)) {
323
            $length = count($relationArray);
324
        }
325
326
        if (! isset($model)) {
327
            $model = $this->model;
328
        }
329
330
        $result = array_reduce(array_splice($relationArray, 0, $length), function ($obj, $method) {
331
            return $obj->$method()->getRelated();
332
        }, $model);
333
334
        return get_class($result);
335
    }
336
337
    /**
338
     * Get the given attribute from a model or models resulting from the specified relation string (eg: the list of streets from
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 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...
339
     * the many addresses of the company of a given user).
340
     *
341
     * @param \Illuminate\Database\Eloquent\Model $model Model (eg: user).
342
     * @param string $relationString Model relation. Can be a string representing the name of a relation method in the given
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 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...
343
     *        Model or one from a different Model through multiple relations. A dot notation can be used to specify
344
     *        multiple relations (eg: user.company.address).
345
     * @param string $attribute The attribute from the relation model (eg: the street attribute from the address model).
346
     *
347
     * @return array An array containing a list of attributes from the resulting model.
348
     */
349
    public function getModelAttributeFromRelation($model, $relationString, $attribute)
350
    {
351
        $endModels = $this->getRelationModelInstances($model, $relationString);
352
        $attributes = [];
353
        foreach ($endModels as $model) {
354
            if ($model->{$attribute}) {
355
                $attributes[] = $model->{$attribute};
356
            }
357
        }
358
359
        return $attributes;
360
    }
361
362
    /**
363
     * Traverse the tree of relations for the given model, defined by the given relation string, and return the ending
364
     * associated model instance or instances.
365
     *
366
     * @param \Illuminate\Database\Eloquent\Model $model The CRUD model.
367
     * @param string $relationString Relation string. A dot notation can be used to chain multiple relations.
368
     * @return array An array of the associated model instances defined by the relation string.
369
     */
370
    private function getRelationModelInstances($model, $relationString)
371
    {
372
        $relationArray = explode('.', $relationString);
373
        $firstRelationName = array_first($relationArray);
374
        $relation = $model->{$firstRelationName};
375
376
        $results = [];
377
        if (! empty($relation)) {
378
            if ($relation instanceof Collection) {
379
                $currentResults = $relation->toArray();
380
            } else {
381
                $currentResults[] = $relation;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$currentResults was never initialized. Although not strictly required by PHP, it is generally a good practice to add $currentResults = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
382
            }
383
384
            array_shift($relationArray);
385
386
            if (! empty($relationArray)) {
387
                foreach ($currentResults as $currentResult) {
388
                    $results = array_merge($results, $this->getRelationModelInstances($currentResult, implode('.', $relationArray)));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 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...
389
                }
390
            } else {
391
                $results = $currentResults;
392
            }
393
        }
394
395
        return $results;
396
    }
397
}
398