Passed
Push — master ( b44092...ffe137 )
by Jianhua
08:35
created

ContentController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
rs 10
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\ContentRequest;
10
use App\Model\Admin\Content;
11
use App\Model\Admin\Entity;
12
use App\Model\Admin\EntityField;
13
use App\Repository\Admin\ContentRepository;
14
use App\Repository\Admin\EntityFieldRepository;
15
use App\Repository\Admin\EntityRepository;
16
use Illuminate\Database\QueryException;
17
use Illuminate\Http\Request;
18
use Illuminate\Support\Str;
19
use Illuminate\View\View;
20
21
class ContentController extends Controller
22
{
23
    protected $formNames = [];
24
25
    protected $entity = null;
26
27
    public function __construct()
28
    {
29
        parent::__construct();
30
        $entity = request()->route()->parameter('entity');
31
        $this->entity = Entity::query()->findOrFail($entity);
32
        ContentRepository::setTable($this->entity->table_name);
33
        $this->breadcrumb[] = ['title' => '内容列表', 'url' => route('admin::content.index', ['entity' => $entity])];
34
    }
35
36
    /**
37
     * 内容管理-内容列表
38
     *
39
     */
40
    public function index($entity)
41
    {
42
        $this->breadcrumb[] = ['title' => $this->entity->name . '内容列表', 'url' => ''];
43
        Content::$listField = [
44
            'title' => '标题'
45
        ];
46
        return view('admin.content.index', [
47
            'breadcrumb' => $this->breadcrumb,
48
            'entity' => $entity,
49
            'entityModel' => $this->entity,
50
            'autoMenu' => EntityRepository::systemMenu()
51
        ]);
52
    }
53
54
    /**
55
     * 内容列表数据接口
56
     *
57
     * @param Request $request
58
     * @return array
59
     */
60
    public function list(Request $request, $entity)
61
    {
62
        $perPage = (int) $request->get('limit', 50);
63
        $condition = $request->only($this->formNames);
64
65
        $data = ContentRepository::list($entity, $perPage, $condition);
66
67
        return $data;
68
    }
69
70
    /**
71
     * 内容管理-新增内容
72
     *
73
     */
74
    public function create($entity)
75
    {
76
        $this->breadcrumb[] = ['title' => "新增{$this->entity->name}内容", 'url' => ''];
77
        $view = $this->getAddOrEditViewPath();
78
79
        return view($view, [
80
            'breadcrumb' => $this->breadcrumb,
81
            'entity' => $entity,
82
            'entityModel' => $this->entity,
83
            'entityFields' => EntityFieldRepository::getByEntityId($entity),
84
            'autoMenu' => EntityRepository::systemMenu()
85
        ]);
86
    }
87
88
    /**
89
     * 内容管理-保存内容
90
     *
91
     * @param ContentRequest $request
92
     * @return array
93
     */
94
    public function save(ContentRequest $request, $entity)
95
    {
96
        $this->validateEntityRequest();
97
        $this->useUserDefinedSaveHandler($request, $entity);
98
        try {
99
            ContentRepository::add($request->only(
100
                EntityFieldRepository::getByEntityId($entity)->pluck('name')->toArray()
101
            ));
102
            return [
103
                'code' => 0,
104
                'msg' => '新增成功',
105
                'redirect' => true
106
            ];
107
        } catch (QueryException $e) {
108
            \Log::error($e);
109
            return [
110
                'code' => 1,
111
                'msg' => '新增失败:' . (Str::contains($e->getMessage(), 'Duplicate entry') ? '当前内容已存在' : '其它错误'),
112
                'redirect' => false
113
            ];
114
        }
115
    }
116
117
    /**
118
     * 内容管理-编辑内容
119
     *
120
     * @param int $id
121
     * @return View
122
     */
123
    public function edit($entity, $id)
124
    {
125
        $this->breadcrumb[] = ['title' => "编辑{$this->entity->name}内容", 'url' => ''];
126
        $view = $this->getAddOrEditViewPath();
127
        $model = ContentRepository::find($id);
128
129
        return view($view, [
130
            'id' => $id,
131
            'model' => $model,
132
            'breadcrumb' => $this->breadcrumb,
133
            'entity' => $entity,
134
            'entityModel' => $this->entity,
135
            'entityFields' => EntityFieldRepository::getByEntityId($entity),
136
            'autoMenu' => EntityRepository::systemMenu()
137
        ]);
138
    }
139
140
    /**
141
     * 内容管理-更新内容
142
     *
143
     * @param ContentRequest $request
144
     * @param int $id
145
     * @return array
146
     */
147
    public function update(ContentRequest $request, $entity, $id)
148
    {
149
        $this->validateEntityRequest();
150
        $this->useUserDefinedUpdateHandler($request, $entity, $id);
151
152
        $fieldInfo = EntityFieldRepository::getByEntityId($entity)
153
                        ->where('is_edit', EntityField::EDIT_ENABLE)
154
                        ->pluck('form_type', 'name')
155
                        ->toArray();
156
        $data = [];
157
        foreach ($fieldInfo as $k => $v) {
158
            if ($v === 'checkbox') {
159
                $data[$k] = '';
160
            }
161
        }
162
        $data = array_merge($data, $request->only(array_keys($fieldInfo)));
163
164
        try {
165
            ContentRepository::update($id, $data);
166
            return [
167
                'code' => 0,
168
                'msg' => '编辑成功',
169
                'redirect' => true
170
            ];
171
        } catch (QueryException $e) {
172
            \Log::error($e);
173
            return [
174
                'code' => 1,
175
                'msg' => '编辑失败:' . (Str::contains($e->getMessage(), 'Duplicate entry') ? '当前内容已存在' : '其它错误'),
176
                'redirect' => false
177
            ];
178
        }
179
    }
180
181
    /**
182
     * 内容管理-删除内容
183
     *
184
     * @param int $id
185
     */
186
    public function delete($entity, $id)
187
    {
188
        try {
189
            ContentRepository::delete($id);
190
            return [
191
                'code' => 0,
192
                'msg' => '删除成功',
193
                'redirect' => route('admin::content.index')
194
            ];
195
        } catch (\RuntimeException $e) {
196
            return [
197
                'code' => 1,
198
                'msg' => '删除失败:' . $e->getMessage(),
199
                'redirect' => route('admin::content.index')
200
            ];
201
        }
202
    }
203
204
    protected function validateEntityRequest()
205
    {
206
        $entityRequestClass = '\\App\\Http\\Requests\\Admin\\Entity\\' .
207
            Str::ucfirst(Str::singular($this->entity->table_name)) . 'Request';
208
        if (class_exists($entityRequestClass)) {
209
            $entityRequestClass::capture()->setContainer(app())->setRedirector(app()->make('redirect'))->validate();
210
        }
211
    }
212
213
    protected function useUserDefinedSaveHandler($request, $entity)
214
    {
215
        $entityControllerClass = '\\App\\Http\\Controllers\\Admin\\Entity\\' .
216
            Str::ucfirst(Str::singular($this->entity->table_name)) . 'Controller';
217
        if (class_exists($entityControllerClass) && method_exists($entityControllerClass, 'save')) {
218
            return call_user_func("{$entityControllerClass}::save", $request, $entity);
219
        }
220
    }
221
222
    protected function useUserDefinedUpdateHandler($request, $entity, $id)
223
    {
224
        $entityControllerClass = '\\App\\Http\\Controllers\\Admin\\Entity\\' .
225
            Str::ucfirst(Str::singular($this->entity->table_name)) . 'Controller';
226
        if (class_exists($entityControllerClass) && method_exists($entityControllerClass, 'update')) {
227
            return call_user_func("{$entityControllerClass}::update", $request, $entity, $id);
228
        }
229
    }
230
231
    protected function getAddOrEditViewPath()
232
    {
233
        $view = 'admin.content.add';
234
        // 自定义模板
235
        $modelName = Str::singular($this->entity->table_name);
236
        $path = resource_path('views/admin/content/' . $modelName . '_add.blade.php');
237
        if (file_exists($path)) {
238
            $view = 'admin.content.' . $modelName . '_add';
239
        }
240
241
        return $view;
242
    }
243
}
244