Passed
Push — master ( 28338c...36cb24 )
by Jianhua
08:56
created

EntityFieldController::save()   C

Complexity

Conditions 12
Paths 11

Size

Total Lines 65
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 50
c 1
b 0
f 0
nc 11
nop 1
dl 0
loc 65
rs 6.9666

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
 * @author  Eddy <[email protected]>
4
 */
5
6
namespace App\Http\Controllers\Admin;
7
8
use App\Http\Controllers\Controller;
9
use App\Http\Requests\Admin\EntityFieldRequest;
10
use App\Model\Admin\Entity;
11
use App\Model\Admin\EntityField;
12
use App\Repository\Admin\EntityFieldRepository;
13
use App\Repository\Admin\EntityRepository;
14
use Illuminate\Database\Eloquent\ModelNotFoundException;
15
use Illuminate\Database\QueryException;
16
use Illuminate\Database\Schema\Blueprint;
17
use Illuminate\Http\Request;
18
use Illuminate\Support\Str;
19
use Illuminate\View\View;
20
use Illuminate\Support\Facades\Schema;
21
use Log;
22
23
class EntityFieldController extends Controller
24
{
25
    protected $formNames = [
26
        'name', 'type', 'comment', 'form_name', 'form_type', 'is_show', 'is_edit', 'is_required',
27
        'form_comment', 'entity_id', 'field_length', 'field_total', 'field_scale', 'order', 'form_params',
28
        'default_value'
29
    ];
30
31
    public function __construct()
32
    {
33
        parent::__construct();
34
35
        $this->breadcrumb[] = ['title' => '模型字段列表', 'url' => route('admin::entityField.index')];
36
    }
37
38
    /**
39
     * 模型字段管理-模型字段列表
40
     *
41
     */
42
    public function index()
43
    {
44
        $this->breadcrumb[] = ['title' => '模型字段列表', 'url' => ''];
45
        return view('admin.entityField.index', ['breadcrumb' => $this->breadcrumb]);
46
    }
47
48
    /**
49
     * 模型字段列表数据接口
50
     *
51
     * @param Request $request
52
     * @return array
53
     */
54
    public function list(Request $request)
55
    {
56
        $perPage = (int) $request->get('limit', 50);
57
        $condition = $request->only($this->formNames);
58
59
        $data = EntityFieldRepository::list($perPage, $condition);
60
61
        return $data;
62
    }
63
64
    /**
65
     * 模型字段管理-新增模型字段
66
     *
67
     */
68
    public function create()
69
    {
70
        $entity = Entity::query()->pluck('name', 'id')->all();
71
        $this->breadcrumb[] = ['title' => '新增模型字段', 'url' => ''];
72
        return view('admin.entityField.add', ['breadcrumb' => $this->breadcrumb, 'entity' => $entity]);
73
    }
74
75
    /**
76
     * 模型字段管理-保存模型字段
77
     *
78
     * @param EntityFieldRequest $request
79
     * @return array
80
     */
81
    public function save(EntityFieldRequest $request)
82
    {
83
        try {
84
            $data = $request->only($this->formNames);
85
            $table = EntityRepository::find($data['entity_id']);
86
            if (!$table) {
87
                return [
88
                    'code' => 1,
89
                    'msg' => '新增失败:模型不存在',
90
                ];
91
            }
92
            if (Schema::hasColumn($table->table_name, $data['name'])) {
93
                return [
94
                    'code' => 2,
95
                    'msg' => '新增失败:字段已存在',
96
                ];
97
            }
98
            if (!in_array($data['type'], config('light.db_table_field_type'))) {
99
                return [
100
                    'code' => 3,
101
                    'msg' => '新增失败:无效字段类型',
102
                ];
103
            }
104
105
            Schema::table($table->table_name, function (Blueprint $table) use ($data) {
106
                $m = $data['type'];
107
                $length = intval($data['field_length']);
108
                $total = intval($data['field_total']);
109
                $scale = intval($data['field_scale']);
110
                if (in_array($m, ['char', 'string'])) {
111
                    $table->$m($data['name'], $length > 0 ? $length : 255)
112
                        ->comment($data['comment'])
113
                        ->default(strval($data['default_value']));
114
                } elseif (Str::contains(Str::lower($m), 'integer')) {
115
                    $table->$m($data['name'])
116
                        ->comment($data['comment'])
117
                        ->default(intval($data['default_value']));
118
                } elseif (in_array($m, ['float', 'double', 'decimal', 'unsignedDecimal'])) {
119
                    if ($total > 0 && $scale > 0 && $total > $scale) {
120
                        $table->$m($data['name'], $total, $scale)
121
                            ->comment($data['comment'])
122
                            ->default(doubleval($data['default_value']));
123
                    } else {
124
                        $table->$m($data['name'])
125
                            ->comment($data['comment'])
126
                            ->default(doubleval($data['default_value']));
127
                    }
128
                } else {
129
                    $table->$m($data['name'])->comment($data['comment'])->nullable();
130
                }
131
            });
132
133
            unset($data['field_length'], $data['field_total'], $data['field_scale']);
134
            EntityFieldRepository::add($data);
135
136
            return [
137
                'code' => 0,
138
                'msg' => '新增成功',
139
                'redirect' => true
140
            ];
141
        } catch (\Exception $e) {
142
            \Log::error($e);
143
            return [
144
                'code' => 1,
145
                'msg' => '新增失败:' . $e->getMessage(),
146
            ];
147
        }
148
    }
149
150
    /**
151
     * 模型字段管理-编辑模型字段
152
     *
153
     * @param int $id
154
     * @return View
155
     */
156
    public function edit($id)
157
    {
158
        $this->breadcrumb[] = ['title' => '编辑模型字段', 'url' => ''];
159
160
        $model = EntityFieldRepository::find($id);
161
        $entity = Entity::query()->pluck('name', 'id')->all();
162
        return view('admin.entityField.add', [
163
            'id' => $id,
164
            'model' => $model,
165
            'breadcrumb' => $this->breadcrumb,
166
            'entity' => $entity
167
        ]);
168
    }
169
170
    /**
171
     * 模型字段管理-更新模型字段
172
     *
173
     * @param EntityFieldRequest $request
174
     * @param int $id
175
     * @return array
176
     */
177
    public function update(EntityFieldRequest $request, $id)
178
    {
179
        $data = $request->only($this->formNames);
180
        try {
181
            if (!isset($data['is_show'])) {
182
                $data['is_show'] = EntityField::SHOW_DISABLE;
183
            }
184
            if (!isset($data['is_edit'])) {
185
                $data['is_edit'] = EntityField::EDIT_DISABLE;
186
            }
187
            if (!isset($data['is_required'])) {
188
                $data['is_required'] = EntityField::REQUIRED_DISABLE;
189
            }
190
191
            unset($data['field_length'], $data['field_total'], $data['field_scale'], $data['entity_id']);
192
            EntityFieldRepository::update($id, $data);
193
            return [
194
                'code' => 0,
195
                'msg' => '编辑成功',
196
                'redirect' => true
197
            ];
198
        } catch (QueryException $e) {
199
            \Log::error($e);
200
            return [
201
                'code' => 1,
202
                'msg' => '编辑失败:' . (Str::contains($e->getMessage(), 'Duplicate entry') ? '当前模型字段已存在' : '其它错误'),
203
                'redirect' => false
204
            ];
205
        }
206
    }
207
208
    /**
209
     * 模型字段管理-删除模型字段
210
     *
211
     * @param int $id
212
     */
213
    public function delete($id)
214
    {
215
        try {
216
            $entityField = EntityField::query()->findOrFail($id);
217
            $entity = $entityField->entity;
218
            Schema::table($entity->table_name, function (Blueprint $table) use ($entityField) {
219
                $table->dropColumn($entityField->name);
220
            });
221
            EntityFieldRepository::delete($id);
222
            return [
223
                'code' => 0,
224
                'msg' => '删除成功',
225
                'redirect' => true
226
            ];
227
        } catch (ModelNotFoundException $e) {
228
            return [
229
                'code' => 2,
230
                'msg' => '删除失败:字段不存在',
231
                'redirect' => false
232
            ];
233
        } catch (\RuntimeException $e) {
234
            return [
235
                'code' => 1,
236
                'msg' => '删除失败:' . $e->getMessage(),
237
                'redirect' => false
238
            ];
239
        }
240
    }
241
}
242