Completed
Push — master ( d25c87...3d1d4f )
by
unknown
05:07
created

Model::persist()   C

Complexity

Conditions 16
Paths 10

Size

Total Lines 68
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 27.3758

Importance

Changes 9
Bugs 0 Features 0
Metric Value
c 9
b 0
f 0
dl 0
loc 68
ccs 31
cts 48
cp 0.6458
rs 5.7201
cc 16
eloc 39
nc 10
nop 1
crap 27.3758

How to fix   Long Method    Complexity   

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
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\Model as ModelAbstractorContract;
7
use Anavel\Crud\Abstractor\ConfigurationReader;
8
use Anavel\Crud\Contracts\Abstractor\Relation;
9
use Anavel\Crud\Contracts\Abstractor\RelationFactory as RelationFactoryContract;
10
use Anavel\Crud\Contracts\Abstractor\FieldFactory as FieldFactoryContract;
11
use ANavallaSuiza\Laravel\Database\Contracts\Dbal\AbstractionLayer;
12
use FormManager\ElementInterface;
13
use Illuminate\Database\Eloquent\Model as LaravelModel;
14
use App;
15
use Anavel\Crud\Contracts\Form\Generator as FormGenerator;
16
use Anavel\Crud\Abstractor\Exceptions\AbstractorException;
17
use Illuminate\Http\Request;
18
use Illuminate\Support\Collection;
19
use League\Flysystem\Adapter\Local;
20
use League\Flysystem\Filesystem;
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 17
    public function __construct(
41
        $config,
42
        AbstractionLayer $dbal,
43
        RelationFactoryContract $relationFactory,
44
        FieldFactoryContract $fieldFactory,
45
        FormGenerator $generator
46
    ) {
47 17
        if (is_array($config)) {
48 17
            $this->model = $config['model'];
49 17
            $this->config = $config;
50 17
        } else {
51
            $this->model = $config;
52
            $this->config = [];
53
        }
54
55 17
        $this->dbal = $dbal;
56 17
        $this->relationFactory = $relationFactory;
57 17
        $this->fieldFactory = $fieldFactory;
58 17
        $this->generator = $generator;
59 17
    }
60
61 3
    public function setSlug($slug)
62
    {
63 3
        $this->slug = $slug;
64
65 3
        return $this;
66
    }
67
68 2
    public function setName($name)
69
    {
70 2
        $this->name = $name;
71
72 2
        return $this;
73
    }
74
75 5
    public function setInstance($instance)
76
    {
77 5
        $this->instance = $instance;
78
79 5
        return $this;
80
    }
81
82
    public function getSlug()
83
    {
84
        return $this->slug;
85
    }
86
87
    public function getName()
88
    {
89
        return transcrud($this->name);
90
    }
91
92 1
    public function getModel()
93
    {
94 1
        return $this->model;
95
    }
96
97
    public function getInstance()
98
    {
99
        return $this->instance;
100
    }
101
102
    public function isSoftDeletes()
103
    {
104
        return $this->getConfigValue('soft_deletes') ? true : false;
105
    }
106
107 8
    public function getColumns($action, $withForeignKeys = false)
108
    {
109 8
        $tableColumns = $this->dbal->getTableColumns();
110
111 8
        $filteredColumns = [];
112 8
        foreach ($tableColumns as $name => $column) {
113 8
            $filteredColumns[str_replace('`', '', $name)] = $column;
114 8
        }
115 8
        $tableColumns = $filteredColumns;
116
117
118 8
        $foreignKeysName = [];
119 8
        if ($withForeignKeys === false) {
120 8
            $foreignKeys = $this->dbal->getTableForeignKeys();
121
122 8
            foreach ($foreignKeys as $foreignKey) {
123
                foreach ($foreignKey->getColumns() as $columnName) {
124
                    $foreignKeysName[] = $columnName;
125
                }
126 8
            }
127 8
        }
128
129 8
        $customDisplayedColumns = $this->getConfigValue($action, 'display');
130 8
        $customHiddenColumns = $this->getConfigValue($action, 'hide') ? : [];
131
132 8
        $columns = array();
133 8
        if (! empty($customDisplayedColumns) && is_array($customDisplayedColumns)) {
134 8
            foreach ($customDisplayedColumns as $customColumn) {
135 8
                if (! array_key_exists($customColumn, $tableColumns)) {
136
                    throw new AbstractorException("Column " . $customColumn . " does not exist on " . $this->getModel());
137
                }
138
139 8
                $columns[$customColumn] = $tableColumns[$customColumn];
140 8
            }
141 8
        } else {
142
            foreach ($tableColumns as $name => $column) {
143
                if (in_array($name, $customHiddenColumns)) {
144
                    continue;
145
                }
146
147
                if (in_array($name, $foreignKeysName)) {
148
                    continue;
149
                }
150
151
                $columns[$name] = $column;
152
            }
153
        }
154
155 8
        return $columns;
156
    }
