AdminController.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace app\common\controller;
  3. use app\admin\service\ConfigService;
  4. use app\admin\traits\Curd;
  5. use app\BaseController;
  6. use app\common\constants\AdminConstant;
  7. use app\common\traits\JumpTrait;
  8. use think\facade\Db;
  9. use think\facade\View;
  10. use think\helper\Str;
  11. use think\response\Json;
  12. class AdminController extends BaseController
  13. {
  14. use Curd;
  15. use JumpTrait;
  16. /**
  17. * 当前模型
  18. * @Model
  19. * @var mixed
  20. */
  21. protected static mixed $model;
  22. /**
  23. * 字段排序
  24. * @var array
  25. */
  26. protected array $sort = [
  27. 'id' => 'desc',
  28. ];
  29. /**
  30. * 允许修改的字段
  31. * @var array
  32. */
  33. protected array $allowModifyFields = [
  34. 'status',
  35. 'sort',
  36. 'remark',
  37. 'is_delete',
  38. 'is_auth',
  39. 'title',
  40. ];
  41. /**
  42. * 过滤节点更新
  43. * @var array
  44. */
  45. protected array $ignoreNode = [];
  46. /**
  47. * 不导出的字段信息
  48. * @var array
  49. */
  50. protected array $noExportFields = ['delete_time', 'update_time'];
  51. /**
  52. * 下拉选择条件
  53. * @var array
  54. */
  55. protected array $selectWhere = [];
  56. /**
  57. * 是否关联查询
  58. * @var bool
  59. */
  60. protected bool $relationSearch = false;
  61. /**
  62. * 模板布局, false取消
  63. * @var string|bool
  64. */
  65. protected string|bool $layout = 'layout/default';
  66. /**
  67. * 是否为演示环境
  68. * @var bool
  69. */
  70. protected bool $isDemo = false;
  71. /**
  72. * @var int|string
  73. */
  74. protected int|string $adminUid;
  75. /**
  76. * 初始化方法
  77. */
  78. protected function initialize(): void
  79. {
  80. parent::initialize();
  81. $this->adminUid = request()->adminUserInfo['id'] ?? 0;
  82. $this->isDemo = env('EASYADMIN.IS_DEMO', false);
  83. $this->setOrder();
  84. $this->viewInit();
  85. }
  86. /**
  87. * 初始化排序
  88. * @return $this
  89. */
  90. public function setOrder(): static
  91. {
  92. $tableOrder = $this->request->param('tableOrder/s', '');
  93. if (!empty($tableOrder)) {
  94. [$orderField, $orderType] = explode(' ', $tableOrder);
  95. $this->sort = [$orderField => $orderType];
  96. }
  97. return $this;
  98. }
  99. /**
  100. * 模板变量赋值
  101. * @param array|string $name 模板变量
  102. * @param mixed|null $value 变量值
  103. */
  104. public function assign(array|string $name, mixed $value = null): void
  105. {
  106. View::assign($name, $value);
  107. }
  108. /**
  109. * 解析和获取模板内容 用于输出
  110. * @param string $template
  111. * @param array $vars
  112. * @param bool $layout 是否需要自动布局
  113. * @return string
  114. */
  115. public function fetch(string $template = '', array $vars = [], bool $layout = true): string
  116. {
  117. if ($layout) View::instance()->engine()->layout('/layout/default');
  118. View::assign($vars);
  119. return View::fetch($template);
  120. }
  121. /**
  122. * 重写验证规则
  123. * @param array $data
  124. * @param array|string $validate
  125. * @param array $message
  126. * @param bool $batch
  127. * @return bool
  128. */
  129. public function validate(array $data, $validate, array $message = [], bool $batch = false): bool
  130. {
  131. try {
  132. parent::validate($data, $validate, $message, $batch);
  133. }catch (\Exception $e) {
  134. $this->error($e->getMessage());
  135. }
  136. return true;
  137. }
  138. /**
  139. * 构建请求参数
  140. * @param array $excludeFields 忽略构建搜索的字段
  141. * @return array
  142. */
  143. protected function buildTableParams(array $excludeFields = []): array
  144. {
  145. $get = $this->request->get();
  146. $page = !empty($get['page']) ? $get['page'] : 1;
  147. $limit = !empty($get['limit']) ? $get['limit'] : 15;
  148. $filters = !empty($get['filter']) ? htmlspecialchars_decode($get['filter']) : '{}';
  149. $ops = !empty($get['op']) ? htmlspecialchars_decode($get['op']) : '{}';
  150. // json转数组
  151. $filters = json_decode($filters, true);
  152. $ops = json_decode($ops, true);
  153. $where = [];
  154. $excludes = [];
  155. // 判断是否关联查询
  156. $tableName = Str::snake(lcfirst((new self::$model)->getName()));
  157. foreach ($filters as $key => $val) {
  158. if (in_array($key, $excludeFields)) {
  159. $excludes[$key] = $val;
  160. continue;
  161. }
  162. $op = !empty($ops[$key]) ? $ops[$key] : '%*%';
  163. if ($this->relationSearch && count(explode('.', $key)) == 1) {
  164. $key = "{$tableName}.{$key}";
  165. }
  166. switch (strtolower($op)) {
  167. case '=':
  168. $where[] = [$key, '=', $val];
  169. break;
  170. case '%*%':
  171. $where[] = [$key, 'LIKE', "%{$val}%"];
  172. break;
  173. case '*%':
  174. $where[] = [$key, 'LIKE', "{$val}%"];
  175. break;
  176. case '%*':
  177. $where[] = [$key, 'LIKE', "%{$val}"];
  178. break;
  179. case 'in':
  180. $where[] = [$key, 'IN', $val];
  181. break;
  182. case 'find_in_set':
  183. $where[] = ['', 'exp', Db::raw("FIND_IN_SET(:param,$key)", ['param' => $val])];
  184. break;
  185. case 'range':
  186. [$beginTime, $endTime] = explode(' - ', $val);
  187. $where[] = [$key, '>=', strtotime($beginTime)];
  188. $where[] = [$key, '<=', strtotime($endTime)];
  189. break;
  190. case 'datetime':
  191. [$beginTime, $endTime] = explode(' - ', $val);
  192. $where[] = [$key, '>=', $beginTime];
  193. $where[] = [$key, '<=', $endTime];
  194. break;
  195. default:
  196. $where[] = [$key, $op, "%{$val}"];
  197. }
  198. }
  199. return [(int)$page, (int)$limit, $where, $excludes];
  200. }
  201. /**
  202. * 下拉选择列表
  203. * @return Json
  204. */
  205. public function selectList(): Json
  206. {
  207. $fields = input('selectFields');
  208. $data = self::$model::where($this->selectWhere)->field($fields)->select()->toArray();
  209. $this->success(null, $data);
  210. }
  211. /**
  212. * 初始化视图参数
  213. */
  214. private function viewInit(): void
  215. {
  216. $request = app()->request;
  217. list($thisModule, $thisController, $thisAction) = [app('http')->getName(), app()->request->controller(), $request->action()];
  218. list($thisControllerArr, $jsPath) = [explode('.', $thisController), null];
  219. foreach ($thisControllerArr as $vo) {
  220. empty($jsPath) ? $jsPath = parse_name($vo) : $jsPath .= '/' . parse_name($vo);
  221. }
  222. $autoloadJs = file_exists(root_path('public') . "static/{$thisModule}/js/{$jsPath}.js");
  223. $thisControllerJsPath = "{$thisModule}/js/{$jsPath}.js";
  224. $adminModuleName = config('admin.alias_name');
  225. $isSuperAdmin = $this->adminUid == AdminConstant::SUPER_ADMIN_ID;
  226. $data = [
  227. 'isDemo' => $this->isDemo,
  228. 'adminModuleName' => $adminModuleName,
  229. 'thisController' => parse_name($thisController),
  230. 'thisAction' => $thisAction,
  231. 'thisRequest' => parse_name("{$thisModule}/{$thisController}/{$thisAction}"),
  232. 'thisControllerJsPath' => "{$thisControllerJsPath}",
  233. 'autoloadJs' => $autoloadJs,
  234. 'isSuperAdmin' => $isSuperAdmin,
  235. 'version' => env('APP_DEBUG') ? time() : ConfigService::getVersion(),
  236. 'adminUploadUrl' => url('ajax/upload', [], false),
  237. 'adminEditor' => sysConfig('site', 'editor_type') ?: 'wangEditor',
  238. 'maxFileSize' => sysConfig('upload', 'upload_allow_size'),
  239. 'iframeOpenTop' => sysConfig('site', 'iframe_open_top') ?: 0,
  240. ];
  241. View::assign($data);
  242. }
  243. /**
  244. * 严格校验接口是否为POST请求
  245. */
  246. protected function checkPostRequest(): void
  247. {
  248. if (!$this->request->isPost()) {
  249. $this->error("当前请求不合法!");
  250. }
  251. }
  252. }