Curd.php 17 KB

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