157
158
    /**
159
     * @return \Illuminate\Support\Collection
160
     */
161 4
    public function getRelations()
162
    {
163 4
        $configRelations = $this->getConfigValue('relations');
164
165 4
        $relations = collect();
166
167 4
        if (! empty($configRelations)) {
168 4
            foreach ($configRelations as $relationName => $configRelation) {
169 4
                if (is_int($relationName)) {
170
                    $relationName = $configRelation;
171
                }
172
173 4
                $config = [];
174 4
                if ($configRelation !== $relationName) {
175 4
                    if (! is_array($configRelation)) {
176
                        $config['type'] = $configRelation;
177
                    } else {
178 4
                        $config = $configRelation;
179
                    }
180 4
                }
181
182
                /** @var Relation $relation */
183 4
                $relation = $this->relationFactory->setModel($this->instance)
184 4
                    ->setConfig($config)
185 4
                    ->get($relationName);
186
187 4
                $secondaryRelations = $relation->getSecondaryRelations();
188
189
190 4
                if (! $secondaryRelations->isEmpty()) {
191 1
                    $relations->put($relationName,
192 1
                        collect(['relation' => $relation, 'secondaryRelations' => $secondaryRelations]));
193 1
                } else {
194 3
                    $relations->put($relationName, $relation);
195
                }
196
197 4
            }
198 4
        }
199
200 4
        return $relations;
201
    }
202
203
    /**
204
     * @param string|null $arrayKey
205
     * @return array
206
     * @throws AbstractorException
207
     */
208 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...
209
    {
210 2
        $columns = $this->getColumns('list');
211
212 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ? : [];
213
214 2
        $fields = array();
215 2
        foreach ($columns as $name => $column) {
216 2
            $presentation = null;
217 2
            if (array_key_exists($name, $fieldsPresentation)) {
218 2
                $presentation = $fieldsPresentation[$name];
219 2
            }
220
221
            $config = [
222 2
                'name'         => $name,
223 2
                'presentation' => $presentation,
224 2
                'form_type'    => null,
225 2
                'validation'   => null,
226
                'functions'    => null
227 2
            ];
228
229 2
            $fields[$arrayKey][] = $this->fieldFactory
230 2
                ->setColumn($column)
231 2
                ->setConfig($config)
232 2
                ->get();
233 2
        }
234
235 2
        return $fields;
236
    }
237
238
    /**
239
     * @param string|null $arrayKey
240
     * @return array
241
     * @throws AbstractorException
242
     */
243 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...
244
    {
245 2
        $columns = $this->getColumns('detail');
246
247 2
        $fieldsPresentation = $this->getConfigValue('fields_presentation') ? : [];
248
249 2
        $fields = array();
250 2
        foreach ($columns as $name => $column) {
251 2
            $presentation = null;
252 2
            if (array_key_exists($name, $fieldsPresentation)) {
253 2
                $presentation = $fieldsPresentation[$name];
254 2
            }
255
256
            $config = [
257 2
                'name'         => $name,
258 2
                'presentation' => $presentation,
259 2
                'form_type'    => null,
260 2
                'validation'   => null,
261
                'functions'    => null
262 2
            ];
263
264 2
            $fields[$arrayKey][] = $this->fieldFactory
265 2
                ->setColumn($column)
266 2
                ->setConfig($config)
267 2
                ->get();
268 2
        }
269
270 2
        return $fields;
271
    }
272
273
    /**
274
     * @param bool|null $withForeignKeys
275
     * @param string|null $arrayKey
276
     * @return array
277
     * @throws AbstractorException
278
     */
279 4
    public function getEditFields($withForeignKeys = false, $arrayKey = 'main')
