Curd.php 16 KB

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