Crud.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. namespace plugin\admin\app\controller;
  3. use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
  4. use Illuminate\Database\Query\Builder as QueryBuilder;
  5. use plugin\admin\app\common\Auth;
  6. use plugin\admin\app\common\Tree;
  7. use plugin\admin\app\common\Util;
  8. use support\exception\BusinessException;
  9. use support\Model;
  10. use support\Request;
  11. use support\Response;
  12. class Crud extends Base
  13. {
  14. /**
  15. * @var Model
  16. */
  17. protected $model = null;
  18. /**
  19. * 查询
  20. * @param Request $request
  21. * @return Response
  22. * @throws BusinessException
  23. */
  24. public function select(Request $request): Response
  25. {
  26. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  27. $query = $this->doSelect($where, $field, $order);
  28. return $this->doFormat($query, $format, $limit);
  29. }
  30. /**
  31. * 添加
  32. * @param Request $request
  33. * @return Response
  34. * @throws BusinessException
  35. */
  36. public function insert(Request $request): Response
  37. {
  38. $data = $this->insertInput($request);
  39. $id = $this->doInsert($data);
  40. return $this->json(0, 'ok', ['id' => $id]);
  41. }
  42. /**
  43. * 更新
  44. * @param Request $request
  45. * @return Response
  46. * @throws BusinessException
  47. */
  48. public function update(Request $request): Response
  49. {
  50. [$id, $data] = $this->updateInput($request);
  51. $this->doUpdate($id, $data);
  52. return $this->json(0);
  53. }
  54. /**
  55. * 删除
  56. * @param Request $request
  57. * @return Response
  58. * @throws BusinessException
  59. */
  60. public function delete(Request $request): Response
  61. {
  62. $ids = $this->deleteInput($request);
  63. $this->doDelete($ids);
  64. return $this->json(0);
  65. }
  66. /**
  67. * 查询前置
  68. * @param Request $request
  69. * @return array
  70. * @throws BusinessException
  71. */
  72. protected function selectInput(Request $request): array
  73. {
  74. $field = $request->get('field');
  75. $order = $request->get('order', 'asc');
  76. $format = $request->get('format', 'normal');
  77. $limit = (int)$request->get('limit', $format === 'tree' ? 1000 : 10);
  78. $limit = $limit <= 0 ? 10 : $limit;
  79. $order = $order === 'asc' ? 'asc' : 'desc';
  80. $where = $request->get();
  81. $page = (int)$request->get('page');
  82. $page = $page > 0 ? $page : 1;
  83. $table = config('plugin.admin.database.connections.mysql.prefix') . $this->model->getTable();
  84. $allow_column = Util::db()->select("desc `$table`");
  85. if (!$allow_column) {
  86. throw new BusinessException('表不存在');
  87. }
  88. $allow_column = array_column($allow_column, 'Field', 'Field');
  89. if (!in_array($field, $allow_column)) {
  90. $field = null;
  91. }
  92. foreach ($where as $column => $value) {
  93. if (
  94. $value === '' || !isset($allow_column[$column]) ||
  95. is_array($value) && (empty($value) || !in_array($value[0], ['null', 'not null']) && !isset($value[1]))
  96. ) {
  97. unset($where[$column]);
  98. }
  99. }
  100. // 按照数据限制字段返回数据
  101. if (!Auth::isSuperAdmin()) {
  102. if ($this->dataLimit === 'personal') {
  103. $where[$this->dataLimitField] = admin_id();
  104. } elseif ($this->dataLimit === 'auth') {
  105. $primary_key = $this->model->getKeyName();
  106. if (!Auth::isSuperAdmin() && (!isset($where[$primary_key]) || $this->dataLimitField != $primary_key)) {
  107. $where[$this->dataLimitField] = ['in', Auth::getScopeAdminIds(true)];
  108. }
  109. }
  110. }
  111. return [$where, $format, $limit, $field, $order, $page];
  112. }
  113. /**
  114. * 指定查询where条件,并没有真正的查询数据库操作
  115. * @param array $where
  116. * @param string|null $field
  117. * @param string $order
  118. * @return EloquentBuilder|QueryBuilder|Model
  119. */
  120. protected function doSelect(array $where, string $field = null, string $order= 'desc')
  121. {
  122. $model = $this->model;
  123. foreach ($where as $column => $value) {
  124. if (is_array($value)) {
  125. if ($value[0] === 'like' || $value[0] === 'not like') {
  126. $model = $model->where($column, $value[0], "%$value[1]%");
  127. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  128. $model = $model->where($column, $value[0], $value[1]);
  129. } elseif ($value[0] == 'in' && !empty($value[1])) {
  130. $valArr = $value[1];
  131. if (is_string($value[1])) {
  132. $valArr = explode(",", trim($value[1]));
  133. }
  134. $model = $model->whereIn($column, $valArr);
  135. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  136. $valArr = $value[1];
  137. if (is_string($value[1])) {
  138. $valArr = explode(",", trim($value[1]));
  139. }
  140. $model = $model->whereNotIn($column, $valArr);
  141. }elseif ($value[0] == 'null') {
  142. $model = $model->whereNull($column);
  143. } elseif ($value[0] == 'not null') {
  144. $model = $model->whereNotNull($column);
  145. } elseif ($value[0] !== '' || $value[1] !== '') {
  146. $model = $model->whereBetween($column, $value);
  147. }
  148. } else {
  149. $model = $model->where($column, $value);
  150. }
  151. }
  152. if ($field) {
  153. $model = $model->orderBy($field, $order);
  154. }
  155. return $model;
  156. }
  157. /**
  158. * 执行真正查询,并返回格式化数据
  159. * @param $query
  160. * @param $format
  161. * @param $limit
  162. * @return Response
  163. */
  164. protected function doFormat($query, $format, $limit): Response
  165. {
  166. $methods = [
  167. 'select' => 'formatSelect',
  168. 'tree' => 'formatTree',
  169. 'table_tree' => 'formatTableTree',
  170. 'normal' => 'formatNormal',
  171. ];
  172. $paginator = $query->paginate($limit);
  173. $total = $paginator->total();
  174. $items = $paginator->items();
  175. if (method_exists($this, "afterQuery")) {
  176. $items = call_user_func([$this, "afterQuery"], $items);
  177. }
  178. $format_function = $methods[$format] ?? 'formatNormal';
  179. return call_user_func([$this, $format_function], $items, $total);
  180. }
  181. /**
  182. * 插入前置方法
  183. * @param Request $request
  184. * @return array
  185. * @throws BusinessException
  186. */
  187. protected function insertInput(Request $request): array
  188. {
  189. $data = $this->inputFilter($request->post());
  190. $password_filed = 'password';
  191. if (isset($data[$password_filed])) {
  192. $data[$password_filed] = Util::passwordHash($data[$password_filed]);
  193. }
  194. if (!Auth::isSuperAdmin()) {
  195. if ($this->dataLimit === 'personal') {
  196. $data[$this->dataLimitField] = admin_id();
  197. } elseif ($this->dataLimit === 'auth') {
  198. if (!empty($data[$this->dataLimitField])) {
  199. $admin_id = $data[$this->dataLimitField];
  200. if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
  201. throw new BusinessException('无数据权限');
  202. }
  203. } else {
  204. $data[$this->dataLimitField] = admin_id();
  205. }
  206. }
  207. } elseif ($this->dataLimit && empty($data[$this->dataLimitField])) {
  208. $data[$this->dataLimitField] = admin_id();
  209. }
  210. return $data;
  211. }
  212. /**
  213. * 执行插入
  214. * @param array $data
  215. * @return mixed|null
  216. */
  217. protected function doInsert(array $data)
  218. {
  219. $primary_key = $this->model->getKeyName();
  220. $model_class = get_class($this->model);
  221. $model = new $model_class;
  222. foreach ($data as $key => $val) {
  223. $model->{$key} = $val;
  224. }
  225. $model->save();
  226. return $primary_key ? $model->$primary_key : null;
  227. }
  228. /**
  229. * 更新前置方法
  230. * @param Request $request
  231. * @return array
  232. * @throws BusinessException
  233. */
  234. protected function updateInput(Request $request): array
  235. {
  236. $primary_key = $this->model->getKeyName();
  237. $id = $request->post($primary_key);
  238. $data = $this->inputFilter($request->post());
  239. $model = $this->model->find($id);
  240. if (!$model) {
  241. throw new BusinessException('记录不存在', 2);
  242. }
  243. if (!Auth::isSuperAdmin()) {
  244. if ($this->dataLimit == 'personal') {
  245. if ($model->{$this->dataLimitField} != admin_id()) {
  246. throw new BusinessException('无数据权限');
  247. }
  248. } elseif ($this->dataLimit == 'auth') {
  249. $scopeAdminIds = Auth::getScopeAdminIds(true);
  250. $admin_ids = [
  251. $data[$this->dataLimitField] ?? false, // 检查要更新的数据admin_id是否是有权限的值
  252. $model->{$this->dataLimitField} ?? false // 检查要更新的记录的admin_id是否有权限
  253. ];
  254. foreach ($admin_ids as $admin_id) {
  255. if ($admin_id && !in_array($admin_id, $scopeAdminIds)) {
  256. throw new BusinessException('无数据权限');
  257. }
  258. }
  259. }
  260. }
  261. $password_filed = 'password';
  262. if (isset($data[$password_filed])) {
  263. // 密码为空,则不更新密码
  264. if ($data[$password_filed] === '') {
  265. unset($data[$password_filed]);
  266. } else {
  267. $data[$password_filed] = Util::passwordHash($data[$password_filed]);
  268. }
  269. }
  270. unset($data[$primary_key]);
  271. return [$id, $data];
  272. }
  273. /**
  274. * 执行更新
  275. * @param $id
  276. * @param $data
  277. * @return void
  278. */
  279. protected function doUpdate($id, $data)
  280. {
  281. $model = $this->model->find($id);
  282. foreach ($data as $key => $val) {
  283. $model->{$key} = $val;
  284. }
  285. $model->save();
  286. }
  287. /**
  288. * 对用户输入表单过滤
  289. * @param array $data
  290. * @return array
  291. * @throws BusinessException
  292. */
  293. protected function inputFilter(array $data): array
  294. {
  295. $table = config('plugin.admin.database.connections.mysql.prefix') . $this->model->getTable();
  296. $allow_column = $this->model->getConnection()->select("desc `$table`");
  297. if (!$allow_column) {
  298. throw new BusinessException('表不存在', 2);
  299. }
  300. $columns = array_column($allow_column, 'Type', 'Field');
  301. foreach ($data as $col => $item) {
  302. if (!isset($columns[$col])) {
  303. unset($data[$col]);
  304. continue;
  305. }
  306. // 非字符串类型传空则为null
  307. if ($item === '' && strpos(strtolower($columns[$col]), 'varchar') === false && strpos(strtolower($columns[$col]), 'text') === false) {
  308. $data[$col] = null;
  309. }
  310. if (is_array($item)) {
  311. $data[$col] = implode(',', $item);
  312. }
  313. }
  314. if (empty($data['created_at'])) {
  315. unset($data['created_at']);
  316. }
  317. if (empty($data['updated_at'])) {
  318. unset($data['updated_at']);
  319. }
  320. return $data;
  321. }
  322. /**
  323. * 删除前置方法
  324. * @param Request $request
  325. * @return array
  326. * @throws BusinessException
  327. */
  328. protected function deleteInput(Request $request): array
  329. {
  330. $primary_key = $this->model->getKeyName();
  331. if (!$primary_key) {
  332. throw new BusinessException('该表无主键,不支持删除');
  333. }
  334. $ids = (array)$request->post($primary_key, []);
  335. if (!Auth::isSuperAdmin()){
  336. if ($this->dataLimit) {
  337. $admin_ids = $this->model->where($primary_key, $ids)->pluck($this->dataLimitField)->toArray();
  338. }
  339. if ($this->dataLimit == 'personal') {
  340. if (!in_array(admin_id(), $admin_ids)) {
  341. throw new BusinessException('无数据权限');
  342. }
  343. } elseif ($this->dataLimit == 'auth') {
  344. if (array_diff($admin_ids, Auth::getScopeAdminIds(true))) {
  345. throw new BusinessException('无数据权限');
  346. }
  347. }
  348. }
  349. return $ids;
  350. }
  351. /**
  352. * 执行删除
  353. * @param array $ids
  354. * @return void
  355. */
  356. protected function doDelete(array $ids)
  357. {
  358. if (!$ids) {
  359. return;
  360. }
  361. $primary_key = $this->model->getKeyName();
  362. $this->model->whereIn($primary_key, $ids)->each(function ($model) {
  363. $model->delete();
  364. });
  365. }
  366. /**
  367. * 格式化树
  368. * @param $items
  369. * @return Response
  370. */
  371. protected function formatTree($items): Response
  372. {
  373. $format_items = [];
  374. foreach ($items as $item) {
  375. $format_items[] = [
  376. 'name' => $item->title ?? $item->name ?? $item->id,
  377. 'value' => (string)$item->id,
  378. 'id' => $item->id,
  379. 'pid' => $item->pid,
  380. ];
  381. }
  382. $tree = new Tree($format_items);
  383. return $this->json(0, 'ok', $tree->getTree());
  384. }
  385. /**
  386. * 格式化表格树
  387. * @param $items
  388. * @return Response
  389. */
  390. protected function formatTableTree($items): Response
  391. {
  392. $tree = new Tree($items);
  393. return $this->json(0, 'ok', $tree->getTree());
  394. }
  395. /**
  396. * 格式化下拉列表
  397. * @param $items
  398. * @return Response
  399. */
  400. protected function formatSelect($items): Response
  401. {
  402. $formatted_items = [];
  403. foreach ($items as $item) {
  404. $formatted_items[] = [
  405. 'name' => $item->title ?? $item->name ?? $item->id,
  406. 'value' => $item->id
  407. ];
  408. }
  409. return $this->json(0, 'ok', $formatted_items);
  410. }
  411. /**
  412. * 通用格式化
  413. * @param $items
  414. * @param $total
  415. * @return Response
  416. */
  417. protected function formatNormal($items, $total): Response
  418. {
  419. return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
  420. }
  421. /**
  422. * 查询数据库后置方法,可用于修改数据
  423. * @param mixed $items 原数据
  424. * @return mixed 修改后数据
  425. */
  426. protected function afterQuery($items)
  427. {
  428. return $items;
  429. }
  430. }