Curd.php 16 KB

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