GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 8671c1...ad075b )
by Aden
02:50
created

ModelAdmin::getCreateRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace LaravelFlare\Flare\Admin\Models;
4
5
use Illuminate\Support\Str;
6
use LaravelFlare\Flare\Admin\Admin;
7
use LaravelFlare\Flare\Exceptions\ModelAdminException;
8
use LaravelFlare\Flare\Admin\Models\Traits\ModelSaving;
9
use LaravelFlare\Flare\Admin\Models\Traits\ModelQuerying;
10
use LaravelFlare\Flare\Contracts\ModelAdmin\ModelQueryable;
11
12
class ModelAdmin extends Admin implements ModelQueryable
13
{
14
    use ModelQuerying;
15
    use ModelSaving;
16
17
    /**
18
     * Class of Model to Manage.
19
     * 
20
     * @var string
21
     */
22
    protected $managedModel;
23
24
    /**
25
     * Entiy Title .
26
     *
27
     * @var string
28
     */
29
    protected $entityTitle;
30
31
    /**
32
     * Plural Entity Title.
33
     *
34
     * @var string
35
     */
36
    protected $pluralEntityTitle;
37
38
    /**
39
     * Validation Rules for onCreate, onEdit actions.
40
     * 
41
     * @var array
42
     */
43
    protected $rules = [];
44
45
    /**
46
     * Columns for Model.
47
     *
48
     * Defines which fields to show in the listing tables output.
49
     * 
50
     * @var array
51
     */
52
    protected $columns = [];
53
54
    /**
55
     * Map Model Attributes to FieldTypes with
56
     * additional parameters which will be output
57
     * as fields when viewing, editting or adding
58
     * a new model entry.
59
     * 
60
     * @var array
61
     */
62
    protected $fields = [];
63
64
    /**
65
     * Columns for Model are Sortable.
66
     *
67
     * @var bool
68
     */
69
    protected $sortable = true;
70
71
    /**
72
     * The Controller to be used by the Model Admin.
73
     *
74
     * This defaults to parent::getController()
75
     * if it has been left undefined. 
76
     * 
77
     * @var string
78
     */
79
    protected $controller = '\LaravelFlare\Flare\Admin\Models\ModelAdminController';
80
81
    /**
82
     * The Policy used for the Model Authorization logic.
83
     *
84
     * This class should implement the ModelAdminPoliceable which
85
     * includes authorization checks for the create, view, edit and delete actions.
86
     * 
87
     * @var string
88
     */
89
    protected $policy = '\LaravelFlare\Flare\Permissions\ModelAdminPolicy';
90
91
    /**
92
     * The current model to be managed.
93
     * 
94
     * @var Model
95
     */
96
    public $model;
97
98
    /**
99
     * __construct.
100
     */
101
    public function __construct()
102
    {
103
        $this->getManagedModel();
104
105
        $this->model = $this->model();
106
    }
107
108
    /**
109
     * Returns a Model Instance.
110
     * 
111
     * @return Model
112
     */
113
    public function model()
114
    {
115
        if (!$this->model) {
116
            $class = $this->getManagedModel();
117
118
            return $this->model = new $class();
119
        }
120
121
        return $this->model;
122
    }
123
124
    /**
125
     * Returns a New Model Instance.
126
     *
127
     * @return Model
128
     */
129
    public function newModel()
130
    {
131
        $class = self::getManagedModel();
132
133
        return new $class();
134
    }
135
136
    /**
137
     * Returns the Managed Model Class.
138
     * 
139
     * @return string
140
     */
141
    public function getManagedModel()
142
    {
143
        if (!isset($this->managedModel) || $this->managedModel === null) {
144
            throw new ModelAdminException('You have a ModelAdmin which does not have a model assigned to it. ModelAdmins must include a model to manage.', 1);
145
        }
146
147
        return $this->managedModel;
148
    }
149
150
    /**
151
     * Set the Managed Model Class.
152
     * 
153
     * @param string $managedModel
154
     */
155
    public function setManagedModel($managedModel = null)
156
    {
157
        $this->managedModel = $managedModel;
158
    }
159
160
    /**
161
     * Get the Entity Title.
162
     *
163
     * @return string
164
     */
165
    public function getEntityTitle()
166
    {
167
        if (!isset($this->entityTitle) || !$this->entityTitle) {
168
            return $this->getTitle();
169
        }
170
171
        return $this->entityTitle;
172
    }
173
174
    /**
175
     * Set Entity Title.
176
     *
177
     * @param string $entityTitle
178
     */
179
    public function setTitle($entityTitle = null)
180
    {
181
        $this->entityTitle = $title;
0 ignored issues
show
Bug introduced by
The variable $title does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
182
    }
183
184
    /**
185
     * Plural Entity Title
186
     *
187
     * @return string
188
     */
189
    public function getPluralEntityTitle()
190
    {
191
        if (!isset($this->pluralEntityTitle) || !$this->pluralEntityTitle) {
192
            return Str::plural($this->getEntityTitle());
193
        }
194
195
        return $this->pluralEntityTitle;
196
    }
197
198
    /**
199
     * Set Plural Title.
200
     * 
201
     * @param string $pluralEntityTitle
202
     */
203
    public function setPluralTitle($pluralEntityTitle = null)
204
    {
205
        $this->pluralEntityTitle = $pluralEntityTitle;
206
    }
207
208
209
    /**
210
     * Returns the Route Paramets.
211
     * 
212
     * @return array
213
     */
214
    public function routeParameters()
215
    {
216
        return array_merge(parent::routeParameters(), [
217
                                                    'model' => $this->managedModel,
218
                                                ]);
219
    }
220
221
    /**
222
     * Formats and returns the Columns.
223
     *
224
     * This is really gross, I'm removing it soon.
225
     * 
226
     * @return
227
     */
228
    public function getColumns()
229
    {
230
        $columns = [];
231
232
        foreach ($this->columns as $field => $fieldTitle) {
233
            if (in_array($field, $this->model->getFillable())) {
234
                if (!$field) {
235
                    $field = $fieldTitle;
236
                    $fieldTitle = Str::title($fieldTitle);
237
                }
238
                $columns[$field] = $fieldTitle;
239
                continue;
240
            }
241
242
            // We can replace this with data_get() I believe.
243
            if (($methodBreaker = strpos($field, '.')) !== false) {
244
                $method = substr($field, 0, $methodBreaker);
245
                if (method_exists($this->model, $method)) {
246
                    if (method_exists($this->model->$method(), $submethod = str_replace($method.'.', '', $field))) {
247
                        $this->model->$method()->$submethod();
248
249
                        $columns[$field] = $fieldTitle;
250
                        continue;
251
                    }
252
                }
253
            }
254
255
            if (is_numeric($field)) {
256
                $field = $fieldTitle;
257
                $fieldTitle = Str::title($fieldTitle);
258
            }
259
260
            $columns[$field] = $fieldTitle;
261
        }
262
263
        if (count($columns)) {
264
            return $columns;
265
        }
266
267
        return [$this->model->getKeyName() => $this->model->getKeyName()];
268
    }
269
270
    /**
271
     * Return the Validation Rules
272
     * 
273
     * @return array
274
     */
275
    public function getRules()
276
    {
277
        return $this->rules;
278
    }
279
280
    /**
281
     * Return the Create Model Entry Validation Rules
282
     * 
283
     * @return array
284
     */
285
    public function getCreateRules()
286
    {
287
        return $this->getRules();
288
    }
289
290
    /**
291
     * Return the Update Model Entry Validation Rules
292
     * 
293
     * @return array
294
     */
295
    public function getUpdateRules()
296
    {
297
        return $this->getRules();
298
    }
299
300
    /**
301
     * Gets an Attribute by the provided key
302
     * on either the current model or a provided model instance.
303
     * 
304
     * @param string $key
305
     * @param mixed  $model
306
     * 
307
     * @return mixed
308
     */
309
    public function getAttribute($key, $model = false)
310
    {
311
        if (!$key) {
312
            return;
313
        }
314
315
        if (!$model) {
316
            $model = $this->model;
317
        }
318
319
        if ($this->hasGetAccessor($key)) {
320
            $method = 'get'.Str::studly($key).'Attribute';
321
322
            return $this->{$method}($model);
323
        }
324
325
        if ($this->hasRelatedKey($key, $model)) {
326
            return $this->relatedKey($key, $model);
327
        }
328
329
        return $model->getAttribute($key);
330
    }
331
332
    /**
333
     * Determine if a get accessor exists for an attribute.
334
     *
335
     * @param string $key
336
     * 
337
     * @return bool
338
     */
339
    public function hasGetAccessor($key)
340
    {
341
        return method_exists($this, 'get'.Str::studly($key).'Attribute');
342
    }
343
344
    /**
345
     * Determines if a key resolved a related Model.
346
     * 
347
     * @param string $key
348
     * @param mixed  $model
349
     * 
350
     * @return bool
351
     */
352
    public function hasRelatedKey($key, $model = false)
353
    {
354
        if (!$model) {
355
            $model = $this->model;
356
        }
357
358
        if (($methodBreaker = strpos($key, '.')) !== false) {
359
            $method = substr($key, 0, $methodBreaker);
360
            if (method_exists($model, $method)) {
361
                return true;
362
            }
363
        }
364
365
        return false;
366
    }
367
368
    /**
369
     * Resolves a relation based on the key provided,
370
     * either on the current model or a provided model instance.
371
     * 
372
     * @param string $key
373
     * @param mixed  $model
374
     * 
375
     * @return mixed
376
     */
377
    public function relatedKey($key, $model = false)
378
    {
379
        if (!$model) {
380
            $model = $this->model;
381
        }
382
383
        if (($methodBreaker = strpos($key, '.')) !== false) {
384
            $method = substr($key, 0, $methodBreaker);
385
            if (method_exists($model, $method)) {
386
                if (method_exists($model->$method, $submethod = str_replace($method.'.', '', $key))) {
387
                    return $model->$method->$submethod();
388
                }
389
390
                if (isset($model->$method->$submethod)) {
391
                    return $model->$method->$submethod;
392
                }
393
394
                return $model->getRelationValue($method);
395
            }
396
        }
397
398
        return false;
399
    }
400
401
    /**
402
     * Set a given attribute on the model.
403
     *
404
     * @param string $key
405
     * @param mixed  $value
406
     */
407
    public function setAttribute($key, $value)
408
    {
409
        if ($this->hasSetMutator($key)) {
410
            $method = 'set'.Str::studly($key).'Attribute';
411
412
            return $this->{$method}($value);
413
        }
414
415
        $this->model->attributes[$key] = $value;
416
    }
417
418
    /**
419
     * Determine if a set mutator exists for an attribute.
420
     *
421
     * @param string $key
422
     * 
423
     * @return bool
424
     */
425
    public function hasSetMutator($key)
426
    {
427
        return method_exists($this, 'set'.Str::studly($key).'Attribute');
428
    }
429
430
    /**
431
     * Determine if a get mutator exists for an attribute.
432
     *
433
     * @param string $key
434
     * 
435
     * @return bool
436
     */
437
    public function hasGetMutator($key)
438
    {
439
        return method_exists($this, 'get'.Str::studly($key).'Attribute');
440
    }
441
442
    /**
443
     * Returns an array of Attribute Fields ready for output.
444
     * 
445
     * @return array
446
     */
447
    public function outputFields()
448
    {
449
        return $this->getFields();
450
    }
451
452
    /**
453
     * Gets the Managed Model Mapping.
454
     * 
455
     * @return array
456
     */
457
    public function getFields()
458
    {
459
        $this->setFields($this->fields);
460
461
        return $this->fields;
462
    }
463
464
    /**
465
     * Sets the Managed Model Mapping.
466
     * 
467
     * @param array $fields
468
     */
469
    public function setFields($fields = [])
470
    {
471
        $this->fields = $fields;
472
473
        $this->formatFields();
474
    }
475
476
    /**
477
     * Format the provided Attribute Fields into a more usable format.
478
     */
479
    protected function formatFields()
480
    {
481
        $fields = $this->fields;
482
483
        if (!$fields instanceof AttributeCollection) {
484
            $fields = new AttributeCollection($fields, $this);
485
        }
486
487
        return $this->fields = $fields->formatFields();
0 ignored issues
show
Documentation Bug introduced by
It seems like $fields->formatFields() of type object<LaravelFlare\Flar...ls\AttributeCollection> is incompatible with the declared type array of property $fields.

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...
488
    }
489
490
    /**
491
     * Determine if the Model Admin is sortable in it's list view.
492
     * 
493
     * @return bool
494
     */
495
    public function isSortable()
496
    {
497
        return isset($this->sortable) && $this->sortable ? true : false;
498
    }
499
500
    /**
501
     * Determine if the Model Admin is sortable by a defined key / column.
502
     *
503
     * @param string $key
504
     * 
505
     * @return bool
506
     */
507
    public function isSortableBy($key)
508
    {
509
        // Sorting is not allowed on Model Admin
510
        if (!$this->isSortable()) {
511
            return false;
512
        }
513
514
        // Key results are mutated, so sorting is not available
515
        if ($this->model()->hasGetMutator($key) || $this->hasGetMutator($key)) {
516
            return false;
517
        }
518
519
        // Key is a relation, so sorting is not available 
520
        if (strpos($key, '.') !== false) {
521
            return false;
522
        }
523
524
        return true;
525
    }
526
527
    /**
528
     * Determine if the Model Admin has Viewing Capabilities.
529
     * 
530
     * @return bool
531
     */
532
    public function hasViewing()
533
    {
534
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelViewing::class);
535
    }
