Curd.php 16 KB

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