Curd.php 17 KB

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