Admin.php 17 KB

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