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 master (9e3162)
by Dave
63:34
created

FormDefault::validateForm()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.1825

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 3
nop 2
dl 0
loc 23
ccs 8
cts 11
cp 0.7272
crap 3.1825
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace SleepingOwl\Admin\Form;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Database\Eloquent\Model;
7
use KodiComponents\Support\HtmlAttributes;
8
use SleepingOwl\Admin\Form\Element\Upload;
9
use Illuminate\Validation\ValidationException;
10
use SleepingOwl\Admin\Contracts\Form\FormInterface;
11
use SleepingOwl\Admin\Exceptions\Form\FormException;
12
use Illuminate\Database\Eloquent\Relations\BelongsTo;
13
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
14
use SleepingOwl\Admin\Contracts\Display\DisplayInterface;
15
use SleepingOwl\Admin\Contracts\Form\FormButtonsInterface;
16
use SleepingOwl\Admin\Contracts\ModelConfigurationInterface;
17
use SleepingOwl\Admin\Contracts\Repositories\RepositoryInterface;
18
19
class FormDefault extends FormElements implements DisplayInterface, FormInterface
20
{
21
    use HtmlAttributes;
22
23
    /**
24
     * View to render.
25
     * @var string|\Illuminate\View\View
26
     */
27
    protected $view = 'form.default';
28
29
    /**
30
     * Form related class.
31
     * @var string
32
     */
33
    protected $class;
34
35
    /**
36
     * @var FormButtons
37
     */
38
    protected $buttons;
39
40
    /**
41
     * Form related repository.
42
     * @var RepositoryInterface
43
     */
44
    protected $repository;
45
46
    /**
47
     * Form action url.
48
     * @var string
49
     */
50
    protected $action;
51
52
    /**
53
     * Form related model instance.
54
     * @var Model
55
     */
56
    protected $model;
57
58
    /**
59
     * Currently loaded model id.
60
     * @var int
61
     */
62
    protected $id;
63
64
    /**
65
     * Is form already initialized?
66
     * @var bool
67
     */
68
    protected $initialized = false;
69
70
    /**
71
     * FormDefault constructor.
72
     *
73
     * @param array $elements
74
     */
75 12
    public function __construct(array $elements = [])
76
    {
77 12
        parent::__construct($elements);
78
79 12
        $this->setButtons(
80 12
            app(FormButtonsInterface::class)
81 12
        );
82 12
    }
83
84
    /**
85
     * Initialize form.
86
     */
87 4
    public function initialize()
88
    {
89 4
        if ($this->initialized) {
90
            return;
91
        }
92
93 4
        $this->initialized = true;
94 4
        $this->repository = app(RepositoryInterface::class);
95 4
        $this->repository->setClass($this->class);
96
97 4
        $model = $this->makeModel();
98 4
        parent::setModel($model);
99 4
        $this->getButtons()->setModel($model);
100
101 4
        parent::initialize();
102
103 4
        if (! $this->hasHtmlAttribute('enctype')) {
104
105 4
            // Recursive iterate subset of form elements
106
            // and if subset contains an upload element then add to for
107 4
            $this->recursiveIterateElements(function ($element) {
108 1
                if ($element instanceof Upload) {
109 1
                    $this->withFiles();
110 4
111 4
                    return true;
112
                }
113 4
            });
114 4
        }
115 4
116 4
        $this->getButtons()->setModelConfiguration(
117
            $this->getModelConfiguration()
118
        );
119
    }
120
121 6
    /**
122
     * Set enctype multipart/form-data.
123 6
     *
124
     * @return $this
125
     */
126
    public function withFiles()
127
    {
128
        $this->setHtmlAttribute('enctype', 'multipart/form-data');
129
130
        return $this;
131 12
    }
132
133 12
    /**
134
     * @return FormButtons
135 12
     */
136
    public function getButtons()
137
    {
138
        return $this->buttons;
139
    }
140
141 2
    /**
142
     * @param FormButtonsInterface $buttons
143 2
     *
144
     * @return $this
145
     */
146
    public function setButtons(FormButtonsInterface $buttons)
147
    {
148
        $this->buttons = $buttons;
0 ignored issues
show
Documentation Bug introduced by
$buttons is of type SleepingOwl\Admin\Contra...rm\FormButtonsInterface, but the property $buttons was declared to be of type 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...
149 1
150
        return $this;
151 1
    }
152
153
    /**
154
     * @return RepositoryInterface
155
     */
156
    public function getRepository()
157
    {
158
        return $this->repository;
159 2
    }
160
161 2
    /**
162 2
     * @return string
163 2
     */
164
    public function getAction()
165 2
    {
166
        return $this->action;
167
    }
168
169
    /**
170
     * @param string $action
171 6
     *
172
     * @return $this
173 6
     */
174
    public function setAction($action)
175
    {
176
        if (is_null($this->action)) {
0 ignored issues
show
introduced by
The condition is_null($this->action) is always false.
Loading history...
177
            $this->action = $action;
178
        }
179
180
        return $this;
181
    }
182 7
183
    /**
184 7
     * @return string
185 7
     */
186 7
    public function getClass()
187
    {
188 7
        return $this->class;
189
    }
190
191
    /**
192
     * @param string $class
193
     *
194
     * @return $this
195
     * @throws FormException
196
     */
197
    public function setModelClass($class)
198
    {
199
        if (is_null($this->class)) {
0 ignored issues
show
introduced by
The condition is_null($this->class) is always false.
Loading history...
200
            $this->class = $class;
201
        }
202
203
        return $this;
204
    }
205
206
    /**
207
     * @deprecated 4.5.0
208
     * @see getElements()
209
     *
210
     * @return Collection[]
211
     */
212
    public function getItems()
213
    {
214
        return $this->getElements();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getElements() returns the type SleepingOwl\Admin\Form\FormElementsCollection which is incompatible with the documented return type Illuminate\Support\Collection[].
Loading history...
215
    }
216
217
    /**
218
     * @deprecated 4.5.0
219
     * @see setElements()
220
     *
221
     * @param array|FormElementInterface $items
0 ignored issues
show
Bug introduced by
The type SleepingOwl\Admin\Form\FormElementInterface 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...
222
     *
223
     * @return $this
224
     */
225
    public function setItems($items)
226
    {
227
        if (! is_array($items)) {
228
            $items = func_get_args();
229
        }
230
231
        return $this->setElements($items);
232
    }
233
234
    /**
235
     * @deprecated 4.5.0
236
     * @see addElement()
237 1
     *
238
     * @param FormElementInterface $item
239 1
     *
240 1
     * @return $this
241
     */
242 1
    public function addItem($item)
243 1
    {
244 1
        return $this->addElement($item);
245 1
    }
246 1
247
    /**
248
     * Set currently loaded model id.
249
     *
250
     * @param int $id
251
     */
252 5
    public function setId($id)
253
    {
254 5
        if (is_null($this->id) && ! is_null($id) && ($model = $this->getRepository()->find($id))) {
0 ignored issues
show
introduced by
The condition is_null($this->id) is always false.
Loading history...
255
            $this->id = $id;
256 5
257
            parent::setModel($model);
258
            $this->getButtons()->setModel($model);
259
            $this->setModelClass(get_class($model));
260 5
        }
261
    }
262
263
    /**
264
     * Get related form model configuration.
265
     * @return ModelConfigurationInterface
266 3
     */
267
    public function getModelConfiguration()
268 3
    {
269
        $class = $this->class;
270
271
        if (is_null($class) && $this->getModel() instanceof Model) {
0 ignored issues
show
introduced by
The condition is_null($class) is always false.
Loading history...
272
            $class = $this->getModel();
273
        }
274
275
        return app('sleeping_owl')->getModel($class);
0 ignored issues
show
Bug introduced by
The method getModel() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

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

275
        return app('sleeping_owl')->/** @scrutinizer ignore-call */ getModel($class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
276
    }
277
278
    /**
279
     * @return Model
280
     */
281
    public function getModel()
282
    {
283
        return $this->model;
284
    }
285 3
286
    /**
287 3
     * @param Model $model
288
     *
289
     * @return $this
290
     */
291
    public function setModel(Model $model)
292
    {
293
    }
294
295
    /**
296
     * @param ModelConfigurationInterface $modelConfiguration
297
     *
298 1
     * @return bool
299
     */
300 1
    public function validModelConfiguration(ModelConfigurationInterface $modelConfiguration = null)
301
    {
302
        return is_null($modelConfiguration) || $modelConfiguration === $this->getModelConfiguration();
303
    }
304 1
305
    /**
306 1
     * Save instance.
307
     *
308 1
     * @param \Illuminate\Http\Request $request
309
     * @param ModelConfigurationInterface $modelConfiguration
310 1
     *
311
     * @return bool
312 1
     */
313
    public function saveForm(\Illuminate\Http\Request $request, ModelConfigurationInterface $modelConfiguration = null)
314
    {
315
        if (! $this->validModelConfiguration($modelConfiguration)) {
316 1
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the return type mandated by SleepingOwl\Admin\Contra...rmInterface::saveForm() of void.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
317
        }
318
319
        $model = $this->getModel();
320 1
        $loaded = $model->exists;
321
322 1
        if ($this->getModelConfiguration()->fireEvent($loaded ? 'updating' : 'creating', true, $model) === false) {
0 ignored issues
show
Bug introduced by
The method fireEvent() does not exist on SleepingOwl\Admin\Contra...lConfigurationInterface. Did you maybe mean fireEdit()? ( Ignorable by Annotation )

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

322
        if ($this->getModelConfiguration()->/** @scrutinizer ignore-call */ fireEvent($loaded ? 'updating' : 'creating', true, $model) === false) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
323
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the return type mandated by SleepingOwl\Admin\Contra...rmInterface::saveForm() of void.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
324 1
        }
325
326 1
        if ($this->getModelConfiguration()->fireEvent('saving', true, $model) === false) {
327 1
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the return type mandated by SleepingOwl\Admin\Contra...rmInterface::saveForm() of void.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
328
        }
329 1
330
        parent::save($request);
331
        $this->saveBelongsToRelations($model);
332
333
        $model->save();
334
335
        $this->saveHasOneRelations($model);
336
337 1
        parent::afterSave($request);
338
339 1
        $this->getModelConfiguration()->fireEvent($loaded ? 'updated' : 'created', false, $model);
340
        $this->getModelConfiguration()->fireEvent('saved', false, $model);
341
342
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the return type mandated by SleepingOwl\Admin\Contra...rmInterface::saveForm() of void.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
343
    }
344 1
345 1
    /**
346
     * @param Model $model
347
     *
348
     * @return void
349
     */
350
    protected function saveBelongsToRelations(Model $model)
351
    {
352 1
        foreach ($model->getRelations() as $name => $relation) {
353
            if ($model->{$name}() instanceof BelongsTo && ! is_null($relation)) {
354 1
                $relation->save();
355
                $model->{$name}()->associate($relation);
356
            }
357
        }
358
    }
359
360
    /**
361
     * @param Model $model
362 1
     *
363 1
     * @return void
364
     */
365
    protected function saveHasOneRelations(Model $model)
366
    {
367
        foreach ($model->getRelations() as $name => $relation) {
368
            if ($model->{$name}() instanceof HasOneOrMany && ! is_null($relation)) {
369
                if (is_array($relation) || $relation instanceof \Traversable) {
370
                    $model->{$name}()->saveMany($relation);
371 2
                } else {
372
                    $model->{$name}()->save($relation);
373 2
                }
374
            }
375
        }
376
    }
377 2
378
    /**
379 2
     * @param \Illuminate\Http\Request $request
380
     * @param ModelConfigurationInterface $modelConfiguration
381 2
     *
382 2
     * @throws ValidationException
383 2
     */
384 2
    public function validateForm(\Illuminate\Http\Request $request, ModelConfigurationInterface $modelConfiguration = null)
385 2
    {
386 2
        if (! $this->validModelConfiguration($modelConfiguration)) {
387
            return;
388 2
        }
389
390 2
        $verifier = app('validation.presence');
391
392 2
        $verifier->setConnection($this->getModel()->getConnectionName());
393 1
394
        $validator = \Validator::make(
395 1
            $request->all(),
396
            $this->getValidationRules(),
397
            $this->getValidationMessages(),
398
            $this->getValidationLabels()
399
        );
400
401
        $validator->setPresenceVerifier($verifier);
402
403
        $this->getModelConfiguration()->fireEvent('validate', false, $this->getModel(), $validator);
404
405
        if ($validator->fails()) {
406
            throw new ValidationException($validator);
407
        }
408
    }
409
410
    /**
411
     * Get the instance as an array.
412
     *
413
     * @return array
414
     */
415
    public function toArray()
416
    {
417
        // This element needs only in template
418
        $this->setHtmlAttribute('method', 'POST');
419
        $this->setHtmlAttribute('action', $this->getAction());
420 4
421
        return [
422 4
            'items' => $this->getElements()->onlyVisible(),
423
            'instance' => $this->getModel(),
424 4
            'attributes' => $this->htmlAttributesToString(),
425
            'buttons' => $this->getButtons(),
426
            'backUrl' => session('_redirectBack', \URL::previous()),
427
        ];
428
    }
429
430
    /**
431
     * @return Model
432
     */
433
    protected function makeModel()
434
    {
435
        $class = $this->getClass();
436
437
        return new $class();
438
    }
439
}
440