🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 控制器 ## 代码 \>注:需要类库`Tree`,和模型`AdminMenuModel` ``` <?php namespace app\agent\controller; use think\Controller; use think\Db; use tree\Tree; use app\agent\model\AdminMenuModel; class RbacController extends Controller { /** * 设置角色权限 */ public function authorize() { $AuthAccess = Db::name("AuthAccess"); $adminMenuModel = new AdminMenuModel(); //角色ID $roleId = $this->request->param("id", 0, 'intval'); if (empty($roleId)) { $this->error("参数错误!"); } $tree = new Tree(); $tree->icon = ['│ ', '├─ ', '└─ ']; $tree->nbsp = '   '; $result = $adminMenuModel->menuCache(); $newMenus = []; $privilegeData = $AuthAccess->where(["role_id" => $roleId])->column("rule_name");//获取权限表数据 foreach ($result as $m) { $newMenus[$m['id']] = $m; } foreach ($result as $n => $t) { $result[$n]['checked'] = ($this->_isChecked($t, $privilegeData)) ? ' checked' : ''; $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus); $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;'; $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : ''; } $str = "<tr id='node-\$id'\$parentIdNode style='\$style'> <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td> </tr>"; $tree->init($result); $category = $tree->getTree(0, $str); $this->assign("category", $category); $this->assign("roleId", $roleId); return $this->fetch(); } /** * 检查指定菜单是否有权限 * @param array $menu menu表中数组 * @param $privData * @return bool */ private function _isChecked($menu, $privData) { $app = $menu['app']; $model = $menu['controller']; $action = $menu['action']; $name = strtolower("$app/$model/$action"); if ($privData) { if (in_array($name, $privData)) { return true; } else { return false; } } else { return false; } } /** * 获取菜单深度 * @param $id * @param array $array * @param int $i * @return int */ protected function _getLevel($id, $array = [], $i = 0) { if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) { return $i; } else { $i++; return $this->_getLevel($array[$id]['parent_id'], $array, $i); } } } ```