Passed
Push — master ( 51b555...6b609b )
by Jianhua
13:56
created

EntityRepository::list()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 21
nc 1
nop 2
dl 0
loc 25
rs 9.584
c 1
b 0
f 0
1
<?php
2
/**
3
 * @author  Eddy <[email protected]>
4
 */
5
6
namespace App\Repository\Admin;
7
8
use App\Model\Admin\Category;
9
use App\Model\Admin\Comment;
10
use App\Model\Admin\CommentOperateLog;
11
use App\Model\Admin\ContentTag;
12
use App\Model\Admin\Entity;
13
use App\Model\Admin\EntityField;
14
use App\Repository\Searchable;
15
use Illuminate\Database\Schema\Blueprint;
16
use Illuminate\Support\Facades\DB;
17
use Illuminate\Support\Facades\Schema;
18
use App\Exceptions\CreateTableException;
19
use App\Model\Admin\Menu;
20
21
class EntityRepository
22
{
23
    use Searchable;
24
25
    public static function list($perPage, $condition = [])
26
    {
27
        $data = Entity::query()
28
            ->where(function ($query) use ($condition) {
29
                Searchable::buildQuery($query, $condition);
30
            })
31
            ->orderBy('id', 'desc')
32
            ->paginate($perPage);
33
        $data->transform(function ($item) {
34
            xssFilter($item);
35
            $item->editUrl = route('admin::entity.edit', ['id' => $item->id]);
36
            $item->deleteUrl = route('admin::entity.delete', ['id' => $item->id]);
37
            $item->copyUrl = route('admin::entity.copy', ['id' => $item->id]);
38
            $item->menuUrl = route('admin::entity.menu', ['id' => $item->id]);
39
            $item->fieldUrl = route('admin::entityField.index') . '?entity_id=' . $item->id;
40
            $item->contentUrl = route('admin::content.index', ['entity' => $item->id]);
41
            $item->commentListUrl = route('admin::comment.index', ['entity_id' => $item->id]);
42
            return $item;
43
        });
44
45
        return [
46
            'code' => 0,
47
            'msg' => '',
48
            'count' => $data->total(),
49
            'data' => $data->items(),
50
        ];
51
    }
52
53
    /**
54
     * 新增模型
55
     *
56
     * @param array $data
57
     * @param mixed $createDB
58
     * @throws CreateTableException|\Exception
59
     * @return Entity
60
     */
61
    public static function add($data, $createDB = true)
62
    {
63
        $entity = Entity::query()->create($data);
64
        try {
65
            if (!$createDB) {
66
                return $entity;
67
            }
68
69
            if (Schema::hasTable($data['table_name'])) {
70
                throw new \RuntimeException("数据库表已存在");
71
            }
72
73
            Schema::create($data['table_name'], function (Blueprint $table) {
74
                $table->increments('id');
75
                $table->timestamps();
76
                $table->engine = 'InnoDB';
77
            });
78
79
            return $entity;
80
        } catch (\Exception $e) {
81
            $entity->delete();
82
            throw new CreateTableException("创建数据库表异常");
83
        }
84
    }
85
86
    public static function copy($tableName, $id)
87
    {
88
        $entity = Entity::findOrFail($id);
89
        if (Schema::hasTable($tableName)) {
90
            throw new \RuntimeException("数据库表已存在");
91
        }
92
93
        try {
94
            // 仅在 Mysql 下测试通过,不支持 Sqlite
95
            DB::statement("CREATE TABLE {$tableName} LIKE {$entity->table_name}");
96
97
            DB::beginTransaction();
98
99
            $newEntity = $entity->replicate();
100
            $newEntity->table_name = $tableName;
101
            $newEntity->name .= '_copy';
102
            $newEntity->save();
103
104
            EntityField::where('entity_id', $id)->get()->each(function ($item) use ($newEntity) {
105
                $m = $item->replicate();
106
                $m->entity_id = $newEntity->id;
107
                $m->save();
108
            });
109
110
            DB::commit();
111
        } catch (\Exception $e) {
112
            Schema::dropIfExists($tableName);
113
            throw $e;
114
        }
115
    }
116
117
    public static function update($id, $data)
118
    {
119
        return Entity::query()->where('id', $id)->update($data);
120
    }
121
122
    public static function find($id)
123
    {
124
        return Entity::query()->find($id);
125
    }
126
127
    public static function external($id)
128
    {
129
        return Entity::query()->External()->find($id);
130
    }
131
132
    public static function all()
133
    {
134
        return Entity::query()->get();
135
    }
136
137
    public static function systemMenu()
138
    {
139
        $entities = Entity::query()->where('is_show_content_manage', Entity::CONTENT_MANAGE_YES)
140
            ->pluck('name', 'id')->all();
141
        $autoMenu = [];
142
        foreach ($entities as $k => $v) {
143
            $autoMenu[] = [
144
                'url' => route('admin::content.index', ['entity' => $k]),
145
                'name' => $v,
146
                'id' => $k,
147
            ];
148
        }
149
150
        return $autoMenu;
151
    }
152
153
    public static function delete($id)
154
    {
155
        $table = Entity::query()->findOrFail($id);
156
        DB::beginTransaction();
157
158
        Schema::dropIfExists($table->table_name);
159
        Entity::destroy($id);
160
        EntityField::query()->where('entity_id', $id)->delete();
161
        Category::query()->where('model_id', $id)->delete();
162
        ContentTag::query()->where('entity_id', $id)->delete();
163
        CommentOperateLog::query()->join('comments', 'comment_operate_logs.comment_id', '=', 'comments.id')
164
            ->where('entity_id', $id)
165
            ->delete();
166
        Comment::query()->where('entity_id', $id)->delete();
167
168
        DB::commit();
169
    }
170
171
    public static function addDefaultMenus(Entity $entity)
172
    {
173
        $params = "entity:{$entity->id}";
174
        $menus = [
175
            '更新内容' => 'admin::content.update',
176
            '保存内容' => 'admin::content.save',
177
            '内容列表数据接口' => 'admin::content.list',
178
            '内容列表' => 'admin::content.index',
179
            '编辑内容' => 'admin::content.edit',
180
            '删除内容' => 'admin::content.delete',
181
            '新增内容' => 'admin::content.create',
182
            '内容批量操作' => 'admin::content.batch',
183
        ];
184
        DB::beginTransaction();
185
        foreach ($menus as $k => $v) {
186
            $data = [
187
                'name' => $entity->name . $k,
188
                'route' => $v,
189
                'route_params' => $params,
190
                'group' => $entity->name . '内容管理',
191
                'pid' => 107,
192
                'is_lock_name' => 1,
193
                'status' => 0,
194
            ];
195
196
            $menu = Menu::select('id')
197
                ->where('name', $data['name'])
198
                ->orWhere(function ($query) use ($data) {
199
                    $query->where('route', $data['route'])
200
                        ->where('route_params', $data['route_params']);
201
                })
202
                ->lockForUpdate()
203
                ->first();
204
            if ($menu) {
205
                continue;
206
            }
207
            Menu::create($data);
208
        }
209
        DB::commit();
210
    }
211
}
212