| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- <?php
- namespace Dcat\Admin\Extend;
- use Illuminate\Support\Arr;
- use Illuminate\Support\Facades\Validator;
- /**
- * @property \Symfony\Component\Console\Output\OutputInterface $output
- */
- trait CanImportMenu
- {
- protected $menu = [];
- protected $menuValidationRules = [
- 'parent' => 'nullable',
- 'title' => 'required',
- 'uri' => 'nullable',
- 'icon' => 'nullable',
- ];
- /**
- * 获取菜单节点.
- *
- * @return array
- */
- protected function menu()
- {
- return $this->menu;
- }
- /**
- * 添加菜单.
- *
- * @param array $menu
- *
- * @throws \Exception
- */
- protected function addMenu(array $menu = [])
- {
- $menu = $menu ?: $this->menu();
- if (! Arr::isAssoc($menu)) {
- foreach ($menu as $v) {
- $this->addMenu($v);
- }
- return;
- }
- if (! $this->validateMenu($menu)) {
- return;
- }
- if ($menuModel = $this->getMenuModel()) {
- $lastOrder = $menuModel::max('order');
- $menuModel::create([
- 'parent_id' => $this->getParentMenuId($menu['parent'] ?? 0),
- 'order' => $lastOrder + 1,
- 'title' => $menu['title'],
- 'icon' => (string) ($menu['icon'] ?? ''),
- 'uri' => (string) ($menu['uri'] ?? ''),
- 'extension' => $this->getName(),
- ]);
- }
- }
- /**
- * 刷新菜单.
- *
- * @throws \Exception
- */
- protected function refreshMenu()
- {
- $this->flushMenu();
- $this->addMenu();
- }
- /**
- * 根据名称获取菜单ID.
- *
- * @param int|string $parent
- *
- * @return int
- */
- protected function getParentMenuId($parent)
- {
- if (is_numeric($parent)) {
- return $parent;
- }
- $menuModel = $this->getMenuModel();
- return $menuModel::query()
- ->where('title', $parent)
- ->where('extension', $this->getName())
- ->value('id') ?: 0;
- }
- /**
- * 删除菜单.
- */
- protected function flushMenu()
- {
- $menuModel = $this->getMenuModel();
- if (! $menuModel) {
- return;
- }
- $menuModel::query()
- ->where('extension', $this->getName())
- ->delete();
- }
- /**
- * 验证菜单字段格式是否正确.
- *
- * @param array $menu
- *
- * @throws \Exception
- *
- * @return bool
- */
- public function validateMenu(array $menu)
- {
- /** @var \Illuminate\Validation\Validator $validator */
- $validator = Validator::make($menu, $this->menuValidationRules);
- if ($validator->passes()) {
- return true;
- }
- return false;
- }
- protected function getMenuModel()
- {
- return config('admin.database.menu_model');
- }
- }
|