Curd.php 17 KB

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