Curd.php 15 KB

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