Curd.php 16 KB

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