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

Test Setup Failed
Push — master ( 775b4e...bb1f8b )
by Cristian
32:16 queued 15:14
created

CrudPanel::setModel()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel;
4
5
use Backpack\CRUD\app\Library\CrudPanel\Traits\Access;
6
use Backpack\CRUD\app\Library\CrudPanel\Traits\AutoFocus;
7
use Backpack\CRUD\app\Library\CrudPanel\Traits\AutoSet;
8
use Backpack\CRUD\app\Library\CrudPanel\Traits\Buttons;
9
use Backpack\CRUD\app\Library\CrudPanel\Traits\Columns;
10
use Backpack\CRUD\app\Library\CrudPanel\Traits\Create;
11
use Backpack\CRUD\app\Library\CrudPanel\Traits\Delete;
12
use Backpack\CRUD\app\Library\CrudPanel\Traits\Errors;
13
use Backpack\CRUD\app\Library\CrudPanel\Traits\FakeColumns;
14
use Backpack\CRUD\app\Library\CrudPanel\Traits\FakeFields;
15
use Backpack\CRUD\app\Library\CrudPanel\Traits\Fields;
16
use Backpack\CRUD\app\Library\CrudPanel\Traits\Filters;
17
use Backpack\CRUD\app\Library\CrudPanel\Traits\HeadingsAndTitles;
18
use Backpack\CRUD\app\Library\CrudPanel\Traits\Macroable;
19
use Backpack\CRUD\app\Library\CrudPanel\Traits\Operations;
20
use Backpack\CRUD\app\Library\CrudPanel\Traits\Query;
21
use Backpack\CRUD\app\Library\CrudPanel\Traits\Read;
22
use Backpack\CRUD\app\Library\CrudPanel\Traits\Relationships;
23
use Backpack\CRUD\app\Library\CrudPanel\Traits\Reorder;
24
use Backpack\CRUD\app\Library\CrudPanel\Traits\SaveActions;
25
use Backpack\CRUD\app\Library\CrudPanel\Traits\Search;
26
use Backpack\CRUD\app\Library\CrudPanel\Traits\Settings;
27
use Backpack\CRUD\app\Library\CrudPanel\Traits\Tabs;
28
use Backpack\CRUD\app\Library\CrudPanel\Traits\Update;
29
use Backpack\CRUD\app\Library\CrudPanel\Traits\Validation;
30
use Backpack\CRUD\app\Library\CrudPanel\Traits\Views;
31
use Exception;
32
use Illuminate\Database\Eloquent\Collection;
33
use Illuminate\Database\Eloquent\Model;
34
use Illuminate\Database\Eloquent\Relations\Relation;
35
use Illuminate\Support\Arr;
36
37
class CrudPanel
38
{
39
    // load all the default CrudPanel features
40
    use Create, Read, Search, Update, Delete, Errors, Reorder, Access, Columns, Fields, Query, Buttons, AutoSet, FakeFields, FakeColumns, AutoFocus, Filters, Tabs, Views, Validation, HeadingsAndTitles, Operations, SaveActions, Settings, Relationships;
0 ignored issues
show
introduced by
The trait Backpack\CRUD\app\Library\CrudPanel\Traits\Buttons requires some properties which are not provided by Backpack\CRUD\app\Library\CrudPanel\CrudPanel: $stack, $name
Loading history...
Bug introduced by
The trait Backpack\CRUD\app\Librar...Panel\Traits\Operations requires the property $action which is not provided by Backpack\CRUD\app\Library\CrudPanel\CrudPanel.
Loading history...
introduced by
The trait Backpack\CRUD\app\Library\CrudPanel\Traits\Filters requires some properties which are not provided by Backpack\CRUD\app\Library\CrudPanel\CrudPanel: $values, $logic, $fallbackLogic, $name
Loading history...
41
    // allow developers to add their own closures to this object
42
    use Macroable;
0 ignored issues
show
Bug introduced by
The trait Backpack\CRUD\app\Librar...dPanel\Traits\Macroable requires the property $name which is not provided by Backpack\CRUD\app\Library\CrudPanel\CrudPanel.
Loading history...
43
44
    // --------------
45
    // CRUD variables
46
    // --------------
47
    // These variables are passed to the CRUD views, inside the $crud variable.
48
    // All variables are public, so they can be modified from your EntityCrudController.
49
    // All functions and methods are also public, so they can be used in your EntityCrudController to modify these variables.
50
51
    public $model = "\App\Models\Entity"; // what's the namespace for your entity's model
52
    public $route; // what route have you defined for your entity? used for links.
53
    public $entity_name = 'entry'; // what name will show up on the buttons, in singural (ex: Add entity)
54
    public $entity_name_plural = 'entries'; // what name will show up on the buttons, in plural (ex: Delete 5 entities)
55
56
    public $entry;
57
58
    protected $request;
59
60
    // The following methods are used in CrudController or your EntityCrudController to manipulate the variables above.
61
62
    public function __construct()
63
    {
64
        $this->setRequest();
65
66
        if ($this->getCurrentOperation()) {
67
            $this->setOperation($this->getCurrentOperation());
68
        }
69
    }
70
71
    /**
72
     * Set the request instance for this CRUD.
73
     *
74
     * @param \Illuminate\Http\Request $request
75
     */
76
    public function setRequest($request = null)
77
    {
78
        $this->request = $request ?? \Request::instance();
79
    }
80
81
    /**
82
     * [getRequest description].
83
     * @return [type] [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
84
     */
85
    public function getRequest()
86
    {
87
        return $this->request;
88
    }
89
90
    // ------------------------------------------------------
91
    // BASICS - model, route, entity_name, entity_name_plural
92
    // ------------------------------------------------------
93
94
    /**
95
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
96
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
97
     *
98
     * @param string $model_namespace Full model namespace. Ex: App\Models\Article
99
     *
100
     * @throws \Exception in case the model does not exist
101
     */
102
    public function setModel($model_namespace)
103
    {
104
        if (! class_exists($model_namespace)) {
105
            throw new \Exception('The model does not exist.', 500);
106
        }
107
108
        if (! method_exists($model_namespace, 'hasCrudTrait')) {
109
            throw new \Exception('Please use CrudTrait on the model.', 500);
110
        }
111
112
        $this->model = new $model_namespace();
113
        $this->query = $this->model->select('*');
114
        $this->entry = null;
115
    }
116
117
    /**
118
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function.
119
     *
120
     * @return string|\Illuminate\Database\Eloquent\Model
121
     */
122
    public function getModel()
123
    {
124
        return $this->model;
125
    }
126
127
    /**
128
     * Get the database connection, as specified in the .env file or overwritten by the property on the model.
129
     *
130
     * @return \Illuminate\Database\Schema\Builder
131
     */
132
    private function getSchema()
133
    {
134
        return $this->getModel()->getConnection()->getSchemaBuilder();
135
    }
136
137
    /**
138
     * Check if the database connection driver is using mongodb.
139
     *
140
     * DEPRECATION NOTICE: This method is no longer used and will be removed in future versions of Backpack
141
     *
142
     * @deprecated
143
     * @return bool
144
     */
145
    private function driverIsMongoDb()
146
    {
147
        return $this->getSchema()->getConnection()->getConfig()['driver'] === 'mongodb';
148
    }
149
150
    /**
151
     * Check if the database connection is any sql driver.
152
     *
153
     * @return bool
154
     */
155
    private function driverIsSql()
156
    {
157
        $driver = $this->getSchema()->getConnection()->getConfig('driver');
158
159
        return in_array($driver, $this->getSqlDriverList());
160
    }
161
162
    /**
163
     * Get SQL driver list.
164
     *
165
     * @return array
166
     */
167
    public function getSqlDriverList()
168
    {
169
        return ['mysql', 'sqlsrv', 'sqlite', 'pgsql'];
170
    }
171
172
    /**
173
     * Set the route for this CRUD.
174
     * Ex: admin/article.
175
     *
176
     * @param string $route Route name.
177
     */
178
    public function setRoute($route)
179
    {
180
        $this->route = $route;
181
    }
182
183
    /**
184
     * Set the route for this CRUD using the route name.
185
     * Ex: admin.article.
186
     *
187
     * @param string $route      Route name.
188
     * @param array  $parameters Parameters.
189
     *
190
     * @throws \Exception
191
     */
192
    public function setRouteName($route, $parameters = [])
193
    {
194
        $complete_route = $route.'.index';
195
196
        if (! \Route::has($complete_route)) {
197
            throw new \Exception('There are no routes for this route name.', 404);
198
        }
199
200
        $this->route = route($complete_route, $parameters);
201
    }
202
203
    /**
204
     * Get the current CrudController route.
205
     *
206
     * Can be defined in the CrudController with:
207
     * - $this->crud->setRoute(config('backpack.base.route_prefix').'/article')
208
     * - $this->crud->setRouteName(config('backpack.base.route_prefix').'.article')
209
     * - $this->crud->route = config('backpack.base.route_prefix')."/article"
210
     *
211
     * @return string
212
     */
213
    public function getRoute()
214
    {
215
        return $this->route;
216
    }
217
218
    /**
219
     * Set the entity name in singular and plural.
220
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
221
     *
222
     * @param string $singular Entity name, in singular. Ex: article
223
     * @param string $plural   Entity name, in plural. Ex: articles
224
     */
225
    public function setEntityNameStrings($singular, $plural)
226
    {
227
        $this->entity_name = $singular;
228
        $this->entity_name_plural = $plural;
229
    }
230
231
    // -----------------------------------------------
232
    // ACTIONS - the current operation being processed
233
    // -----------------------------------------------
234
235
    /**
236
     * Get the action being performed by the controller,
237
     * including middleware names, route name, method name,
238
     * namespace, prefix, etc.
239
     *
240
     * @return string The EntityCrudController route action array.
241
     */
242
    public function getAction()
243
    {
244
        return $this->getRequest()->route()->getAction();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getRequest()->route()->getAction() also could return the type array which is incompatible with the documented return type string.
Loading history...
245
    }
246
247
    /**
248
     * Get the full name of the controller method
249
     * currently being called (including namespace).
250
     *
251
     * @return string The EntityCrudController full method name with namespace.
252
     */
253
    public function getActionName()
254
    {
255
        return $this->getRequest()->route()->getActionName();
256
    }
257
258
    /**
259
     * Get the name of the controller method
260
     * currently being called.
261
     *
262
     * @return string The EntityCrudController method name.
263
     */
264
    public function getActionMethod()
265
    {
266
        return $this->getRequest()->route()->getActionMethod();
267
    }
268
269
    /**
270
     * Check if the controller method being called
271
     * matches a given string.
272
     *
273
     * @param string $methodName Name of the method (ex: index, create, update)
274
     *
275
     * @return bool Whether the condition is met or not.
276
     */
277
    public function actionIs($methodName)
278
    {
279
        return $methodName === $this->getActionMethod();
280
    }
281
282
    // ----------------------------------
283
    // Miscellaneous functions or methods
284
    // ----------------------------------
285
286
    /**
287
     * Return the first element in an array that has the given 'type' attribute.
288
     *
289
     * @param string $type
290
     * @param array  $array
291
     *
292
     * @return array
293
     */
294
    public function getFirstOfItsTypeInArray($type, $array)
295
    {
296
        return Arr::first($array, function ($item) use ($type) {
297
            return $item['type'] == $type;
298
        });
299
    }
300
301
    // ------------
302
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
303
    // ------------
304
    //
305
    // TODO:
306
    // - figure out if they are really needed
307
    // - comments inside the function to explain how they work
308
    // - write docblock for them
309
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
310
311
    public function sync($type, $fields, $attributes)
312
    {
313
        if (! empty($this->{$type})) {
314
            $this->{$type} = array_map(function ($field) use ($fields, $attributes) {
315
                if (in_array($field['name'], (array) $fields)) {
316
                    $field = array_merge($field, $attributes);
317
                }
318
319
                return $field;
320
            }, $this->{$type});
321
        }
322
    }
323
324
    /**
325
     * Get the Eloquent Model name from the given relation definition string.
326
     *
327
     * @example For a given string 'company' and a relation between App/Models/User and App/Models/Company, defined by a
328
     *          company() method on the user model, the 'App/Models/Company' string will be returned.
329
     * @example For a given string 'company.address' and a relation between App/Models/User, App/Models/Company and
330
     *          App/Models/Address defined by a company() method on the user model and an address() method on the
331
     *          company model, the 'App/Models/Address' string will be returned.
332
     *
333
     * @param string                              $relationString Relation string. A dot notation can be used to chain multiple relations.
334
     * @param int                                 $length         Optionally specify the number of relations to omit from the start of the relation string. If
335
     *                                                            the provided length is negative, then that many relations will be omitted from the end of the relation
336
     *                                                            string.
337
     * @param \Illuminate\Database\Eloquent\Model $model          Optionally specify a different model than the one in the crud object.
338
     *
339
     * @return string Relation model name.
340
     */
341
    public function getRelationModel($relationString, $length = null, $model = null)
342
    {
343
        $relationArray = explode('.', $relationString);
344
345
        if (! isset($length)) {
346
            $length = count($relationArray);
347
        }
348
349
        if (! isset($model)) {
350
            $model = $this->model;
351
        }
352
353
        $result = array_reduce(array_splice($relationArray, 0, $length), function ($obj, $method) {
354
            try {
355
                $result = $obj->$method();
356
357
                return $result->getRelated();
358
            } catch (Exception $e) {
359
                return $obj;
360
            }
361
        }, $model);
362
363
        return get_class($result);
364
    }
365
366
    /**
367
     * Get the given attribute from a model or models resulting from the specified relation string (eg: the list of streets from
368
     * the many addresses of the company of a given user).
369
     *
370
     * @param \Illuminate\Database\Eloquent\Model $model          Model (eg: user).
371
     * @param string                              $relationString Model relation. Can be a string representing the name of a relation method in the given
372
     *                                                            Model or one from a different Model through multiple relations. A dot notation can be used to specify
373
     *                                                            multiple relations (eg: user.company.address).
374
     * @param string                              $attribute      The attribute from the relation model (eg: the street attribute from the address model).
375
     *
376
     * @return array An array containing a list of attributes from the resulting model.
377
     */
378
    public function getRelatedEntriesAttributes($model, $relationString, $attribute)
379
    {
380
        $endModels = $this->getRelatedEntries($model, $relationString);
381
        $attributes = [];
382
        foreach ($endModels as $model => $entries) {
0 ignored issues
show
introduced by
$model is overwriting one of the parameters of this function.
Loading history...
383
            $model_instance = new $model();
384
            $modelKey = $model_instance->getKeyName();
385
386
            if (is_array($entries)) {
387
                //if attribute does not exist in main array we have more than one entry OR the attribute
388
                //is an acessor that is not in $appends property of model.
389
                if (! isset($entries[$attribute])) {
390
                    //we first check if we don't have the attribute because it's and acessor that is not in appends.
391
                    if ($model_instance->hasGetMutator($attribute) && isset($entries[$modelKey])) {
392
                        $entry_in_database = $model_instance->find($entries[$modelKey]);
393
                        $attributes[$entry_in_database->{$modelKey}] = $this->parseTranslatableAttributes($model_instance, $attribute, $entry_in_database->{$attribute});
394
                    } else {
395
                        //we have multiple entries
396
                        //for each entry we check if $attribute exists in array or try to check if it's an acessor.
397
                        foreach ($entries as $entry) {
398
                            if (isset($entry[$attribute])) {
399
                                $attributes[$entry[$modelKey]] = $this->parseTranslatableAttributes($model_instance, $attribute, $entry[$attribute]);
400
                            } else {
401
                                if ($model_instance->hasGetMutator($attribute)) {
402
                                    $entry_in_database = $model_instance->find($entry[$modelKey]);
403
                                    $attributes[$entry_in_database->{$modelKey}] = $this->parseTranslatableAttributes($model_instance, $attribute, $entry_in_database->{$attribute});
404
                                }
405
                            }
406
                        }
407
                    }
408
                } else {
409
                    //if we have the attribute we just return it, does not matter if it is direct attribute or an acessor added in $appends.
410
                    $attributes[$entries[$modelKey]] = $this->parseTranslatableAttributes($model_instance, $attribute, $entries[$attribute]);
411
                }
412
            }
413
        }
414
415
        return $attributes;
416
    }
417
418
    /**
419
     * Parse translatable attributes from a model or models resulting from the specified relation string.
420
     *
421
     * @param \Illuminate\Database\Eloquent\Model $model          Model (eg: user).
422
     * @param string                              $attribute      The attribute from the relation model (eg: the street attribute from the address model).
423
     * @param string                              $value          Attribute value translatable or not
424
     *
425
     * @return string A string containing the translated attributed based on app()->getLocale()
426
     */
427
    public function parseTranslatableAttributes($model, $attribute, $value)
428
    {
429
        if (! method_exists($model, 'isTranslatableAttribute')) {
430
            return $value;
431
        }
432
433
        if (! $model->isTranslatableAttribute($attribute)) {
434
            return $value;
435
        }
436
437
        if (! is_array($value)) {
0 ignored issues
show
introduced by
The condition is_array($value) is always false.
Loading history...
438
            $decodedAttribute = json_decode($value, true);
439
        } else {
440
            $decodedAttribute = $value;
441
        }
442
443
        if (is_array($decodedAttribute) && ! empty($decodedAttribute)) {
444
            if (isset($decodedAttribute[app()->getLocale()])) {
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

444
            if (isset($decodedAttribute[app()->/** @scrutinizer ignore-call */ getLocale()])) {
Loading history...
445
                return $decodedAttribute[app()->getLocale()];
446
            } else {
447
                return Arr::first($decodedAttribute);
448
            }
449
        }
450
451
        return $value;
452
    }
453
454
    /**
455
     * Traverse the tree of relations for the given model, defined by the given relation string, and return the ending
456
     * associated model instance or instances.
457
     *
458
     * @param \Illuminate\Database\Eloquent\Model $model          The CRUD model.
459
     * @param string                              $relationString Relation string. A dot notation can be used to chain multiple relations.
460
     *
461
     * @return array An array of the associated model instances defined by the relation string.
462
     */
463
    private function getRelatedEntries($model, $relationString)
464
    {
465
        $relationArray = explode('.', $relationString);
466
        $firstRelationName = Arr::first($relationArray);
467
        $relation = $model->{$firstRelationName};
468
469
        $results = [];
470
        if (! is_null($relation)) {
471
            if ($relation instanceof Collection) {
472
                $currentResults = $relation->all();
473
            } elseif (is_array($relation)) {
474
                $currentResults = $relation;
475
            } elseif ($relation instanceof Model) {
476
                $currentResults = [$relation];
477
            } else {
478
                $currentResults = [];
479
            }
480
481
            array_shift($relationArray);
482
483
            if (! empty($relationArray)) {
484
                foreach ($currentResults as $currentResult) {
485
                    $results = array_merge_recursive($results, $this->getRelatedEntries($currentResult, implode('.', $relationArray)));
486
                }
487
            } else {
488
                $relatedClass = get_class($model->{$firstRelationName}()->getRelated());
489
                $results[$relatedClass] = $currentResults;
490
            }
491
        }
492
493
        return $results;
494
    }
495
}
496