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
Branch development (1ea943)
by butschster
05:38
created

FormDefault::setView()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 9.4285
1
<?php
2
3
namespace SleepingOwl\Admin\Form;
4
5
use Request;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Model;
8
use KodiComponents\Support\HtmlAttributes;
9
use SleepingOwl\Admin\Form\Element\Upload;
10
use Illuminate\Validation\ValidationException;
11
use SleepingOwl\Admin\Contracts\FormInterface;
12
use SleepingOwl\Admin\Contracts\DisplayInterface;
13
use SleepingOwl\Admin\Contracts\RepositoryInterface;
14
use SleepingOwl\Admin\Exceptions\Form\FormException;
15
use Illuminate\Database\Eloquent\Relations\BelongsTo;
16
use SleepingOwl\Admin\Contracts\FormButtonsInterface;
17
use SleepingOwl\Admin\Contracts\FormElementInterface;
18
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
19
use SleepingOwl\Admin\Contracts\ModelConfigurationInterface;
20
21
class FormDefault extends FormElements implements DisplayInterface, FormInterface
22
{
23
    use HtmlAttributes;
24
25
    /**
26
     * View to render.
27
     * @var string|\Illuminate\View\View
28
     */
29
    protected $view = 'form.default';
30
31
    /**
32
     * Form related class.
33
     * @var string
34
     */
35
    protected $class;
36
37
    /**
38
     * @var FormButtons
39
     */
40
    protected $buttons;
41
42
    /**
43
     * Form related repository.
44
     * @var RepositoryInterface
45
     */
46
    protected $repository;
47
48
    /**
49
     * Form action url.
50
     * @var string
51
     */
52
    protected $action;
53
54
    /**
55
     * Form related model instance.
56
     * @var Model
57
     */
58
    protected $model;
59
60
    /**
61
     * Currently loaded model id.
62
     * @var int
63
     */
64
    protected $id;
65
66
    /**
67
     * Is form already initialized?
68
     * @var bool
69
     */
70
    protected $initialized = false;
71
72
    /**
73
     * FormDefault constructor.
74
     *
75
     * @param array $elements
76
     */
77
    public function __construct(array $elements = [])
78
    {
79
        parent::__construct($elements);
80
81
        $this->setButtons(
82
            app(FormButtonsInterface::class)
83
        );
84
    }
85
86
    /**
87
     * Initialize form.
88
     */
89
    public function initialize()
90
    {
91
        if ($this->initialized) {
92
            return;
93
        }
94
95
        $this->initialized = true;
96
        $this->repository = app(RepositoryInterface::class, [$this->class]);
97
        $this->setModel(
98
            $this->makeModel()
99
        );
100
101
        parent::initialize();
102
103
        if (! $this->hasHtmlAttribute('enctype')) {
0 ignored issues
show
Documentation introduced by
'enctype' is of type string, but the function expects a object<KodiComponents\Support\srtring>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
            // Try to find upload element
105
            $this->getElements()->each(function ($element) {
106
107
                // TODO: this not works withs nested elements
108
                if ($element instanceof Upload and ! $this->hasHtmlAttribute('enctype')) {
0 ignored issues
show
Documentation introduced by
'enctype' is of type string, but the function expects a object<KodiComponents\Support\srtring>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
109
                    $this->setHtmlAttribute('enctype', 'multipart/form-data');
110
                }
111
            });
112
        }
113
114
        $this->getButtons()->setModelConfiguration(
115
            $this->getModelConfiguration()
116
        );
117
    }
118
119
    /**
120
     * @return FormButtons
121
     */
122
    public function getButtons()
123
    {
124
        return $this->buttons;
125
    }
126
127
    /**
128
     * @param FormButtonsInterface $buttons
129
     *
130
     * @return $this
131
     */
132
    public function setButtons(FormButtonsInterface $buttons)
133
    {
134
        $this->buttons = $buttons;
0 ignored issues
show
Documentation Bug introduced by
$buttons is of type object<SleepingOwl\Admin...s\FormButtonsInterface>, but the property $buttons was declared to be of type object<SleepingOwl\Admin\Form\FormButtons>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
135
136
        return $this;
137
    }
138
139
    /**
140
     * @return RepositoryInterface
141
     */
142
    public function getRepository()
143
    {
144
        return $this->repository;
145
    }
146
147
    /**
148
     * @return string
149
     */
150
    public function getAction()
151
    {
152
        return $this->action;
153
    }
154
155
    /**
156
     * @param string $action
157
     *
158
     * @return $this
159
     */
160
    public function setAction($action)
161
    {
162
        $this->action = $action;
163
164
        return $this;
165
    }
166
167
    /**
168
     * @return string
169
     */
170
    public function getClass()
171
    {
172
        return $this->class;
173
    }
174
175
    /**
176
     * @param string $class
177
     *
178
     * @return $this
179
     * @throws FormException
180
     */
181
    public function setModelClass($class)
182
    {
183
        if (is_null($this->class)) {
184
            $this->class = $class;
185
        }
186
187
        return $this;
188
    }
189
190
    /**
191
     * @deprecated 4.5.0
192
     * @see getElements()
193
     *
194
     * @return Collection[]
195
     */
196
    public function getItems()
197
    {
198
        return $this->getElements();
199
    }
200
201
    /**
202
     * @deprecated 4.5.0
203
     * @see setElements()
204
     *
205
     * @param array|FormElementInterface $items
206
     *
207
     * @return $this
208
     */
209
    public function setItems($items)
210
    {
211
        if (! is_array($items)) {
212
            $items = func_get_args();
213
        }
214
215
        return $this->setElements($items);
216
    }
217
218
    /**
219
     * @deprecated 4.5.0
220
     * @see addElement()
221
     *
222
     * @param FormElementInterface $item
223
     *
224
     * @return $this
225
     */
226
    public function addItem($item)
227
    {
228
        return $this->addElement($item);
229
    }
230
231
    /**
232
     * Set currently loaded model id.
233
     *
234
     * @param int $id
235
     */
236
    public function setId($id)
237
    {
238
        if (is_null($this->id) and ! is_null($id) and ($model = $this->getRepository()->find($id))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
239
            $this->id = $id;
240
241
            $this->setModel($model);
242
        }
243
    }
244
245
    /**
246
     * Get related form model configuration.
247
     * @return ModelConfigurationInterface
248
     */
249
    public function getModelConfiguration()
250
    {
251
        return app('sleeping_owl')->getModel($this->class);
252
    }
253
254
    /**
255
     * @return Model
256
     */
257
    public function getModel()
258
    {
259
        return $this->model;
260
    }
261
262
    /**
263
     * @param Model $model
264
     *
265
     * @return $this
266
     */
267
    public function setModel(Model $model)
268
    {
269
        parent::setModel($model);
270
        $this->getButtons()->setModel($model);
271
272
        return $this;
273
    }
274
275
    /**
276
     * Save instance.
277
     *
278
     * @param ModelConfigurationInterface $modelConfiguration
279
     *
280
     * @return bool
281
     */
282
    public function saveForm(ModelConfigurationInterface $modelConfiguration)
283
    {
284
        if ($modelConfiguration !== $this->getModelConfiguration()) {
285
            return;
286
        }
287
288
        parent::save();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (save() instead of saveForm()). Are you sure this is correct? If so, you might want to change this to $this->save().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
289
290
        $model = $this->getModel();
291
292
        $this->saveBelongsToRelations($model);
293
294
        $loaded = $model->exists;
295
296
        if ($modelConfiguration->fireEvent($loaded ? 'updating' : 'creating', true, $model) === false) {
297
            return false;
298
        }
299
300
        if ($modelConfiguration->fireEvent('saving', true, $model) === false) {
301
            return false;
302
        }
303
304
        $model->save();
305
306
        $this->saveHasOneRelations($model);
307
308
        parent::afterSave();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (afterSave() instead of saveForm()). Are you sure this is correct? If so, you might want to change this to $this->afterSave().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
309
310
        $modelConfiguration->fireEvent($loaded ? 'updated' : 'created', false, $model);
311
        $modelConfiguration->fireEvent('saved', false, $model);
312
313
        return true;
314
    }
315
316
    /**
317
     * @param Model $model
318
     *
319
     * @return void
320
     */
321
    protected function saveBelongsToRelations(Model $model)
322
    {
323
        foreach ($model->getRelations() as $name => $relation) {
324
            if ($model->{$name}() instanceof BelongsTo && ! is_null($relation)) {
325
                $relation->save();
326
                $model->{$name}()->associate($relation);
327
            }
328
        }
329
    }
330
331
    /**
332
     * @param Model $model
333
     *
334
     * @return void
335
     */
336
    protected function saveHasOneRelations(Model $model)
337
    {
338
        foreach ($model->getRelations() as $name => $relation) {
339
            if ($model->{$name}() instanceof HasOneOrMany && ! is_null($relation)) {
340
                if (is_array($relation) || $relation instanceof \Traversable) {
341
                    $model->{$name}()->saveMany($relation);
342
                } else {
343
                    $model->{$name}()->save($relation);
344
                }
345
            }
346
        }
347
    }
348
349
    /**
350
     * @param ModelConfigurationInterface $modelConfiguration
351
     *
352
     * @throws ValidationException
353
     * @return void
354
     */
355
    public function validateForm(ModelConfigurationInterface $modelConfiguration)
356
    {
357
        if ($modelConfiguration !== $this->getModelConfiguration()) {
358
            return;
359
        }
360
361
        $verifier = app('validation.presence');
362
        $verifier->setConnection($this->getModel()->getConnectionName());
363
364
        $validator = \Validator::make(
365
            Request::all(),
366
            $this->getValidationRules(),
367
            $this->getValidationMessages(),
368
            $this->getValidationLabels()
369
        );
370
371
        $validator->setPresenceVerifier($verifier);
372
373
        $modelConfiguration->fireEvent('validate', false, $this->getModel(), $validator);
374
375
        if ($validator->fails()) {
376
            throw new ValidationException($validator);
377
        }
378
    }
379
380
    /**
381
     * Get the instance as an array.
382
     *
383
     * @return array
384
     */
385
    public function toArray()
386
    {
387
        // This element needs only in template
388
        $this->setHtmlAttribute('method', 'POST');
389
        $this->setHtmlAttribute('action', $this->getAction());
390
391
        return [
392
            'items' => $this->getElements()->onlyVisible(),
393
            'instance' => $this->getModel(),
394
            'attributes' => $this->htmlAttributesToString(),
395
            'buttons' => $this->getButtons(),
396
            'backUrl' => session('_redirectBack', \URL::previous()),
397
        ];
398
    }
399
400
    /**
401
     * @return Model
402
     */
403
    protected function makeModel()
404
    {
405
        $class = $this->getClass();
406
407
        return new $class();
408
    }
409
}
410