Files
amb_wechatapp/application/admin/controller/Menu.php
T

122 lines
2.8 KiB
PHP

<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
class Menu extends Backend
{
protected $noNeedLogin = ['*'];
protected $noNeedRight = '*';
protected $layout = '';
/**
* 权限更新流程
* 1、清空tuzhi_auth_rule表,
* 2、执行 php think menu --controller=all-controller 重载路由
* 3、menu.php 文件更新菜单架构(对应前台-管理员端的路由)
* 4、menu_bind_rule.php 增加模块对应控制器
* 5、执行build()方法,更新menu_auth.php文件
*/
/**
* 对比哪些rule未被使用
* @return void
*/
public function compare(){
$rules = \app\admin\library\Auth::instance()->getRoleRules(['*']);
$compareData = Db::name("auth_rule")->where([
'name'=>['not in',$rules]
])->select();
$compareData = collection($compareData)->toArray();
foreach ($compareData as $rule){
echo "{$rule['name']} - {$rule['title']}<br>";
}
}
/**
* 构建menu_auth.php文件
* @return string[]
*/
public function build()
{
$bindRule = config('menu_bind_rule');
$tree = [];
foreach ($bindRule as $role => $urls){
$rules = [];
if(!empty($urls)){
foreach ($urls as $url){
$rules = array_merge($rules,$this->getMenuRules($url));
}
}
$tree[$role] = $rules;
}
$this->buildMenuAuthFile($tree);
}
public function getMenuRules($name){
$rule = Db::name('auth_rule')->where([
'name'=>$name
])->find();
if(!$rule){
return [];
}
$data = [];
$rules = $this->getChildRules($rule['id']);
foreach ($rules as $key => $item){
$data[$key] = $item;
}
$data[$rule['name']] = $rule['title'];
return $data;
}
public function getChildRules($id,$rules = []){
$urls = Db::name('auth_rule')->where([
'pid'=>$id
])->field(['name','title','id'])->select();
if($urls){
foreach($urls as $k=>$v){
$rules[$v['name']] = $v['title'];
$rules = $this->getChildRules($v['id'],$rules);
}
}
if(!$rules){
return [];
}
//按照rule去重
return array_merge([], $rules);
}
/**
* 构建菜单文件
* @return void
*/
public function buildMenuAuthFile($rules){
// 将数组结构保存为 PHP 文件
$phpContent = "<?php\n\nreturn " . var_export($rules, true) . ";\n";
$filePath = APP_PATH . 'extra' . DIRECTORY_SEPARATOR . 'menu_auth.php';
file_put_contents($filePath, $phpContent);
}
}