Completed
Push — master ( adcdfa...64ceef )
by
unknown
16:40 queued 12:16
created

Model::getFieldValue()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 57
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 36
nc 6
nop 2
dl 0
loc 57
ccs 0
cts 38
cp 0
crap 90
rs 7.0745
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Anavel\Crud\Abstractor\Eloquent;
4
5
use ANavallaSuiza\Laravel\Database\Contracts\Dbal\AbstractionLayer;
6
use Anavel\Crud\Abstractor\ConfigurationReader;
7
use Anavel\Crud\Abstractor\Eloquent\Traits\HandleFiles;
8
use Anavel\Crud\Abstractor\Eloquent\Traits\ModelFields;
9
use Anavel\Crud\Abstractor\Exceptions\AbstractorException;
10
use Anavel\Crud\Contracts\Abstractor\Field as FieldContract;
11
use Anavel\Crud\Contracts\Abstractor\FieldFactory as FieldFactoryContract;
12
use Anavel\Crud\Contracts\Abstractor\Model as ModelAbstractorContract;
13
use Anavel\Crud\Contracts\Abstractor\Relation;
14
use Anavel\Crud\Contracts\Abstractor\RelationFactory as RelationFactoryContract;
15
use Anavel\Crud\Contracts\Form\Generator as FormGenerator;
16
use App;
17
use FormManager\ElementInterface;
18
use Illuminate\Database\Eloquent\Model as LaravelModel;
19
use Illuminate\Http\Request;
20
use Illuminate\Support\Collection;
21
22
class Model implements ModelAbstractorContract
23
{
24
    use ConfigurationReader;
25
    use ModelFields;
26
    use HandleFiles;
27
28
    protected $dbal;
29
    protected $relationFactory;
30
    protected $fieldFactory;
31
    protected $generator;
32
33
    protected $model;
34
    protected $config;
35
36
    protected $slug;
37
    protected $name;
38
    protected $instance;
39
40
    /**
41
     * @var bool
42
     */
43
    protected $mustDeleteFilesInFilesystem;
44
45 17
    public function __construct(
46
        $config,
47
        AbstractionLayer $dbal,
48
        RelationFactoryContract $relationFactory,
49
        FieldFactoryContract $fieldFactory,
50
        FormGenerator $generator,
51
        $mustDeleteFilesInFilesystem = false
52
    ) {
53 17
        if (is_array($config)) {
54 17
            $this->model = $config['model'];
55 17
            $this->config = $config;
56 17
        } else {
57
            $this->model = $config;
58
            $this->config = [];
59
        }
60
61 17
        $this->dbal = $dbal;
62 17
        $this->relationFactory = $relationFactory;
63 17
        $this->fieldFactory = $fieldFactory;
64 17
        $this->generator = $generator;
65 17
        $this->mustDeleteFilesInFilesystem = $mustDeleteFilesInFilesystem;
66 17
    }
67
68 3
    public function setSlug($slug)
69
    {
70 3
        $this->slug = $slug;
71
72 3
        return $this;
73
    }
74
75 2
    public function setName($name)
76
    {
77 2
        $this->name = $name;
78
79 2
        return $this;
80
    }
81
82 5
    public function setInstance($instance)
83
    {
84 5
        $this->instance = $instance;
85
86 5
        return $this;
87
    }
88
89
    public function getSlug()
90
    {
91
        return $this->slug;
92
    }
93
94
    public function getName()
95
    {
96
        return transcrud($this->name);
97
    }
98
99 1
    public function getModel()
100
    {
101 1
        return $this->model;
102
    }
103
104
    public function getInstance()
105
    {
106
        return $this->instance;
107
    }
108
109
    /**
110
     * @return array
111
     */
112
    public function getConfig()
113
    {
114
        return $this->config;
115
    }
116
117
    public function isSoftDeletes()
118
    {
119
        return $this->getConfigValue('soft_deletes') ? true : false;
120
    }
121
122 8
    public function getColumns($action, $withForeignKeys = false)
123
    {
124 8
        $tableColumns = $this->dbal->getTableColumns();
125
126 8
        $filteredColumns = [];
127 8
        foreach ($tableColumns as $name => $column) {
128 8
            $filteredColumns[str_replace('`', '', $name)] = $column;
129 8
        }
130 8
        $tableColumns = $filteredColumns;
131
132
133 8
        $foreignKeysName = [];
134 8
        if ($withForeignKeys === false) {
135 8
            $foreignKeys = $this->dbal->getTableForeignKeys();
136
137 8
            foreach ($foreignKeys as $foreignKey) {
138
                foreach ($foreignKey->getColumns() as $columnName) {
139
                    $foreignKeysName[] = $columnName;
140
                }
141 8
            }
142 8
        }
143
144 8
        $customDisplayedColumns = $this->getConfigValue($action, 'display');
145 8
        $customHiddenColumns = $this->getConfigValue($action, 'hide') ?: [];
146
147 8
        $columns = [];
148 8
        if (!empty($customDisplayedColumns) && is_array($customDisplayedColumns)) {
149 8
            foreach ($customDisplayedColumns as $customColumn) {
150 8
                if (strpos($customColumn, '.')) {
151
                    $customColumnRelation = explode('.', $customColumn);
152
153
                    $customColumnRelationFieldName = array_pop($customColumnRelation);
154
155
                    $modelAbstractor = $this;
156
                    foreach ($customColumnRelation as $relationName) {
157
                        $nestedRelation = $this->getNestedRelation($modelAbstractor, $relationName);
158
                        $modelAbstractor = $nestedRelation->getModelAbstractor();
159
                    }
160
161
                    $relationColumns = $nestedRelation->getModelAbstractor()->getColumns($action);
0 ignored issues
show
Bug introduced by
The variable $nestedRelation does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
162
163
                    if (!array_key_exists($customColumnRelationFieldName, $relationColumns)) {
164
                        throw new AbstractorException('Column '.$customColumnRelationFieldName.' does not exist on relation '.implode('.', $customColumnRelation).' of model '.$this->getModel());
165
                    }
166
167
                    $columns[$customColumn] = $relationColumns[$customColumnRelationFieldName];
168
                } else {
169 8
                    if (!array_key_exists($customColumn, $tableColumns)) {
170
                        throw new AbstractorException('Column '.$customColumn.' does not exist on '.$this->getModel());
171
                    }
172
173 8
                    $columns[$customColumn] = $tableColumns[$customColumn];
174
                }
175 8
            }
176 8
        } else {
177
            foreach ($tableColumns as $name => $column) {
178
                if (in_array($name, $customHiddenColumns)) {
179
                    continue;
180
                }
181
182
                if (in_array($name, $foreignKeysName)) {
183
                    continue;
184
                }
185
186
                $columns[$name] = $column;
187
            }
188
        }
189
190 8
        return $columns;
191
    }
192
193
    protected function getNestedRelation(Model $modelAbstractor, $relationName)
194
    {
195
        $relations = $modelAbstractor->getRelations();
196
197
        if (!$relations->has($relationName)) {
198
            throw new AbstractorException('Relation '.$relationName.' not configured on '.$modelAbstractor->getModel());
199
        }
200
201
        $relation = $relations->get($relationName);
202
203
        if ($relation instanceof Relation) {
204
            return $relation;
205
        } else {
206
            return $relation['relation'];
207
        }
208
    }
209
210
    /**
211
     * @return \Illuminate\Support\Collection
212
     */
213 4
    public function getRelations()
214
    {
215 4
        $configRelations = $this->getConfigValue('relations');
216
217 4
        $relations = collect();
218
219 4
        if (!empty($configRelations)) {
220 4
            foreach ($configRelations as $relationName => $configRelation) {
221 4
                if (is_int($relationName)) {
222
                    $relationName = $configRelation;
223
                }
224
225 4
                $config = [];
226 4
                if ($configRelation !== $relationName) {
227 4
                    if (!is_array($configRelation)) {
228
                        $config['type'] = $configRelation;
229
                    } else {
230 4
                        $config = $configRelation;
231
                    }
232 4
                }
233
234
                /** @var Relation $relation */
235 4
                $relation = $this->relationFactory->setModel($this->instance)
236 4
                    ->setConfig($config)
237 4
                    ->get($relationName);
238
239 4
                $secondaryRelations = $relation->getSecondaryRelations();
240
241
242 4
                if (!$secondaryRelations->isEmpty()) {
243 1
                    $relations->put(
244 1
                        $relationName,
245 1
                        collect(['relation' => $relation, 'secondaryRelations' => $secondaryRelations])
246 1
                    );
247 1
                } else {
248 3
                    $relations->put($relationName, $relation);
249
                }
250 4
            }
251 4
        }
252
253 4
        return $relations;
254
    }
255
256
    /**
257
     * @param string|null $arrayKey
258
     *
259
     * @throws AbstractorException
260
     *
261
     * @return array
262
     */
263 2 View Code Duplication
    public function getListFields($arrayKey = 'main')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
    {
265 2
        $columns = $this->getColumns('list');
266
267 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ?: [];
268
269 2
        $fields = [];
270 2
        foreach ($columns as $name => $column) {
271 2
            $presentation = null;
272 2
            if (array_key_exists($name, $fieldsPresentation)) {
273 2
                $presentation = $fieldsPresentation[$name];
274 2
            }
275
276
            $config = [
277 2
                'name'         => $name,
278 2
                'presentation' => $presentation,
279 2
                'form_type'    => null,
280 2
                'validation'   => null,
281 2
                'functions'    => null,
282 2
            ];
283
284 2
            $fields[$arrayKey][] = $this->fieldFactory
285 2
                ->setColumn($column)
286 2
                ->setConfig($config)
287 2
                ->get();
288 2
        }
289
290 2
        return $fields;
291
    }
292
293
    /**
294
     * @param string|null $arrayKey
295
     *
296
     * @throws AbstractorException
297
     *
298
     * @return array
299
     */
300 2 View Code Duplication
    public function getDetailFields($arrayKey = 'main')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
301
    {
302 2
        $columns = $this->getColumns('detail');
303
304 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ?: [];
305
306 2
        $fields = [];
307 2
        foreach ($columns as $name => $column) {
308 2
            $presentation = null;
309 2
            if (array_key_exists($name, $fieldsPresentation)) {
310 2
                $presentation = $fieldsPresentation[$name];
311 2
            }
312
313
            $config = [
314 2
                'name'         => $name,
315 2
                'presentation' => $presentation,
316 2
                'form_type'    => null,
317 2
                'validation'   => null,
318 2
                'functions'    => null,
319 2
            ];
320
321 2
            $fields[$arrayKey][] = $this->fieldFactory
322 2
                ->setColumn($column)
323 2
                ->setConfig($config)
324 2
                ->get();
325 2
        }
326
327 2
        return $fields;
328
    }
329
330
    /**
331
     * @param bool|null   $withForeignKeys
332
     * @param string|null $arrayKey
333
     *
334
     * @throws AbstractorException
335
     *
336
     * @return array
337
     */
338 4
    public function getEditFields($withForeignKeys = false, $arrayKey = 'main')
339
    {
340 4
        $columns = $this->getColumns('edit', $withForeignKeys);
0 ignored issues
show
Bug introduced by
It seems like $withForeignKeys defined by parameter $withForeignKeys on line 338 can also be of type null; however, Anavel\Crud\Abstractor\E...ent\Model::getColumns() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
341
342 4
        $this->readConfig('edit');
343
344 4
        $fields = [];
345 4
        foreach ($columns as $name => $column) {
346 4
            if (!in_array($name, $this->getReadOnlyColumns())) {
347 4
                $presentation = null;
348 4
                if (array_key_exists($name, $this->fieldsPresentation)) {
349
                    $presentation = $this->fieldsPresentation[$name];
350
                }
351
352
                $config = [
353 4
                    'name'         => $name,
354 4
                    'presentation' => $presentation,
355 4
                    'form_type'    => null,
356 4
                    'validation'   => null,
357 4
                    'functions'    => null,
358 4
                ];
359
360 4
                $config = $this->setConfig($config, $name);
361
362 4
                $field = $this->fieldFactory
363 4
                    ->setColumn($column)
364 4
                    ->setConfig($config)
365 4
                    ->get();
366
367 4
                if (!empty($this->instance) && !empty($this->instance->getAttribute($name))) {
368
                    $field->setValue($this->instance->getAttribute($name));
369
                }
370
371 4
                $fields[$arrayKey][$name] = $field;
372
373 4 View Code Duplication
                if (!empty($config['form_type']) && $config['form_type'] === 'file') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
374 4
                    $field = $this->fieldFactory
375 4
                        ->setColumn($column)
376 4
                        ->setConfig([
377 4
                            'name'         => $name.'__delete',
378 4
                            'presentation' => null,
379 4
                            'form_type'    => 'checkbox',
380 4
                            'no_validate'  => true,
381 4
                            'functions'    => null,
382 4
                        ])
383 4
                        ->get();
384 4
                    $fields[$arrayKey][$name.'__delete'] = $field;
385 4
                }
386 4
            }
387 4
        }
388
389 4
        return $fields;
390
    }
