审查视图

application/admin/command/Menu.php 12.7 KB
Karson authored
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php

namespace app\admin\command;

use app\admin\model\AuthRule;
use ReflectionClass;
use ReflectionMethod;
use think\Cache;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
14
use think\Exception;
15
use think\Loader;
Karson authored
16 17 18 19 20 21 22 23

class Menu extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this
Karson authored
24 25 26 27
            ->setName('menu')
            ->addOption('controller', 'c', Option::VALUE_REQUIRED | Option::VALUE_IS_ARRAY, 'controller name,use \'all-controller\' when build all menu', null)
            ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete the specified menu', '')
            ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force delete menu,without tips', null)
eviltrue authored
28
            ->addOption('equal', 'e', Option::VALUE_OPTIONAL, 'the controller must be equal', null)
Karson authored
29
            ->setDescription('Build auth menu from controller');
30
        //要执行的controller必须一样,不适用模糊查询
Karson authored
31 32 33 34 35 36 37
    }

    protected function execute(Input $input, Output $output)
    {
        $this->model = new AuthRule();
        $adminPath = dirname(__DIR__) . DS;
        //控制器名
Karson authored
38
        $controller = $input->getOption('controller') ?: '';
Karson authored
39
        if (!$controller) {
40
            throw new Exception("please input controller name");
Karson authored
41
        }
Karson authored
42
        $force = $input->getOption('force');
43 44
        //是否为删除模式
        $delete = $input->getOption('delete');
eviltrue authored
45
        //是否控制器完全匹配
46
        $equal = $input->getOption('equal');
eviltrue authored
47 48

Karson authored
49 50
        if ($delete) {
            if (in_array('all-controller', $controller)) {
51 52 53
                throw new Exception("could not delete all menu");
            }
            $ids = [];
eviltrue authored
54
            $list = $this->model->where(function ($query) use ($controller, $equal) {
Karson authored
55
                foreach ($controller as $index => $item) {
56 57 58 59 60 61 62 63 64 65 66 67
                    if (stripos($item, '_') !== false) {
                        $item = Loader::parseName($item, 1);
                    }
                    if (stripos($item, '/') !== false) {
                        $controllerArr = explode('/', $item);
                        end($controllerArr);
                        $key = key($controllerArr);
                        $controllerArr[$key] = Loader::parseName($controllerArr[$key]);
                    } else {
                        $controllerArr = [Loader::parseName($item)];
                    }
                    $item = str_replace('_', '\_', implode('/', $controllerArr));
68
                    if ($equal) {
eviltrue authored
69
                        $query->whereOr('name', 'eq', $item);
70
                    } else {
71
                        $query->whereOr('name', 'like', strtolower($item) . "%");
72
                    }
Karson authored
73 74 75
                }
            })->select();
            foreach ($list as $k => $v) {
76 77 78
                $output->warning($v->name);
                $ids[] = $v->id;
            }
Karson authored
79
            if (!$ids) {
80 81
                throw new Exception("There is no menu to delete");
            }
Karson authored
82 83
            if (!$force) {
                $output->info("Are you sure you want to delete all those menu?  Type 'yes' to continue: ");
84
                $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
Karson authored
85 86 87
                if (trim($line) != 'yes') {
                    throw new Exception("Operation is aborted!");
                }
88 89 90 91 92 93 94
            }
            AuthRule::destroy($ids);

            Cache::rm("__menu__");
            $output->info("Delete Successed");
            return;
        }
Karson authored
95
Karson authored
96 97
        if (!in_array('all-controller', $controller)) {
            foreach ($controller as $index => $item) {
98 99 100 101 102 103 104 105 106 107 108
                if (stripos($item, '_') !== false) {
                    $item = Loader::parseName($item, 1);
                }
                if (stripos($item, '/') !== false) {
                    $controllerArr = explode('/', $item);
                    end($controllerArr);
                    $key = key($controllerArr);
                    $controllerArr[$key] = ucfirst($controllerArr[$key]);
                } else {
                    $controllerArr = [ucfirst($item)];
                }
Karson authored
109 110 111 112 113 114
                $adminPath = dirname(__DIR__) . DS . 'controller' . DS . implode(DS, $controllerArr) . '.php';
                if (!is_file($adminPath)) {
                    $output->error("controller not found");
                    return;
                }
                $this->importRule($item);
Karson authored
115
            }
Karson authored
116
        } else {
117 118 119 120
            $authRuleList = AuthRule::select();
            //生成权限规则备份文件
            file_put_contents(RUNTIME_PATH . 'authrule.json', json_encode(collection($authRuleList)->toArray()));
121
            $this->model->where('id', '>', 0)->delete();
Karson authored
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
            $controllerDir = $adminPath . 'controller' . DS;
            // 扫描新的节点信息并导入
            $treelist = $this->import($this->scandir($controllerDir));
        }
        Cache::rm("__menu__");
        $output->info("Build Successed!");
    }

    /**
     * 递归扫描文件夹
     * @param string $dir
     * @return array
     */
    public function scandir($dir)
    {
        $result = [];
        $cdir = scandir($dir);
Karson authored
139 140 141
        foreach ($cdir as $value) {
            if (!in_array($value, array(".", ".."))) {
                if (is_dir($dir . DS . $value)) {
142
                    $result[$value] = $this->scandir($dir . DS . $value);
Karson authored
143
                } else {
Karson authored
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
                    $result[] = $value;
                }
            }
        }
        return $result;
    }

    /**
     * 导入规则节点
     * @param array $dirarr
     * @param array $parentdir
     * @return array
     */
    public function import($dirarr, $parentdir = [])
    {
        $menuarr = [];
Karson authored
160 161
        foreach ($dirarr as $k => $v) {
            if (is_array($v)) {
Karson authored
162 163 164
                //当前是文件夹
                $nowparentdir = array_merge($parentdir, [$k]);
                $this->import($v, $nowparentdir);
Karson authored
165
            } else {
Karson authored
166
                //只匹配PHP文件
Karson authored
167
                if (!preg_match('/^(\w+)\.php$/', $v, $matchone)) {
Karson authored
168 169 170 171 172 173 174 175 176 177 178 179 180
                    continue;
                }
                //导入文件
                $controller = ($parentdir ? implode('/', $parentdir) . '/' : '') . $matchone[1];
                $this->importRule($controller);
            }
        }

        return $menuarr;
    }

    protected function importRule($controller)
    {
181
        $controller = str_replace('\\', '/', $controller);
182 183 184 185 186 187 188 189 190
        if (stripos($controller, '/') !== false) {
            $controllerArr = explode('/', $controller);
            end($controllerArr);
            $key = key($controllerArr);
            $controllerArr[$key] = ucfirst($controllerArr[$key]);
        } else {
            $key = 0;
            $controllerArr = [ucfirst($controller)];
        }
191 192
        $classSuffix = Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '';
        $className = "\\app\\admin\\controller\\" . implode("\\", $controllerArr) . $classSuffix;
Karson authored
193 194 195 196 197 198 199 200 201 202 203 204 205

        $pathArr = $controllerArr;
        array_unshift($pathArr, '', 'application', 'admin', 'controller');
        $classFile = ROOT_PATH . implode(DS, $pathArr) . $classSuffix . ".php";
        $classContent = file_get_contents($classFile);
        $uniqueName = uniqid("FastAdmin") . $classSuffix;
        $classContent = str_replace("class " . $controllerArr[$key] . $classSuffix . " ", 'class ' . $uniqueName . ' ', $classContent);
        $classContent = preg_replace("/namespace\s(.*);/", 'namespace ' . __NAMESPACE__ . ";", $classContent);

        //临时的类文件
        $tempClassFile = __DIR__ . DS . $uniqueName . ".php";
        file_put_contents($tempClassFile, $classContent);
        $className = "\\app\\admin\\command\\" . $uniqueName;
206 207 208 209 210 211 212 213 214

        //删除临时文件
        register_shutdown_function(function () use ($tempClassFile) {
            if ($tempClassFile) {
                //删除临时文件
                @unlink($tempClassFile);
            }
        });
Karson authored
215
        //反射机制调用类的注释和方法名
216 217
        $reflector = new ReflectionClass($className);
Karson authored
218 219 220
        //只匹配公共的方法
        $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
        $classComment = $reflector->getDocComment();
Karson authored
221 222 223
        //判断是否有启用软删除
        $softDeleteMethods = ['destroy', 'restore', 'recyclebin'];
        $withSofeDelete = false;
224 225 226
        $modelRegexArr = ["/\\\$this\->model\s*=\s*model\(['|\"](\w+)['|\"]\);/", "/\\\$this\->model\s*=\s*new\s+([a-zA-Z\\\]+);/"];
        $modelRegex = preg_match($modelRegexArr[0], $classContent) ? $modelRegexArr[0] : $modelRegexArr[1];
        preg_match_all($modelRegex, $classContent, $matches);
Karson authored
227
        if (isset($matches[1]) && isset($matches[1][0]) && $matches[1][0]) {
Karson authored
228 229
            \think\Request::instance()->module('admin');
            $model = model($matches[1][0]);
Karson authored
230
            if (in_array('trashed', get_class_methods($model))) {
Karson authored
231 232 233
                $withSofeDelete = true;
            }
        }
Karson authored
234
        //忽略的类
235
        if (stripos($classComment, "@internal") !== false) {
Karson authored
236 237 238 239 240 241
            return;
        }
        preg_match_all('#(@.*?)\n#s', $classComment, $annotations);
        $controllerIcon = 'fa fa-circle-o';
        $controllerRemark = '';
        //判断注释中是否设置了icon值
Karson authored
242 243
        if (isset($annotations[1])) {
            foreach ($annotations[1] as $tag) {
244
                if (stripos($tag, '@icon') !== false) {
Karson authored
245 246
                    $controllerIcon = substr($tag, stripos($tag, ' ') + 1);
                }
247
                if (stripos($tag, '@remark') !== false) {
Karson authored
248 249 250 251 252
                    $controllerRemark = substr($tag, stripos($tag, ' ') + 1);
                }
            }
        }
        //过滤掉其它字符
253
        $controllerTitle = trim(preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $classComment));
