Admin.php 17 KB

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