Completed
Pull Request — master (#74)
by
unknown
13:28 queued 09:37
created

Model::getDetailFields()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 29
Code Lines 19

Duplication

Lines 29
Ratio 100 %

Code Coverage

Tests 20
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 6
nop 1
dl 29
loc 29
ccs 20
cts 20
cp 1
crap 4
rs 8.5806
c 0
b 0
f 0
1
<?php
2
namespace Anavel\Crud\Abstractor\Eloquent;
3
4
use Anavel\Crud\Abstractor\Eloquent\Traits\HandleFiles;
5
use Anavel\Crud\Abstractor\Eloquent\Traits\ModelFields;
6
use Anavel\Crud\Contracts\Abstractor\Field as FieldContract;
7
use Anavel\Crud\Contracts\Abstractor\Model as ModelAbstractorContract;
8
use Anavel\Crud\Abstractor\ConfigurationReader;
9
use Anavel\Crud\Contracts\Abstractor\Relation;
10
use Anavel\Crud\Contracts\Abstractor\RelationFactory as RelationFactoryContract;
11
use Anavel\Crud\Contracts\Abstractor\FieldFactory as FieldFactoryContract;
12
use ANavallaSuiza\Laravel\Database\Contracts\Dbal\AbstractionLayer;
13
use FormManager\ElementInterface;
14
use Illuminate\Database\Eloquent\Model as LaravelModel;
15
use App;
16
use Anavel\Crud\Contracts\Form\Generator as FormGenerator;
17
use Anavel\Crud\Abstractor\Exceptions\AbstractorException;
18
use Illuminate\Http\Request;
19
use Illuminate\Support\Collection;
20
use League\Flysystem\Adapter\Local;
21
use League\Flysystem\Filesystem;
22
23
class Model implements ModelAbstractorContract
24
{
25
    use ConfigurationReader;
26
    use ModelFields;
27
    use HandleFiles;
28
29
    protected $dbal;
30
    protected $relationFactory;
31
    protected $fieldFactory;
32
    protected $generator;
33
34
    protected $model;
35
    protected $config;
36
37
    protected $slug;
38
    protected $name;
39
    protected $instance;
40
41
    /**
42
     * @var bool
43
     */
44
    protected $mustDeleteFilesInFilesystem;
45
46 17
    public function __construct(
47
        $config,
48
        AbstractionLayer $dbal,
49
        RelationFactoryContract $relationFactory,
50
        FieldFactoryContract $fieldFactory,
51
        FormGenerator $generator,
52
        $mustDeleteFilesInFilesystem = false
53
    ) {
54 17
        if (is_array($config)) {
55 17
            $this->model = $config['model'];
56 17
            $this->config = $config;
57 17
        } else {
58
            $this->model = $config;
59
            $this->config = [];
60
        }
61
62 17
        $this->dbal = $dbal;
63 17
        $this->relationFactory = $relationFactory;
64 17
        $this->fieldFactory = $fieldFactory;
65 17
        $this->generator = $generator;
66 17
        $this->mustDeleteFilesInFilesystem = $mustDeleteFilesInFilesystem;
67 17
    }
68
69 3
    public function setSlug($slug)
70
    {
71 3
        $this->slug = $slug;
72
73 3
        return $this;
74
    }
75
76 2
    public function setName($name)
77
    {
78 2
        $this->name = $name;
79
80 2
        return $this;
81
    }
82
83 5
    public function setInstance($instance)
84
    {
85 5
        $this->instance = $instance;
86
87 5
        return $this;
88
    }
89
90
    public function getSlug()
91
    {
92
        return $this->slug;
93
    }
94
95
    public function getName()
96
    {
97
        return transcrud($this->name);
98
    }
99
100 1
    public function getModel()
101
    {
102 1
        return $this->model;
103
    }
104
105
    public function getInstance()
106
    {
107
        return $this->instance;
108
    }
109
110
    /**
111
     * @return array
112
     */
113
    public function getConfig()
114
    {
115
        return $this->config;
116
    }
117
118
    public function isSoftDeletes()
119
    {
120
        return $this->getConfigValue('soft_deletes') ? true : false;
121
    }
122
123 8
    public function getColumns($action, $withForeignKeys = false)
124
    {
125 8
        $tableColumns = $this->dbal->getTableColumns();
126
127 8
        $filteredColumns = [];
128 8
        foreach ($tableColumns as $name => $column) {
129 8
            $filteredColumns[str_replace('`', '', $name)] = $column;
130 8
        }
131 8
        $tableColumns = $filteredColumns;
132
133
134 8
        $foreignKeysName = [];
135 8
        if ($withForeignKeys === false) {
136 8
            $foreignKeys = $this->dbal->getTableForeignKeys();
137
138 8
            foreach ($foreignKeys as $foreignKey) {
139
                foreach ($foreignKey->getColumns() as $columnName) {
140
                    $foreignKeysName[] = $columnName;
141
                }
142 8
            }
143 8
        }
144
145 8
        $customDisplayedColumns = $this->getConfigValue($action, 'display');
146 8
        $customHiddenColumns = $this->getConfigValue($action, 'hide') ? : [];
147
148 8
        $columns = array();
149 8
        if (! empty($customDisplayedColumns) && is_array($customDisplayedColumns)) {
150 8
            foreach ($customDisplayedColumns as $customColumn) {
151 8
                if (strpos($customColumn, '.')) {
152
                    $customColumnRelation = explode('.', $customColumn);
153
154
                    $customColumnRelationFieldName = array_pop($customColumnRelation);
155
156
                    $modelAbstractor = $this;
157
                    foreach ($customColumnRelation as $relationName) {
158
                        $nestedRelation = $this->getNestedRelation($modelAbstractor, $relationName);
159
                        $modelAbstractor = $nestedRelation->getModelAbstractor();
160
                    }
161
162
                    $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...
163
164
                    if (! array_key_exists($customColumnRelationFieldName, $relationColumns)) {
165
                        throw new AbstractorException("Column " . $customColumnRelationFieldName . " does not exist on relation " . implode('.', $customColumnRelation) . " of model " . $this->getModel());
166
                    }
167
168
                    $columns[$customColumn] = $relationColumns[$customColumnRelationFieldName];
169
                } else {
170 8
                    if (! array_key_exists($customColumn, $tableColumns)) {
171
                        throw new AbstractorException("Column " . $customColumn . " does not exist on " . $this->getModel());
172
                    }
173
174 8
                    $columns[$customColumn] = $tableColumns[$customColumn];
175
                }
176 8
            }
177 8
        } else {
178
            foreach ($tableColumns as $name => $column) {
179
                if (in_array($name, $customHiddenColumns)) {
180
                    continue;
181
                }
182
183
                if (in_array($name, $foreignKeysName)) {
184
                    continue;
185
                }
186
187
                $columns[$name] = $column;
188
            }
189
        }
190
191 8
        return $columns;
192
    }
193
194
    protected function getNestedRelation(Model $modelAbstractor, $relationName)
195
    {
196
        $relations = $modelAbstractor->getRelations();
197
198
        if (! $relations->has($relationName)) {
199
            throw new AbstractorException("Relation " . $relationName . " not configured on " . $modelAbstractor->getModel());
200
        }
201
202
        $relation = $relations->get($relationName);
203
204
        if ($relation instanceof Relation) {
205
            return $relation;
206
        } else {
207
            return $relation['relation'];
208
        }
209
    }
210
211
    /**
212
     * @return \Illuminate\Support\Collection
213
     */
214 4
    public function getRelations()
215
    {
216 4
        $configRelations = $this->getConfigValue('relations');
217
218 4
        $relations = collect();
219
220 4
        if (! empty($configRelations)) {
221 4
            foreach ($configRelations as $relationName => $configRelation) {
222 4
                if (is_int($relationName)) {
223
                    $relationName = $configRelation;
224
                }
225
226 4
                $config = [];
227 4
                if ($configRelation !== $relationName) {
228 4
                    if (! is_array($configRelation)) {
229
                        $config['type'] = $configRelation;
230
                    } else {
231 4
                        $config = $configRelation;
232
                    }
233 4
                }
234
235
                /** @var Relation $relation */
236 4
                $relation = $this->relationFactory->setModel($this->instance)
237 4
                    ->setConfig($config)
238 4
                    ->get($relationName);
239
240 4
                $secondaryRelations = $relation->getSecondaryRelations();
241
242
243 4
                if (! $secondaryRelations->isEmpty()) {
244 1
                    $relations->put(
245 1
                        $relationName,
246 1
                        collect(['relation' => $relation, 'secondaryRelations' => $secondaryRelations])
247 1
                    );
248 1
                } else {
249 3
                    $relations->put($relationName, $relation);
250
                }
251 4
            }
252 4
        }
253
254 4
        return $relations;
255
    }
256
257
    /**
258
     * @param string|null $arrayKey
259
     * @return array
260
     * @throws AbstractorException
261
     */
262 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...
263
    {
264 2
        $columns = $this->getColumns('list');
265
266 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ? : [];
267
268 2
        $fields = array();
269 2
        foreach ($columns as $name => $column) {
270 2
            $presentation = null;
271 2
            if (array_key_exists($name, $fieldsPresentation)) {
272 2
                $presentation = $fieldsPresentation[$name];
273 2
            }
274
275
            $config = [
276 2
                'name'         => $name,
277 2
                'presentation' => $presentation,
278 2
                'form_type'    => null,
279 2
                'validation'   => null,
280
                'functions'    => null
281 2
            ];
282
283 2
            $fields[$arrayKey][] = $this->fieldFactory
284 2
                ->setColumn($column)
285 2
                ->setConfig($config)
286 2
                ->get();
287 2
        }
288
289 2
        return $fields;
290
    }
291
292
    /**
293
     * @param string|null $arrayKey
294
     * @return array
295
     * @throws AbstractorException
296
     */
297 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...
298
    {
299 2
        $columns = $this->getColumns('detail');
300
301 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ? : [];
302
303 2
        $fields = array();
304 2
        foreach ($columns as $name => $column) {
305 2
            $presentation = null;
306 2
            if (array_key_exists($name, $fieldsPresentation)) {
307 2
                $presentation = $fieldsPresentation[$name];
308 2
            }
309
310
            $config = [
311 2
                'name'         => $name,
312 2
                'presentation' => $presentation,
313 2
                'form_type'    => null,
314 2
                'validation'   => null,
315
                'functions'    => null
316 2
            ];
317
318 2
            $fields[$arrayKey][] = $this->fieldFactory
319 2
                ->setColumn($column)
320 2
                ->setConfig($config)
321 2
                ->get();
322 2
        }
323
324 2
        return $fields;
325
    }
326
327
    /**
328
     * @param bool|null $withForeignKeys
329
     * @param string|null $arrayKey
330
     * @return array
331
     * @throws AbstractorException
332
     */
333 4
    public function getEditFields($withForeignKeys = false, $arrayKey = 'main')
334
    {
335 4
        $columns = $this->getColumns('edit', $withForeignKeys);
0 ignored issues
show
Bug introduced by
It seems like $withForeignKeys defined by parameter $withForeignKeys on line 333 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...
336
337 4
        $this->readConfig('edit');
338
339 4
        $fields = array();
340 4
        foreach ($columns as $name => $column) {
341 4
            if (! in_array($name, $this->getReadOnlyColumns())) {
342 4
                $presentation = null;
343 4
                if (array_key_exists($name, $this->fieldsPresentation)) {
344
                    $presentation = $this->fieldsPresentation[$name];
345
                }
346
347
                $config = [
348 4
                    'name'         => $name,
349 4
                    'presentation' => $presentation,
350 4
                    'form_type'    => null,
351 4
                    'validation'   => null,
352
                    'functions'    => null
353 4
                ];
354
355 4
                $config = $this->setConfig($config, $name);
356
357 4
                $field = $this->fieldFactory
358 4
                    ->setColumn($column)
359 4
                    ->setConfig($config)
360 4
                    ->get();
361
362 4
                if (! empty($this->instance) && ! empty($this->instance->getAttribute($name))) {
363
                    $field->setValue($this->instance->getAttribute($name));
364
                }
365
366 4
                $fields[$arrayKey][$name] = $field;
367
368 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...
369 4
                    $field = $this->fieldFactory
370 4
                        ->setColumn($column)
371 4
                        ->setConfig([
372 4
                            'name'         => $name . '__delete',
373 4
                            'presentation' => null,
374 4
                            'form_type'    => 'checkbox',
375 4
                            'no_validate'  => true,
376
                            'functions'    => null
377 4
                        ])
378 4
                        ->get();
379 4
                    $fields[$arrayKey][$name . '__delete'] = $field;
380 4
                }
381 4
            }
382 4
        }
383
384 4
        return $fields;
385
    }
386
387 4
    protected function getReadOnlyColumns()
388
    {
389 4
        $columns = [LaravelModel::CREATED_AT, LaravelModel::UPDATED_AT];
390
391 4
        $columns[] = $this->dbal->getModel()->getKeyName();
392
393 4
        return $columns;
394
    }
395
396
    /**
397
     * @param string $action
398
     * @return ElementInterface
399
     */
400 2
    public function getForm($action)
401
    {
402 2
        $this->generator->setModelFields($this->getEditFields());
403 2
        $this->generator->setRelatedModelFields($this->getRelations());
404
405 2
        return $this->generator->getForm($action);
406
    }
407
408
    /**
409
     * @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...
410
     * @return mixed
411
     */
412 1
    public function persist(Request $request)
413
    {
414
        /** @var \ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager $modelManager */
415 1
        $modelManager = App::make('ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager');
416 1
        if (! empty($this->instance)) {
417
            $item = $this->instance;
418
        } else {
419 1
            $item = $modelManager->getModelInstance($this->getModel());
420
        }
421
422
423 1
        $fields = $this->getEditFields(true);
424 1
        if (empty($fields['main']) && $this->getRelations()->isEmpty()) {
425
            return;
426
        }
427
428 1
        if (! empty($fields['main'])) {
429 1
            $skip = null;
430 1
            foreach ($fields['main'] as $key => $field) {
431
                /** @var FieldContract $field */
432 1
                if ($skip === $key) {
433
                    $skip = null;
434
                    continue;
435
                }
436 1
                $fieldName = $field->getName();
437 1
                $requestValue = $request->input("main.{$fieldName}");
438
439 1
                if (get_class($field->getFormField()) === \FormManager\Fields\Checkbox::class) {
440
                    if (empty($requestValue)) {
441
                        // Unchecked checkboxes are not sent, so we force setting them to false
442
                        $item->setAttribute(
443
                            $fieldName,
444
                            $field->applyFunctions(null)
445
                        );
446
                    } else {
447
                        $requestValue = true;
448
                    }
449
                }
450
451 1
                if (get_class($field->getFormField()) === \FormManager\Fields\File::class) {
452
                    $handleResult = $this->handleField($request, $item, $fields['main'], 'main', $fieldName,$this->mustDeleteFilesInFilesystem);
453
                    if (! empty($handleResult['skip'])) {
454
                        $skip = $handleResult['skip'];
455
                    }
456
                    if (! empty($handleResult['requestValue'])) {
457
                        $requestValue = $handleResult['requestValue'];
458
                    }
459
                }
460
461
462 1
                if (! $field->saveIfEmpty() && empty($requestValue)) {
463
                    continue;
464
                }
465
466 1
                if (! empty($requestValue) || (empty($requestValue) && ! empty($item->getAttribute($fieldName)))) {
467 1
                    $item->setAttribute(
468 1
                        $fieldName,
469 1
                        $field->applyFunctions($requestValue)
470 1
                    );
471 1
                }
472 1
            }
473 1
        }
474
475 1
        $item->save();
476
477 1
        $this->setInstance($item);
478
479
480 1
        if (! empty($relations = $this->getRelations())) {
481 1
            foreach ($relations as $relationKey => $relation) {
482 1
                if ($relation instanceof Collection) {
483
                    $input = $request->input($relationKey);
484
                    /** @var $relationInstance Relation */
485
                    $relationInstance = $relation->get('relation');
486
                    $relationInstance->persist($input, $request);
0 ignored issues
show
Bug introduced by
It seems like $input defined by $request->input($relationKey) on line 483 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...
487
                } else {
488
                    /** @var $relation Relation */
489 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...
490
                }
491 1
            }
492 1
        }
493
494 1
        return $item;
495
    }
496
497
    /**
498
     * @return array
499
     */
500 1
    public function getValidationRules()
501
    {
502 1
        return $this->generator->getValidationRules();
503
    }
504
505
    public function getFieldValue($item, $fieldName)
506
    {
507
        $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...
508
509
        if (strpos($fieldName, '.')) {
510
            $customColumnRelation = explode('.', $fieldName);
511
512
            $customColumnRelationFieldName = array_pop($customColumnRelation);
513
514
            $entity = $item;
515
            $relation = null;
516
            $relationName = '';
517
            foreach ($customColumnRelation as $relationName) {
518
                $relation = $entity->{$relationName};
519
                if ($relation instanceof Collection) {
520
                    $entity = $relation->first();
521
                } else {
522
                    $entity = $relation;
523
                }
524
            }
525
526
            $lastRelationName = $relationName;
527
528
            array_pop($customColumnRelation);
529
530
            $prevModelAbtractor = $this;
531
            foreach ($customColumnRelation as $relationName) {
532
                $nestedRelation = $this->getNestedRelation($prevModelAbtractor, $relationName);
533
                $prevModelAbtractor = $nestedRelation->getModelAbstractor();
534
            }
535
536
            if (empty($relation)) {
537
                return null;
538
            }
539
540
            if ($relation instanceof Collection) {
541
                $relations = $prevModelAbtractor->getRelations();
542
543
                $relationAbstractor = $relations->get($lastRelationName);
544
545
                if ($relationAbstractor instanceof \Anavel\Crud\Abstractor\Eloquent\Relation\Translation) {
546
                    $value = $entity->getAttribute($customColumnRelationFieldName);
547
                } else {
548
                    $value = $relation->implode($customColumnRelationFieldName, ', ');
549
                }
550
            } else {
551
                $value = $relation->getAttribute($customColumnRelationFieldName);
552
            }
553
        } else {
554
            $value = $item->getAttribute($fieldName);
555
        }
556
557
        return $value;
558
    }
559
560
    /**
561
     * @return boolean
562
     */
563
    public function mustDeleteFilesInFilesystem()
564
    {
565
        return $this->mustDeleteFilesInFilesystem;
566
    }
567
}
568