FieldController::update()   F
last analyzed

Complexity

Conditions 30
Paths 5283

Size

Total Lines 88

Duplication

Lines 8
Ratio 9.09 %

Importance

Changes 0
Metric Value
dl 8
loc 88
rs 0
c 0
b 0
f 0
cc 30
nc 5283
nop 3

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
3
namespace Fabrica\Http\Api;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Event;
7
8
use Fabrica\Events\FieldChangeEvent;
9
use Fabrica\Events\FieldDeleteEvent;
10
use Fabrica\Http\Requests;
11
use Fabrica\Http\Api\Controller;
12
use Fabrica\Customization\Eloquent\Field;
13
use Fabrica\Customization\Eloquent\Screen;
14
use Fabrica\Project\Eloquent\Project;
15
use Fabrica\Project\Provider;
16
17
use DB;
18
19
class FieldController extends Controller
20
{
21
    private $special_fields = [
22
        'id', 
23
        'type', 
24
        'state', 
25
        'reporter', 
26
        'modifier', 
27
        'created_at', 
28
        'updated_at', 
29
        'resolved_at', 
30
        'closed_at', 
31
        'regression_times', 
32
        'his_resolvers',
33
        'resolved_logs',
34
        'no', 
35
        'schema', 
36
        'parent_id', 
37
        'parent', 
38
        'links', 
39
        'subtasks', 
40
        'entry_id', 
41
        'definition_id', 
42
        'comments_num', 
43
        'worklogs_num', 
44
        'gitcommits_num', 
45
        'sprint', 
46
        'sprints', 
47
        'filter', 
48
        'from',
49
        'from_kanban_id',
50
        'limit',
51
        'page',
52
        'orderBy',
53
        'stat_x',
54
        'stat_y',
55
    ];
56
57
    private $sys_fields = [
58
        'title',
59
        'priority',
60
        'resolution',
61
        'assignee',
62
        'module',
63
        'comments',
64
        'resolve_version',
65
        'effect_versions',
66
        'expect_complete_time',
67
        'expect_start_time',
68
        'progress',
69
        'related_users',
70
        'descriptions',
71
        'epic',
72
        'labels',
73
        'original_estimate',
74
        'story_points',
75
        'attachments'
76
    ];
77
78
    private $all_types = [
79
        'Tags', 
80
        'Integer', 
81
        'Number', 
82
        'Text', 
83
        'TextArea', 
84
        'Select', 
85
        'MultiSelect', 
86
        'RadioGroup', 
87
        'CheckboxGroup', 
88
        'DatePicker', 
89
        'DateTimePicker', 
90
        'TimeTracking', 
91
        'File', 
92
        'SingleVersion', 
93
        'MultiVersion', 
94
        'SingleUser', 
95
        'MultiUser', 
96
        'Url'
97
    ];
98
    /**
99
     * Display a listing of the resource.
100
     *
101
     * @return \Illuminate\Http\Response
102
     */
103
    public function index($project_key)
104
    {
105
        $fields = Provider::getFieldList($project_key);
106
        foreach ($fields as $field)
107
        {
108
            $field->screens = Screen::whereRaw([ 'field_ids' => $field->id ])
109
                ->orderBy('project_key', 'asc')
110
                ->get(['project_key', 'name'])
111
                ->toArray();
112
113
            $field->is_used = !!($field->screens);
114
115
            $field->screens = array_filter(
116
                $field->screens, function ($item) use ($project_key) { 
117
                    return $item['project_key'] === $project_key || $item['project_key'] === '$_sys_$';
118
                }
119
            );
120
        }
121
        $types = Provider::getTypeList($project_key, ['name']);
122
        return response()->json(['ecode' => 0, 'data' => $fields, 'options' => [ 'types' => $types ]]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
123
    }
124
125
    /**
126
     * Store a newly created resource in storage.
127
     *
128
     * @param  \Illuminate\Http\Request $request
129
     * @return \Illuminate\Http\Response
130
     */
131
    public function store(Request $request, $project_key)
132
    {
133
        $name = $request->input('name');
134
        if (!$name) {
135
            throw new \UnexpectedValueException('the name cannot be empty.', -12200);
136
        }
137
138
        $key = $request->input('key');
139
        if (!$key) {
140
            throw new \InvalidArgumentException('field key cannot be empty.', -12201);
141
        }
142
143
        if (in_array($key, $this->special_fields)) {
144
            throw new \InvalidArgumentException('field key has been used by system.', -12202);
145
        }
146
147
        if (Provider::isFieldKeyExisted($project_key, $key)) {
148
            throw new \InvalidArgumentException('field key cannot be repeated.', -12203);
149
        }
150
151
        $type = $request->input('type');
152
        if (!$type) {
153
            throw new \UnexpectedValueException('the type cannot be empty.', -12204);
154
        }
155
156
        if ($type === 'TimeTracking' && Provider::isFieldKeyExisted($project_key, $key . '_m')) {
157
            throw new \InvalidArgumentException('field key cannot be repeated.', -12203);
158
        }
159
160
        if ($type === 'MultiUser' && Provider::isFieldKeyExisted($project_key, $key . '_ids')) {
161
            throw new \UnexpectedValueException('the type cannot be empty.', -12204);
162
        }
163
164
        if (!in_array($type, $this->all_types)) {
165
            throw new \UnexpectedValueException('the type is incorrect type.', -12205);
166
        }
167
168
        $optionTypes = [ 'Select', 'MultiSelect', 'RadioGroup', 'CheckboxGroup' ];
169
        if (in_array($type, $optionTypes)) {
170
            $optionValues = $request->input('optionValues') ?: [];
171
            foreach ($optionValues as $key => $val)
172
            {
173
                if (!isset($val['name']) || !$val['name']) {
174
                    continue;
175
                }
176
                $optionValues[$key]['id'] = md5(microtime() . $val['name']);
177
            }
178
179
            $defaultValue = $request->input('defaultValue') ?: '';
180
            if ($defaultValue) {
181
                $defaults = is_array($defaultValue) ? $defaultValue : explode(',', $defaultValue);
182
                $options = array_column($optionValues, 'id');
183 View Code Duplication
                if ('MultiSelect' === $type || 'CheckboxGroup' === $type) {
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...
184
                    $defaultValue = array_values(array_intersect($defaults, $options));
185
                }
186
                else
187
                {
188
                    $defaultValue = implode(',', array_intersect($defaults, $options));
189
                }
190
            }
191
            $field = Field::create([ 'project_key' => $project_key, 'optionValues' => $optionValues, 'defaultValue' => $defaultValue ] + $request->all());
192
        }
193
        else
194
        {
195
            $field = Field::create([ 'project_key' => $project_key ] + $request->all());
196
        }
197
        return response()->json(['ecode' => 0, 'data' => $field]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
198
    }
199
200
    /**
201
     * Display the specified resource.
202
     *
203
     * @param  int $id
204
     * @return \Illuminate\Http\Response
205
     */
206
    public function show($project_key, $id)
207
    {
208
        $field = Field::find($id);
209
        //if (!$field || $project_key != $field->project_key)
210
        //{
211
        //    throw new \UnexpectedValueException('the field does not exist or is not in the project.', -10002);
212
        //}
213
        // get related screen
214
        $field->screens = Screen::whereRaw([ 'field_ids' => $id ])->get(['name']);
215
216
        return response()->json(['ecode' => 0, 'data' => $field]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
217
    }
218
219
    /**
220
     * Update the specified resource in storage.
221
     *
222
     * @param  \Illuminate\Http\Request $request
223
     * @param  int                      $id
224
     * @return \Illuminate\Http\Response
225
     */
226
    public function update(Request $request, $project_key, $id)
227
    {
228
        $name = $request->input('name');
229
        if (isset($name)) {
230
            if (!$name) {
231
                throw new \UnexpectedValueException('the name can not be empty.', -12200);
232
            }
233
        }
234
235
        $field = Field::find($id);
236
        if (!$field || $project_key != $field->project_key) {
237
            throw new \UnexpectedValueException('the field does not exist or is not in the project.', -12206);
238
        }
239
240
        $updValues = [];
241
242
        $optionTypes = [ 'Select', 'MultiSelect', 'RadioGroup', 'CheckboxGroup' ];
243
        if (in_array($field->type, $optionTypes)) {
244
            $optionValues = $request->input('optionValues');
245
            $defaultValue = $request->input('defaultValue');
246
            if (isset($optionValues) || isset($defaultValue)) {
247
                if (isset($optionValues)) {
248
                    if (isset($field->optionValues) && $field->optionValues) {
249
                        $old_option_ids = array_column($field->optionValues, 'id');
250
                    }
251
                    else
252
                    {
253
                        $old_option_ids = [];
254
                    }
255
256
                    foreach ($optionValues as $key => $val)
257
                    {
258
                        if (!isset($val['name']) || !$val['name']) {
259
                            continue;
260
                        }
261
262
                        if (!isset($val['id']) || !in_array($val['id'], $old_option_ids)) {
263
                            $optionValues[$key]['id'] = md5(microtime() . $val['name']);
264
                        }
265
                    }
266
                }
267
                else
268
                {
269
                    $optionValues = $field->optionValues ?: [];
270
                }
271
                $updValues['optionValues'] = $optionValues;
272
273
                $options = array_column($optionValues, 'id');
274
                $defaultValue = isset($defaultValue) ? $defaultValue : ($field->defaultValue ?: '');
275
                $defaults = is_array($defaultValue) ? $defaultValue : explode(',', $defaultValue);
276 View Code Duplication
                if ('MultiSelect' === $field->type || 'CheckboxGroup' === $field->type) {
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...
277
                    $defaultValue = array_values(array_intersect($defaults, $options));
278
                }
279
                else
280
                {
281
                    $defaultValue = implode(',', array_intersect($defaults, $options));
282
                }
283
                $updValues['defaultValue'] = $defaultValue;
284
            }
285
        }
286
287
        $mmTypes = [ 'Number', 'Integer' ];
288
        if (in_array($field->type, $mmTypes)) {
289
            $maxValue = $request->input('maxValue');
290
            if (isset($maxValue)) {
291
                $updValues['maxValue'] = ($maxValue === '' ? '' : ($maxValue + 0));
292
            }
293
294
            $minValue = $request->input('minValue');
295
            if (isset($minValue)) {
296
                $updValues['minValue'] = ($minValue === '' ? '' : ($minValue + 0));
297
            }
298
        }
299
300
        $mlTypes = [ 'Text', 'TextArea' ];
301
        if (in_array($field->type, $mlTypes)) {
302
            $maxLength = $request->input('maxLength');
303
            if (isset($maxLength)) {
304
                $updValues['maxLength'] = ($maxLength === '' ? '' : intval($maxLength));
305
            }
306
        }
307
308
        $field->fill($updValues + $request->except(['project_key', 'key', 'type']))->save();
309
310
        Event::fire(new FieldChangeEvent($id));
311
312
        return response()->json(['ecode' => 0, 'data' => Field::find($id)]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
313
    }
314
315
    /**
316
     * Remove the specified resource from storage.
317
     *
318
     * @param  int $id
319
     * @return \Illuminate\Http\Response
320
     */
321
    public function destroy($project_key, $id)
322
    {
323
        $field = Field::find($id);
324
        if (!$field || $project_key != $field->project_key) {
325
            throw new \UnexpectedValueException('the field does not exist or is not in the project.', -12206);
326
        }
327
328
        if (in_array($field->key, $this->sys_fields)) {
329
            throw new \UnexpectedValueException('the field is built in the system.', -12208);
330
        }
331
332
        $isUsed = Screen::whereRaw([ 'field_ids' => $id ])->exists();
333
        if ($isUsed) {
334
            throw new \UnexpectedValueException('the field has been used in screen.', -12207);
335
        }
336
337
        Field::destroy($id);
338
339
        Event::fire(new FieldDeleteEvent($project_key, $id, $field->key, $field->type));
340
        return response()->json(['ecode' => 0, 'data' => ['id' => $id]]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
341
    }
342
343
    /**
344
     * view the application in the all projects.
345
     *
346
     * @return \Illuminate\Http\Response
347
     */
348 View Code Duplication
    public function viewUsedInProject($project_key, $id)
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...
349
    {
350
        if ($project_key !== '$_sys_$') {
351
            return response()->json(['ecode' => 0, 'data' => [] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
352
        }
353
354
        $res = [];
355
        $projects = Project::all();
356
        foreach($projects as $project)
357
        {
358
            $screens = Screen::where('field_ids', $id)
359
                ->where('project_key', '<>', '$_sys_$')
360
                ->where('project_key', $project->key)
361
                ->get([ 'id', 'name' ])
362
                ->toArray();
363
364
            if ($screens) {
365
                $res[] = [ 'key' => $project->key, 'name' => $project->name, 'status' => $project->status, 'screens' => $screens ];
366
            }
367
        }
368
369
        return response()->json(['ecode' => 0, 'data' => $res ]);
370
    }
371
}
372