Curd.php 17 KB

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