Curd.php 17 KB

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