Karson authored
254 255 256

        //导入中文语言包
        \think\Lang::load(dirname(__DIR__) . DS . 'lang/zh-cn.php');
257
Karson authored
258
        //先导入菜单的数据
Karson authored
259
        $pid = 0;
Karson authored
260
        foreach ($controllerArr as $k => $v) {
Karson authored
261
            $key = $k + 1;
262 263 264 265 266 267 268
            //驼峰转下划线
            $controllerNameArr = array_slice($controllerArr, 0, $key);
            foreach ($controllerNameArr as &$val) {
                $val = strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $val), "_"));
            }
            unset($val);
            $name = implode('/', $controllerNameArr);
Karson authored
269 270 271
            $title = (!isset($controllerArr[$key]) ? $controllerTitle : '');
            $icon = (!isset($controllerArr[$key]) ? $controllerIcon : 'fa fa-list');
            $remark = (!isset($controllerArr[$key]) ? $controllerRemark : '');
272
            $title = $title ? $title : $v;
Karson authored
273
            $rulemodel = $this->model->get(['name' => $name]);
Karson authored
274
            if (!$rulemodel) {
Karson authored
275
                $this->model
Karson authored
276 277 278
                    ->data(['pid' => $pid, 'name' => $name, 'title' => $title, 'icon' => $icon, 'remark' => $remark, 'ismenu' => 1, 'status' => 'normal'])
                    ->isUpdate(false)
                    ->save();
Karson authored
279
                $pid = $this->model->id;
Karson authored
280
            } else {
Karson authored
281 282 283 284
                $pid = $rulemodel->id;
            }
        }
        $ruleArr = [];