391
392 4
    protected function getReadOnlyColumns()
393
    {
394 4
        $columns = [LaravelModel::CREATED_AT, LaravelModel::UPDATED_AT];
395
396 4
        $columns[] = $this->dbal->getModel()->getKeyName();
397
398 4
        return $columns;
399
    }
400
401
    /**
402
     * @param string $action
403
     *
404
     * @return ElementInterface
405
     */
406 2
    public function getForm($action)
407
    {
408 2
        $this->generator->setModelFields($this->getEditFields());
409 2
        $this->generator->setRelatedModelFields($this->getRelations());
410
411 2
        return $this->generator->getForm($action);
412
    }
413
414
    /**
415
     * @param array $requestForm
0 ignored issues
show
Documentation introduced by
There is no parameter named $requestForm. Did you maybe mean $request?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
416
     *
417
     * @return mixed
418
     */
419 1
    public function persist(Request $request)
420
    {
421
        /** @var \ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager $modelManager */
422 1
        $modelManager = App::make('ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager');
423 1
        if (!empty($this->instance)) {
424
            $item = $this->instance;
425
        } else {
426 1
            $item = $modelManager->getModelInstance($this->getModel());
427
        }
428
429
430 1
        $fields = $this->getEditFields(true);
431 1
        if (empty($fields['main']) && $this->getRelations()->isEmpty()) {
432
            return;
433
        }
434
435 1
        if (!empty($fields['main'])) {
436 1
            $skip = null;
437 1
            foreach ($fields['main'] as $key => $field) {
438
                /* @var FieldContract $field */
439 1
                if ($skip === $key) {
440
                    $skip = null;
441
                    continue;
442
                }
443 1
                $fieldName = $field->getName();
444 1
                $requestValue = $request->input("main.{$fieldName}");
445
446 1
                if (get_class($field->getFormField()) === \FormManager\Fields\Checkbox::class) {
447
                    if (empty($requestValue)) {
448
                        // Unchecked checkboxes are not sent, so we force setting them to false
449
                        $item->setAttribute(
450
                            $fieldName,
451
                            $field->applyFunctions(null)
452
                        );
453
                    } else {
454
                        $requestValue = true;
455
                    }
456
                }
457
458 1
                if (get_class($field->getFormField()) === \FormManager\Fields\File::class) {
459
                    $handleResult = $this->handleField($request, $item, $fields['main'], 'main', $fieldName, $this->mustDeleteFilesInFilesystem);
460
                    if (!empty($handleResult['skip'])) {
461
                        $skip = $handleResult['skip'];
462
                    }
463
                    if (!empty($handleResult['requestValue'])) {
464
                        $requestValue = $handleResult['requestValue'];
465
                    }
466
                }
467
468
469 1
                if (!$field->saveIfEmpty() && empty($requestValue)) {
470
                    continue;
471
                }
472
473 1
                if (!empty($requestValue) || (empty($requestValue) && !empty($item->getAttribute($fieldName)))) {
474 1
                    $item->setAttribute(
475 1
                        $fieldName,
476 1
                        $field->applyFunctions($requestValue)
477 1
                    );
478 1
                }
479 1
            }
480 1
        }
481
482 1
        $item->save();
483
484 1
        $this->setInstance($item);
485
486
487 1
        if (!empty($relations = $this->getRelations())) {
488 1
            foreach ($relations as $relationKey => $relation) {
489 1
                if ($relation instanceof Collection) {
490
                    $input = $request->input($relationKey);
491
                    /** @var $relationInstance Relation */
492
                    $relationInstance = $relation->get('relation');
493
                    $relationInstance->persist($input, $request);
0 ignored issues
show
Bug introduced by
It seems like $input defined by $request->input($relationKey) on line 490 can also be of type string; however, Anavel\Crud\Contracts\Ab...tor\Relation::persist() does only seem to accept null|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
494
                } else {
495
                    /* @var $relation Relation */
496 1
                    $relation->persist($request->input($relationKey), $request);
0 ignored issues
show
Bug introduced by
It seems like $request->input($relationKey) targeting Illuminate\Http\Request::input() can also be of type string; however, Anavel\Crud\Contracts\Ab...tor\Relation::persist() does only seem to accept null|array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
497
                }
498 1
            }
499 1
        }
500
501 1
        return $item;
502
    }
