Admin.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Contracts\ExceptionHandler;
  5. use Dcat\Admin\Contracts\Repository;
  6. use Dcat\Admin\Exception\InvalidArgumentException;
  7. use Dcat\Admin\Http\Controllers\AuthController;
  8. use Dcat\Admin\Http\JsonResponse;
  9. use Dcat\Admin\Layout\Menu;
  10. use Dcat\Admin\Layout\Navbar;
  11. use Dcat\Admin\Layout\SectionManager;
  12. use Dcat\Admin\Repositories\EloquentRepository;
  13. use Dcat\Admin\Support\Composer;
  14. use Dcat\Admin\Traits\HasAssets;
  15. use Dcat\Admin\Traits\HasHtml;
  16. use Dcat\Admin\Traits\HasPermissions;
  17. use Illuminate\Auth\GuardHelpers;
  18. use Illuminate\Contracts\Auth\Authenticatable;
  19. use Illuminate\Database\Eloquent\Builder;
  20. use Illuminate\Database\Eloquent\Model;
  21. use Illuminate\Http\Exceptions\HttpResponseException;
  22. use Illuminate\Support\Facades\Auth;
  23. use Illuminate\Support\Facades\Event;
  24. use Symfony\Component\HttpFoundation\Response;
  25. class Admin
  26. {
  27. use HasAssets;
  28. use HasHtml;
  29. const VERSION = '2.0.23-beta';
  30. const SECTION = [
  31. // 往 <head> 标签内输入内容
  32. 'HEAD' => 'ADMIN_HEAD',
  33. // 往body标签内部输入内容
  34. 'BODY_INNER_BEFORE' => 'ADMIN_BODY_INNER_BEFORE',
  35. 'BODY_INNER_AFTER' => 'ADMIN_BODY_INNER_AFTER',
  36. // 往#app内部输入内容
  37. 'APP_INNER_BEFORE' => 'ADMIN_APP_INNER_BEFORE',
  38. 'APP_INNER_AFTER' => 'ADMIN_APP_INNER_AFTER',
  39. // 顶部导航栏用户面板
  40. 'NAVBAR_USER_PANEL' => 'ADMIN_NAVBAR_USER_PANEL',
  41. 'NAVBAR_AFTER_USER_PANEL' => 'ADMIN_NAVBAR_AFTER_USER_PANEL',
  42. // 顶部导航栏之前
  43. 'NAVBAR_BEFORE' => 'ADMIN_NAVBAR_BEFORE',
  44. // 顶部导航栏底下
  45. 'NAVBAR_AFTER' => 'ADMIN_NAVBAR_AFTER',
  46. // 侧边栏顶部用户信息面板
  47. 'LEFT_SIDEBAR_USER_PANEL' => 'ADMIN_LEFT_SIDEBAR_USER_PANEL',
  48. // 菜单栏
  49. 'LEFT_SIDEBAR_MENU' => 'ADMIN_LEFT_SIDEBAR_MENU',
  50. // 菜单栏顶部
  51. 'LEFT_SIDEBAR_MENU_TOP' => 'ADMIN_LEFT_SIDEBAR_MENU_TOP',
  52. // 菜单栏底部
  53. 'LEFT_SIDEBAR_MENU_BOTTOM' => 'ADMIN_LEFT_SIDEBAR_MENU_BOTTOM',
  54. ];
  55. private static $defaultPjaxContainerId = 'pjax-container';
  56. /**
  57. * 版本.
  58. *
  59. * @return string
  60. */
  61. public static function longVersion()
  62. {
  63. return sprintf('Dcat Admin <comment>version</comment> <info>%s</info>', static::VERSION);
  64. }
  65. /**
  66. * @return Color
  67. */
  68. public static function color()
  69. {
  70. return app('admin.color');
  71. }
  72. /**
  73. * 菜单管理.
  74. *
  75. * @param Closure|null $builder
  76. *
  77. * @return Menu
  78. */
  79. public static function menu(Closure $builder = null)
  80. {
  81. $menu = app('admin.menu');
  82. $builder && $builder($menu);
  83. return $menu;
  84. }
  85. /**
  86. * 设置 title.
  87. *
  88. * @return string|void
  89. */
  90. public static function title($title = null)
  91. {
  92. if ($title === null) {
  93. return static::context()->metaTitle ?: config('admin.title');
  94. }
  95. static::context()->metaTitle = $title;
  96. }
  97. /**
  98. * @param null|string $favicon
  99. *
  100. * @return string|void
  101. */
  102. public static function favicon($favicon = null)
  103. {
  104. if ($favicon === null) {
  105. return static::context()->favicon;
  106. }
  107. static::context()->favicon = $favicon;
  108. }
  109. /**
  110. * 设置翻译文件路径.
  111. *
  112. * @param string|null $path
  113. */
  114. public static function translation(?string $path)
  115. {
  116. static::context()->translation = $path;
  117. }
  118. /**
  119. * 获取登录用户模型.
  120. *
  121. * @return Model|Authenticatable|HasPermissions
  122. */
  123. public static function user()
  124. {
  125. return static::guard()->user();
  126. }
  127. /**
  128. * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard|GuardHelpers
  129. */
  130. public static function guard()
  131. {
  132. return Auth::guard(config('admin.auth.guard') ?: 'admin');
  133. }
  134. /**
  135. * @param Closure|null $builder
  136. *
  137. * @return Navbar
  138. */
  139. public static function navbar(Closure $builder = null)
  140. {
  141. $navbar = app('admin.navbar');
  142. $builder && $builder($navbar);
  143. return $navbar;
  144. }
  145. /**
  146. * 启用或禁用Pjax.
  147. *
  148. * @param bool $value
  149. *
  150. * @return void
  151. */
  152. public static function pjax(bool $value = true)
  153. {
  154. static::context()->pjaxContainerId = $value ? static::$defaultPjaxContainerId : false;
  155. }
  156. /**
  157. * 禁用pjax.
  158. *
  159. * @return void
  160. */
  161. public static function disablePjax()
  162. {
  163. static::pjax(false);
  164. }
  165. /**
  166. * 获取pjax ID.
  167. *
  168. * @return string|void
  169. */
  170. public static function getPjaxContainerId()
  171. {
  172. $id = static::context()->pjaxContainerId;
  173. if ($id === false) {
  174. return;
  175. }
  176. return $id ?: static::$defaultPjaxContainerId;
  177. }
  178. /**
  179. * section.
  180. *
  181. * @param Closure|null $builder
  182. *
  183. * @return SectionManager
  184. */
  185. public static function section(Closure $builder = null)
  186. {
  187. $manager = app('admin.sections');
  188. $builder && $builder($manager);
  189. return $manager;
  190. }
  191. /**
  192. * 配置.
  193. *
  194. * @return \Dcat\Admin\Support\Setting
  195. */
  196. public static function setting()
  197. {
  198. return app('admin.setting');
  199. }
  200. /**
  201. * 创建数据仓库实例.
  202. *
  203. * @param string|Repository|Model|Builder $value
  204. * @param array $args
  205. *
  206. * @return Repository
  207. */
  208. public static function repository($repository, array $args = [])
  209. {
  210. if (is_string($repository)) {
  211. $repository = new $repository($args);
  212. }
  213. if ($repository instanceof Model || $repository instanceof Builder) {
  214. $repository = EloquentRepository::make($repository);
  215. }
  216. if (! $repository instanceof Repository) {
  217. $class = is_object($repository) ? get_class($repository) : $repository;
  218. throw new InvalidArgumentException("The class [{$class}] must be a type of [".Repository::class.'].');
  219. }
  220. return $repository;
  221. }
  222. /**
  223. * 应用管理.
  224. *
  225. * @return Application
  226. */
  227. public static function app()
  228. {
  229. return app('admin.app');
  230. }
  231. /**
  232. * 处理异常.
  233. *
  234. * @param \Throwable $e
  235. *
  236. * @return mixed
  237. */
  238. public static function handleException(\Throwable $e)
  239. {
  240. return app(ExceptionHandler::class)->handle($e);
  241. }
  242. /**
  243. * 上报异常.
  244. *
  245. * @param \Throwable $e
  246. *
  247. * @return mixed
  248. */
  249. public static function reportException(\Throwable $e)
  250. {
  251. return app(ExceptionHandler::class)->report($e);
  252. }
  253. /**
  254. * 显示异常信息.
  255. *
  256. * @param \Throwable $e
  257. *
  258. * @return mixed
  259. */
  260. public static function renderException(\Throwable $e)
  261. {
  262. return app(ExceptionHandler::class)->render($e);
  263. }
  264. /**
  265. * @param callable $callback
  266. */
  267. public static function booting($callback)
  268. {
  269. Event::listen('admin:booting', $callback);
  270. }
  271. /**
  272. * @param callable $callback
  273. */
  274. public static function booted($callback)
  275. {
  276. Event::listen('admin:booted', $callback);
  277. }
  278. /**
  279. * @return void
  280. */
  281. public static function callBooting()
  282. {
  283. Event::dispatch('admin:booting');
  284. }
  285. /**
  286. * @return void
  287. */
  288. public static function callBooted()
  289. {
  290. Event::dispatch('admin:booted');
  291. }
  292. /**
  293. * 上下文管理.
  294. *
  295. * @return \Dcat\Admin\Support\Context
  296. */
  297. public static function context()
  298. {
  299. return app('admin.context');
  300. }
  301. /**
  302. * 翻译器.
  303. *
  304. * @return \Dcat\Admin\Support\Translator
  305. */
  306. public static function translator()
  307. {
  308. return app('admin.translator');
  309. }
  310. /**
  311. * @param array|string $name
  312. *
  313. * @return void
  314. */
  315. public static function addIgnoreQueryName($name)
  316. {
  317. $context = static::context();
  318. $ignoreQueries = $context->ignoreQueries ?? [];
  319. $context->ignoreQueries = array_merge($ignoreQueries, (array) $name);
  320. }
  321. /**
  322. * @return array
  323. */
  324. public static function getIgnoreQueryNames()
  325. {
  326. return static::context()->ignoreQueries ?? [];
  327. }
  328. /**
  329. * 响应json数据.
  330. *
  331. * @param array $data
  332. *
  333. * @return JsonResponse
  334. */
  335. public static function json(array $data = [])
  336. {
  337. return JsonResponse::make($data);
  338. }
  339. /**
  340. * 插件管理.
  341. *
  342. * @param string $name
  343. *
  344. * @return \Dcat\Admin\Extend\Manager|\Dcat\Admin\Extend\ServiceProvider|null
  345. */
  346. public static function extension(?string $name = null)
  347. {
  348. if ($name) {
  349. return app('admin.extend')->get($name);
  350. }
  351. return app('admin.extend');
  352. }
  353. /**
  354. * 响应并中断后续逻辑.
  355. *
  356. * @param Response|string|array $response
  357. *
  358. * @throws HttpResponseException
  359. */
  360. public static function exit($response = '')
  361. {
  362. if (is_array($response)) {
  363. $response = response()->json($response);
  364. } elseif ($response instanceof JsonResponse) {
  365. $response = $response->send();
  366. }
  367. throw new HttpResponseException($response instanceof Response ? $response : response($response));
  368. }
  369. /**
  370. * 类自动加载器.
  371. *
  372. * @return \Composer\Autoload\ClassLoader
  373. */
  374. public static function classLoader()
  375. {
  376. return Composer::loader();
  377. }
  378. /**
  379. * 往分组插入中间件.
  380. *
  381. * @param array $mix
  382. */
  383. public static function mixMiddlewareGroup(array $mix = [])
  384. {
  385. $router = app('router');
  386. $group = $router->getMiddlewareGroups()['admin'] ?? [];
  387. if ($mix) {
  388. $finalGroup = [];
  389. foreach ($group as $i => $mid) {
  390. $next = $i + 1;
  391. $finalGroup[] = $mid;
  392. if (! isset($group[$next]) || $group[$next] !== 'admin.permission') {
  393. continue;
  394. }
  395. $finalGroup = array_merge($finalGroup, $mix);
  396. $mix = [];
  397. }
  398. if ($mix) {
  399. $finalGroup = array_merge($finalGroup, $mix);
  400. }
  401. $group = $finalGroup;
  402. }
  403. $router->middlewareGroup('admin', $group);
  404. }
  405. /**
  406. * 获取js配置.
  407. *
  408. * @param array|null $variables
  409. *
  410. * @return string
  411. */
  412. public static function jsVariables(array $variables = null)
  413. {
  414. $jsVariables = static::context()->jsVariables ?: [];
  415. if ($variables !== null) {
  416. static::context()->jsVariables = array_merge(
  417. $jsVariables,
  418. $variables
  419. );
  420. return;
  421. }
  422. $sidebarStyle = config('admin.layout.sidebar_style') ?: 'light';
  423. $jsVariables['pjax_container_selector'] = '#'.static::getPjaxContainerId();
  424. $jsVariables['token'] = csrf_token();
  425. $jsVariables['lang'] = __('admin.client') ?: [];
  426. $jsVariables['colors'] = static::color()->all();
  427. $jsVariables['dark_mode'] = static::isDarkMode();
  428. $jsVariables['sidebar_dark'] = config('admin.layout.sidebar_dark') || ($sidebarStyle === 'dark');
  429. $jsVariables['sidebar_light_style'] = in_array($sidebarStyle, ['dark', 'light'], true) ? 'sidebar-light-primary' : 'sidebar-primary';
  430. return admin_javascript_json($jsVariables);
  431. }
  432. /**
  433. * @return bool
  434. */
  435. public static function isDarkMode()
  436. {
  437. $bodyClass = config('admin.layout.body_class');
  438. return in_array(
  439. 'dark-mode',
  440. is_array($bodyClass) ? $bodyClass : explode(' ', $bodyClass),
  441. true
  442. );
  443. }
  444. /**
  445. * 注册路由.
  446. *
  447. * @return void
  448. */
  449. public static function routes()
  450. {
  451. $attributes = [
  452. 'prefix' => config('admin.route.prefix'),
  453. 'middleware' => config('admin.route.middleware'),
  454. ];
  455. if (config('admin.auth.enable', true)) {
  456. app('router')->group($attributes, function ($router) {
  457. /* @var \Illuminate\Routing\Router $router */
  458. $router->namespace('Dcat\Admin\Http\Controllers')->group(function ($router) {
  459. /* @var \Illuminate\Routing\Router $router */
  460. $router->resource('auth/users', 'UserController');
  461. $router->resource('auth/menu', 'MenuController', ['except' => ['create', 'show']]);
  462. if (config('admin.permission.enable')) {
  463. $router->resource('auth/roles', 'RoleController');
  464. $router->resource('auth/permissions', 'PermissionController');
  465. }
  466. });
  467. $router->resource('auth/extensions', 'Dcat\Admin\Http\Controllers\ExtensionController', ['only' => ['index', 'store', 'update']]);
  468. $authController = config('admin.auth.controller', AuthController::class);
  469. $router->get('auth/login', $authController.'@getLogin');
  470. $router->post('auth/login', $authController.'@postLogin');
  471. $router->get('auth/logout', $authController.'@getLogout');
  472. $router->get('auth/setting', $authController.'@getSetting');
  473. $router->put('auth/setting', $authController.'@putSetting');
  474. });
  475. }
  476. static::registerHelperRoutes();
  477. }
  478. /**
  479. * 注册api路由.
  480. *
  481. * @return void
  482. */
  483. public static function registerApiRoutes()
  484. {
  485. $attributes = [
  486. 'prefix' => admin_base_path('dcat-api'),
  487. 'middleware' => config('admin.route.middleware'),
  488. 'namespace' => 'Dcat\Admin\Http\Controllers',
  489. 'as' => 'dcat-api.',
  490. ];
  491. app('router')->group($attributes, function ($router) {
  492. /* @var \Illuminate\Routing\Router $router */
  493. $router->post('action', 'HandleActionController@handle')->name('action');
  494. $router->post('form', 'HandleFormController@handle')->name('form');
  495. $router->post('form/upload', 'HandleFormController@uploadFile')->name('form.upload');
  496. $router->post('form/destroy-file', 'HandleFormController@destroyFile')->name('form.destroy-file');
  497. $router->post('value', 'ValueController@handle')->name('value');
  498. $router->get('render', 'RenderableController@handle')->name('render');
  499. $router->post('tinymce/upload', 'TinymceController@upload')->name('tinymce.upload');
  500. $router->post('editor-md/upload', 'EditorMDController@upload')->name('editor-md.upload');
  501. });
  502. }
  503. /**
  504. * 注册开发工具路由.
  505. *
  506. * @return void
  507. */
  508. public static function registerHelperRoutes()
  509. {
  510. if (! config('admin.helpers.enable', true) || ! config('app.debug')) {
  511. return;
  512. }
  513. $attributes = [
  514. 'prefix' => config('admin.route.prefix'),
  515. 'middleware' => config('admin.route.middleware'),
  516. ];
  517. app('router')->group($attributes, function ($router) {
  518. /* @var \Illuminate\Routing\Router $router */
  519. $router->get('helpers/scaffold', 'Dcat\Admin\Http\Controllers\ScaffoldController@index');
  520. $router->post('helpers/scaffold', 'Dcat\Admin\Http\Controllers\ScaffoldController@store');
  521. $router->post('helpers/scaffold/table', 'Dcat\Admin\Http\Controllers\ScaffoldController@table');
  522. $router->get('helpers/icons', 'Dcat\Admin\Http\Controllers\IconController@index');
  523. });
  524. }
  525. }