536
537
    /**
538
     * Determine if the Model Admin has Creating Capabilities.
539
     * 
540
     * @return bool
541
     */
542
    public function hasCreating()
543
    {
544
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelCreating::class);
545
    }
546
547
    /**
548
     * Determine if the Model Admin has Cloning Capabilities.
549
     * 
550
     * @return bool
551
     */
552
    public function hasCloning()
553
    {
554
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelCloning::class);
555
    }
556
557
    /**
558
     * Determine if the Model Admin has Editting Capabilities.
559
     * 
560
     * @return bool
561
     */
562
    public function hasEditting()
563
    {
564
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelEditting::class);
565
    }
566
567
    /**
568
     * Determine if the Model Admin has Deleting Capabilities.
569
     * 
570
     * @return bool
571
     */
572
    public function hasDeleting()
573
    {
574
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelDeleting::class);
575
    }
576
577
    /**
578
     * Determine if the Managed Model is using the SoftDeletes Trait.
579
     *
580
     * This is guarded by hasDeleting, since we shouldn't allow SoftDeleting
581
     * without the deleting trait (even though it isn't really required).
582
     *
583
     * @return bool
584
     */
585
    public function hasSoftDeleting()
586
    {
587
        if (!$this->hasDeleting()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hasDeleting() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
588
            return false;
589
        }
590
591
        $managedModelClass = $this->getManagedModel();
592
593
        return in_array(
594
            \Illuminate\Database\Eloquent\SoftDeletes::class, class_uses_recursive(get_class(new $managedModelClass()))
595
        ) && in_array(
596
            \LaravelFlare\Flare\Admin\Models\Traits\ModelSoftDeleting::class, class_uses_recursive(get_class($this))
597
        );
598
    }
