Curd.php 14 KB

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