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

Passed
Push — datatable-single-component ( 863f17...49cc78 )
by Pedro
13:04
created

CrudPanel::getSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
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\HasViewNamespaces;
18
use Backpack\CRUD\app\Library\CrudPanel\Traits\HeadingsAndTitles;
19
use Backpack\CRUD\app\Library\CrudPanel\Traits\Input;
20
use Backpack\CRUD\app\Library\CrudPanel\Traits\Macroable;
21
use Backpack\CRUD\app\Library\CrudPanel\Traits\MorphRelationships;
22
use Backpack\CRUD\app\Library\CrudPanel\Traits\Operations;
23
use Backpack\CRUD\app\Library\CrudPanel\Traits\Query;
24
use Backpack\CRUD\app\Library\CrudPanel\Traits\Read;
25
use Backpack\CRUD\app\Library\CrudPanel\Traits\Relationships;
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Librar...el\Traits\Relationships was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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

472
            if (isset($decodedAttribute[app()->/** @scrutinizer ignore-call */ getLocale()])) {
Loading history...
473
                return $decodedAttribute[app()->getLocale()];
474
            } else {
475
                return Arr::first($decodedAttribute);
476
            }
477
        }
478
479
        return $value;
480
    }
481
482
    public function setLocaleOnModel(Model $model)
483
    {
484
        $useFallbackLocale = $this->shouldUseFallbackLocale();
485
486
        if (method_exists($model, 'translationEnabled') && $model->translationEnabled()) {
487
            $locale = $this->getRequest()->input('_locale', app()->getLocale());
488
            if (in_array($locale, array_keys($model->getAvailableLocales()))) {
0 ignored issues
show
Bug introduced by
It seems like $model->getAvailableLocales() can also be of type Illuminate\Database\Eloquent\Builder and Illuminate\Database\Eloq...gHasThroughRelationship; however, parameter $array of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

488
            if (in_array($locale, array_keys(/** @scrutinizer ignore-type */ $model->getAvailableLocales()))) {
Loading history...
489
                $model->setLocale(! is_bool($useFallbackLocale) ? $useFallbackLocale : $locale);
0 ignored issues
show
introduced by
The condition is_bool($useFallbackLocale) is always true.
Loading history...
490
                $model->useFallbackLocale = (bool) $useFallbackLocale;
491
            }
492
        }
493
494
        return $model;
495
    }
496
497
    /**
498
     * Traverse the tree of relations for the given model, defined by the given relation string, and return the ending
499
     * associated model instance or instances.
500
     *
501
     * @param  Model  $model  The CRUD model.
502
     * @param  string  $relationString  Relation string. A dot notation can be used to chain multiple relations.
503
     * @return array An array of the associated model instances defined by the relation string.
504
     */
505
    private function getRelatedEntries($model, $relationString)
506
    {
507
        $relationArray = explode('.', $this->getOnlyRelationEntity(['entity' => $relationString]));
508
        $firstRelationName = Arr::first($relationArray);
509
        $relation = $model->{$firstRelationName};
510
511
        $results = [];
512
        if (! is_null($relation)) {
513
            if ($relation instanceof Collection) {
514
                $currentResults = $relation->all();
515
            } elseif (is_array($relation)) {
516
                $currentResults = $relation;
517
            } elseif ($relation instanceof Model) {
518
                $currentResults = [$relation];
519
            } else {
520
                $currentResults = [];
521
            }
522
523
            array_shift($relationArray);
524
525
            if (! empty($relationArray)) {
526
                foreach ($currentResults as $currentResult) {
527
                    $results = array_merge_recursive($results, $this->getRelatedEntries($currentResult, implode('.', $relationArray)));
528
                }
529
            } else {
530
                $relatedClass = get_class($model->{$firstRelationName}()->getRelated());
531
                $results[$relatedClass] = $currentResults;
532
            }
533
        }
534
535
        return $results;
536
    }
537
538
    /**
539
     * Allow to add an attribute to multiple fields/columns/filters/buttons at same time.
540
     *
541
     * Using the fluent syntax allow the developer to add attributes to multiple fields at the same time. Eg:
542
     *
543
     * - CRUD::group(CRUD::field('price')->type('number'), CRUD::field('title')->type('text'))->tab('both_on_same_tab');
544
     *
545
     * @param  mixed fluent syntax objects.
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Library\CrudPanel\fluent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
546
     * @return CrudObjectGroup
547
     */
548
    public function group(...$objects)
549
    {
550
        return new CrudObjectGroup(...$objects);
551
    }
552
}
553