503
504
    /**
505
     * @return array
506
     */
507 1
    public function getValidationRules()
508
    {
509 1
        return $this->generator->getValidationRules();
510
    }
511
512
    public function getFieldValue($item, $fieldName)
513
    {
514
        $value = null;
0 ignored issues
show
Unused Code introduced by
$value 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...
515
516
        if (strpos($fieldName, '.')) {
517
            $customColumnRelation = explode('.', $fieldName);
518
519
            $customColumnRelationFieldName = array_pop($customColumnRelation);
520
521
            $entity = $item;
522
            $relation = null;
523
            $relationName = '';
524
            foreach ($customColumnRelation as $relationName) {
525
                $relation = $entity->{$relationName};
526
                if ($relation instanceof Collection) {
527
                    $entity = $relation->first();
528
                } else {
529
                    $entity = $relation;
530
                }
531
            }
532
533
            if (is_null($entity)) {
534
                return;
535
            }
536
            $lastRelationName = $relationName;
537
538
            array_pop($customColumnRelation);
539
540
            $prevModelAbtractor = $this;
541
            foreach ($customColumnRelation as $relationName) {
542
                $nestedRelation = $this->getNestedRelation($prevModelAbtractor, $relationName);
543
                $prevModelAbtractor = $nestedRelation->getModelAbstractor();
544
            }
545
546
            if (empty($relation)) {
547
                return;
548
            }
549
550
            if ($relation instanceof Collection) {
551
                $relations = $prevModelAbtractor->getRelations();
552
553
                $relationAbstractor = $relations->get($lastRelationName);
554
555
                if ($relationAbstractor instanceof \Anavel\Crud\Abstractor\Eloquent\Relation\Translation) {
556
                    $value = $entity->getAttribute($customColumnRelationFieldName);
557
                } else {
558
                    $value = $relation->implode($customColumnRelationFieldName, ', ');
559
                }
560
            } else {
561
                $value = $relation->getAttribute($customColumnRelationFieldName);
562
            }
563
        } else {
564
            $value = $item->getAttribute($fieldName);
565
        }
566
567
        return $value;
568
    }
569
570
    /**
571
     * @return bool
572
     */
573
    public function mustDeleteFilesInFilesystem()
574
    {
575
        return $this->mustDeleteFilesInFilesystem;
576
    }
577
}
578