Karson authored
285
        foreach ($methods as $m => $n) {
Karson authored
286
            //过滤特殊的类
Karson authored
287
            if (substr($n->name, 0, 2) == '__' || $n->name == '_initialize') {
Karson authored
288 289
                continue;
            }
Karson authored
290
            //未启用软删除时过滤相关方法
Karson authored
291
            if (!$withSofeDelete && in_array($n->name, $softDeleteMethods)) {
Karson authored
292 293
                continue;
            }
Karson authored
294
            //只匹配符合的方法
Karson authored
295
            if (!preg_match('/^(\w+)' . Config::get('action_suffix') . '/', $n->name, $matchtwo)) {
Karson authored
296 297 298 299 300
                unset($methods[$m]);
                continue;
            }
            $comment = $reflector->getMethod($n->name)->getDocComment();
            //忽略的方法
301
            if (stripos($comment, "@internal") !== false) {
Karson authored
302 303 304
                continue;
            }
            //过滤掉其它字符
Karson authored
305
            $comment = preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $comment);
306
307
            $title = $comment ? $comment : ucfirst($n->name);
308 309 310 311 312

            //获取主键,作为AuthRule更新依据
            $id = $this->getAuthRulePK($name . "/" . strtolower($n->name));

            $ruleArr[] = array('id' => $id, 'pid' => $pid, 'name' => $name . "/" . strtolower($n->name), 'icon' => 'fa fa-circle-o', 'title' => $title, 'ismenu' => 0, 'status' => 'normal');
Karson authored
313
        }
314
        $this->model->isUpdate(false)->saveAll($ruleArr);
Karson authored
315 316
    }
317
    //获取主键
318 319
    protected function getAuthRulePK($name)
    {
Karson authored
320
        if (!empty($name)) {
321
            $id = $this->model
Karson authored
322 323
                ->where('name', $name)
                ->value('id');
324
            return $id ? $id : null;
325 326
        }
    }
Karson authored
327
}