599
600
    /**
601
     * Determine if the Model Admin has Validating Capabilities.
602
     * 
603
     * @return bool
604
     */
605
    public function hasValidating()
606
    {
607
        return $this->hasTrait(\LaravelFlare\Flare\Admin\Models\Traits\ModelValidating::class);
608
    }
609
610
    /**
611
     * Determine if the Managed Model has a Trait and Contract.
612
     *
613
     * @return bool
614
     */
615
    public function hasTraitAndContract($trait = null, $contract = null)
616
    {
617
        return ($this->hasTrait($trait) && $this->hasContract($contract));
618
    }
619
620
    /**
621
     * Returns whether the current ModelAdmin has a given trait.
622
     * 
623
     * @param string $trait
624
     * 
625
     * @return bool
626
     */
627
    public function hasTrait($trait = null)
628
    {
629
        if (!$trait) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $trait of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
630
            return;
631
        }
632
633
        return in_array($trait, class_uses_recursive(get_class($this)));
634
    }
635
636
    /**
637
     * Returns whether the current ModelAdmin has a given contract.
638
     * 
639
     * @param string $contract
640
     * 
641
     * @return bool
642
     */
643
    public function hasContract($contract = null)
0 ignored issues
show
Unused Code introduced by
The parameter $contract 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...
644
    {
645
        if (!$trait) {
0 ignored issues
show
Bug introduced by
The variable $trait does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
646
            return;
647
        }
648
649
        $managedModelClass = $this->getManagedModel();
0 ignored issues
show
Unused Code introduced by
$managedModelClass is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
650
    }
651
}
652