Completed
Push — master ( ee2ad8...88c902 )
by
unknown
03:03
created

MiniCrud::getEditFields()   D

Complexity

Conditions 16
Paths 4

Size

Total Lines 84
Code Lines 50

Duplication

Lines 9
Ratio 10.71 %

Code Coverage

Tests 52
CRAP Score 16.0931

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 9
loc 84
ccs 52
cts 56
cp 0.9286
rs 4.8736
cc 16
eloc 50
nc 4
nop 1
crap 16.0931

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\Relation;
3
4
use Anavel\Crud\Abstractor\Eloquent\Relation\Traits\CheckRelationCompatibility;
5
use Anavel\Crud\Contracts\Abstractor\Field;
6
use Anavel\Crud\Contracts\Abstractor\Relation as RelationContract;
7
use App;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Collection;
11
12
class MiniCrud extends Relation
13
{
14
    use CheckRelationCompatibility;
15
16
    /** @var \ANavallaSuiza\Laravel\Database\Contracts\Dbal\AbstractionLayer $dbal */
17
    protected $dbal;
18
19
    protected $compatibleEloquentRelations = array(
20
        'Illuminate\Database\Eloquent\Relations\HasMany'
21
    );
22
23 10
    public function setup()
24
    {
25 10
        $this->checkRelationCompatibility();
26 8
    }
27
28
    /**
29
     * @return array
30
     */
31 2
    public function getEditFields($arrayKey = null)
32
    {
33 2
        $fields = [];
34
35 2
        if (empty($arrayKey)) {
36 2
            $arrayKey = $this->name;
37 2
        }
38
39 2
        $columns = $this->modelAbstractor->getColumns('edit');
40
41 2
        $this->readConfig('edit');
42
43
        /** @var Collection $results */
44 2
        $results = $this->eloquentRelation->getResults();
45
46 2
        $results->put('emptyResult', '');
47 2
        if (! empty($columns)) {
48 2
            $readOnly = [Model::CREATED_AT, Model::UPDATED_AT];
49 2
            foreach ($results as $key => $result) {
50 2
                $tempFields = [];
51 2
                $index = $key === 'emptyResult' ? 0 : $result->id;
52 2
                foreach ($columns as $columnName => $column) {
53 2
                    if (in_array($columnName, $readOnly, true)) {
54
                        continue;
55
                    }
56 2
                    if ($this->skipField($columnName, $key)) {
57
                        continue;
58
                    }
59
60
61 2
                    $formType = null;
62 2
                    if ($key !== 'emptyResult' && ($columnName === $this->eloquentRelation->getParent()->getKeyName())) {
63
                        $formType = 'hidden';
64
                    }
65
66
                    $config = [
67 2
                        'name'         => $columnName,
68 2
                        'presentation' => $this->name . ' ' . ucfirst(transcrud($columnName)) . ' [' . $index . ']',
69 2
                        'form_type'    => $formType,
70 2
                        'no_validate'  => true,
71 2
                        'validation'   => null,
72
                        'functions'    => null
73 2
                    ];
74
75 2
                    $config = $this->setConfig($config, $columnName);
76
77
                    /** @var Field $field */
78 2
                    $field = $this->fieldFactory
79 2
                        ->setColumn($column)
80 2
                        ->setConfig($config)
81 2
                        ->get();
82
83 2
                    if ($key !== 'emptyResult') {
84 2
                        $field->setValue($result->getAttribute($columnName));
85 2
                    }
86 2
                    $tempFields[] = $field;
87 2
                }
88 2
89 2
                $relationModel = $this->eloquentRelation->getRelated()->newInstance();
90 2
                if (! empty($result)) {
91
                    $relationModel = $result;
92 2
                }
93
                $this->modelAbstractor->setInstance($relationModel);
94 2
                $secondaryRelations = $this->getSecondaryRelations();
95
                if (! empty($secondaryRelations)) {
96 View Code Duplication
                    foreach ($secondaryRelations as $secondaryRelationKey => $secondaryRelation) {
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...
97
                        foreach ($secondaryRelation->getEditFields($secondaryRelationKey) as $editGroupName => $editGroup) {
98
                            if ($secondaryRelation->getType() === 'Anavel\Crud\Abstractor\Eloquent\Relation\Select') {
99
                                $tempFields[key($editGroup)] = $editGroup[key($editGroup)];
100
                            } else {
101 4
                                $tempFields[$editGroupName] = $editGroup;
102
                            }
103 4
                        };
104 4
                    }
105 4
                }
106 4
107
                $fields[$arrayKey][$index] = $tempFields;
108 4
            }
109 4
        }
110 4
111 4
//        $fields = $this->addSecondaryRelationFields($fields);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
112 2
113 2
        return $fields;
114 2
    }
115
116
    /**
117 4
     * @param array|null $relationArray
118
     * @return mixed
119 4
     */
120 4
    public function persist(array $relationArray = null)
121
    {
122
        if (! empty($relationArray)) {
123 4
            $keyName = $this->eloquentRelation->getParent()->getKeyName();
124 4
            $currentRelations = $this->eloquentRelation->get()->keyBy($keyName);
125 1
126 1
            foreach ($relationArray as $relation) {
127
                if (! empty($relation[$keyName])
128
                    && ($currentRelations->has($relation[$keyName]))
129 4
                ) {
130 4
                    $relationModel = $currentRelations->get($relation[$keyName]);
131 4
                } else {
132
                    $relationModel = $this->eloquentRelation->getRelated()->newInstance();
133 4
                }
134 4
135
                $this->modelAbstractor->setInstance($relationModel);
136 4
                $secondaryRelations = $this->getSecondaryRelations();
137 4
138
139 4
                $this->setKeys($relationModel);
140 1
141
                $shouldBeSkipped = true;
142 1
                $delayedRelations = collect();
143
144 1
145 1
                foreach ($relation as $fieldKey => $fieldValue) {
146 1
                    if ($secondaryRelations->has($fieldKey)) {
147 1
                        $delayedRelations->put($fieldKey, $fieldValue);
148 4
                        continue;
149 4
                    }
150 4
151 4
                    if ($shouldBeSkipped) {
152
                        $shouldBeSkipped = ($shouldBeSkipped === ($fieldValue === ''));
153 2
                    }
154
155 2
                    $relationModel->setAttribute($fieldKey, $fieldValue);
156 2
                }
157
158 1
                if (! $shouldBeSkipped) {
159
                    $relationModel->save();
160 1
161
                    if (! $delayedRelations->isEmpty()) {
162
                        foreach ($delayedRelations as $relationKey => $delayedRelation) {
163
                            /** @var RelationContract $secondaryRelation */
164 1
                            $secondaryRelation = $secondaryRelations->get($relationKey);
165
166
                            $secondaryRelation->persist($delayedRelation);
167
                        }
168 1
                    }
169
                }
170
            }
171
        }
172
    }
173
174
    protected function setKeys(Model $relationModel)
175
    {
176
        $relationModel->setAttribute($this->eloquentRelation->getForeignKey(), $this->relatedModel->id);
177
    }
178
179 View Code Duplication
    protected function skipField($columnName, $key)
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...
180
    {
181
        if ($columnName === $this->eloquentRelation->getPlainForeignKey()) {
182
            return true;
183 2
        }
184
185 2
        if ($key === 'emptyResult' && ($columnName === $this->eloquentRelation->getParent()->getKeyName())) {
186 2
            return true;
187 2
        }
188
189
        return false;
190
    }
191
192
    /**
193 2
     * @return string
194 2
     */
195 2
    public function getDisplayType()
196 2
    {
197 2
        return self::DISPLAY_TYPE_TAB;
198 2
    }
199
200 2
    /**
201
     * @param array $fields
202
     * @return array
203
     */
204
    public function addSecondaryRelationFields(array $fields)
205
    {
206
        $tempFields = [];
207 View Code Duplication
        foreach ($this->getSecondaryRelations() as $relationKey => $relation) {
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...
208
            foreach ($relation->getEditFields($relationKey) as $editGroupName => $editGroup) {
209
                if ($relation->getType() === 'Anavel\Crud\Abstractor\Eloquent\Relation\Select') {
210
                    $tempFields[key($editGroup)] = $editGroup[key($editGroup)];
211
                } else {
212
                    $tempFields[$editGroupName] = $editGroup;
213
                }
214
            };
215
        }
216
        foreach ($fields[$this->name] as $groupKey => $mainFields) {
217
            $combinedFields = array_merge($mainFields, $tempFields);
218
            $fields[$this->name][$groupKey] = $combinedFields;
219
        }
220
221
        return $fields;
222
    }
223
}
224
225