280
    {
281 4
        $columns = $this->getColumns('edit', $withForeignKeys);
0 ignored issues
show
Bug introduced by
It seems like $withForeignKeys defined by parameter $withForeignKeys on line 279 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...
282
283 4
        $this->readConfig('edit');
284
285 4
        $fields = array();
286 4
        foreach ($columns as $name => $column) {
287 4
            if (! in_array($name, $this->getReadOnlyColumns())) {
288 4
                $presentation = null;
289 4
                if (array_key_exists($name, $this->fieldsPresentation)) {
290
                    $presentation = $this->fieldsPresentation[$name];
291
                }
292
293
                $config = [
294 4
                    'name'         => $name,
295 4
                    'presentation' => $presentation,
296 4
                    'form_type'    => null,
297 4
                    'validation'   => null,
298
                    'functions'    => null
299 4
                ];
300
301 4
                $config = $this->setConfig($config, $name);
302
303 4
                $field = $this->fieldFactory
304 4
                    ->setColumn($column)
305 4
                    ->setConfig($config)
306 4
                    ->get();
307
308 4
                if (! empty($this->instance) && ! empty($this->instance->getAttribute($name))) {
309
                    $field->setValue($this->instance->getAttribute($name));
310
                }
311
312 4
                $fields[$arrayKey][] = $field;
313
314 4
                if (! empty($config['form_type']) && $config['form_type'] === 'file') {
315 4
                    $field = $this->fieldFactory
316 4
                        ->setColumn($column)
317 4
                        ->setConfig([
318 4
                            'name'         => $name . '__delete',
319 4
                            'presentation' => null,
320 4
                            'form_type'    => 'checkbox',
321 4
                            'validation'   => null,
322
                            'functions'    => null
323 4
                        ])
324 4
                        ->get();
325 4
                    $fields[$arrayKey][] = $field;
326 4
                }
327 4
            }
328 4
        }
329
330 4
        return $fields;
331
    }
332
333 4
    protected function getReadOnlyColumns()
334
    {
335 4
        $columns = [LaravelModel::CREATED_AT, LaravelModel::UPDATED_AT];
336
337 4
        $columns[] = $this->dbal->getModel()->getKeyName();
338
339 4
        return $columns;
340
    }
341
342
    /**
343
     * @param string $action
344
     * @return ElementInterface
345
     */
346 2
    public function getForm($action)
347
    {
348 2
        $this->generator->setModelFields($this->getEditFields());
349 2
        $this->generator->setRelatedModelFields($this->getRelations());
350
351 2
        return $this->generator->getForm($action);
352
    }
353
354
    /**
355
     * @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...
356
     * @return mixed
357
     */
358 1
    public function persist(Request $request)
359
    {
360
        /** @var \ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager $modelManager */
361 1
        $modelManager = App::make('ANavallaSuiza\Laravel\Database\Contracts\Manager\ModelManager');
362 1
        if (! empty($this->instance)) {
363
            $item = $this->instance;
364
        } else {
365 1
            $item = $modelManager->getModelInstance($this->getModel());
366
        }
367
368
369 1
        $fields = $this->getEditFields(true);
370 1
        if (empty($fields['main']) && $this->getRelations()->isEmpty()) {
371
            return;
372
        }
373
374 1
        if (! empty($fields['main'])) {
375 1
            $skipNext = false;
376 1
            foreach ($fields['main'] as $key => $field) {
377 1
                if ($skipNext === true) {
378
                    $skipNext = false;
379
                    continue;
380
                }
381 1
                $fieldName = $field->getName();
382 1
                $requestValue = $request->input("main.{$fieldName}");
383
384 1
                if (get_class($field->getFormField()) === \FormManager\Fields\File::class) {
385
                    $handleResult = $this->handleField($request, $item, $fields, $key, 'main', $fieldName);
386
                    if (! empty($handleResult['skipNext'])) {
387
                        $skipNext = $handleResult['skipNext'];
388
                    }
389
                    if (! empty($handleResult['requestValue'])) {
390
                        $requestValue = $handleResult['requestValue'];
391
                    }
392
                }
393
394
395 1
                if (! $field->saveIfEmpty() && empty($requestValue)) {
396
                    continue;
397
                }
398
399 1
                if (! empty($requestValue)) {
400 1
                    $item->setAttribute(
401 1
                        $fieldName,
402 1
                        $field->applyFunctions($requestValue)
403 1
                    );
404 1
                }
405 1
            }
406 1
        }
407
408 1
        $item->save();
409
410 1
        $this->setInstance($item);
411
412
413 1
        if (! empty($relations = $this->getRelations())) {
414 1
            foreach ($relations as $relationKey => $relation) {
415 1
                if ($relation instanceof Collection) {
416
                    $input = $request->input($relationKey);
417
                    $relation->get('relation')->persist($input);
418
                } else {
419 1
                    $relation->persist($request->input($relationKey));
420
                }
421 1
            }
422 1
        }
423
424 1
        return $item;
425
    }
426
427
    /**
428
     * @return array
429
     */
430 1
    public function getValidationRules()
431
    {
432 1
        return $this->generator->getValidationRules();
433
    }
434
}
435