Admin.php 17 KB

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