审查视图

application/admin/command/Menu.php 10.3 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;
Karson authored
15 16 17 18 19 20 21 22 23 24 25

class Menu extends Command
{

    protected $model = null;

    protected function configure()
    {
        $this
                ->setName('menu')
                ->addOption('controller', 'c', Option::VALUE_REQUIRED, 'controller name,use \'all-controller\' when build all menu', null)
26
                ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete the specified menu', '')
Karson authored
27 28 29 30 31 32 33 34
                ->setDescription('Build auth menu from controller');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->model = new AuthRule();
        $adminPath = dirname(__DIR__) . DS;
        //控制器名
Karson authored
35
        $controller = $input->getOption('controller') ?: '';
Karson authored
36 37
        if (!$controller)
        {
38
            throw new Exception("please input controller name");
Karson authored
39
        }
40 41 42 43 44 45 46 47 48
        //是否为删除模式
        $delete = $input->getOption('delete');
        if ($delete)
        {
            if ($controller == 'all-controller')
            {
                throw new Exception("could not delete all menu");
            }
            $ids = [];
49
            $list = $this->model->where('name', 'like', strtolower($controller) . "%")->select();
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
            foreach ($list as $k => $v)
            {
                $output->warning($v->name);
                $ids[] = $v->id;
            }
            if (!$ids)
            {
                throw new Exception("There is no menu to delete");
            }
            $output->info("Are you sure you want to delete all those menu?  Type 'yes' to continue: ");
            $line = fgets(STDIN);
            if (trim($line) != 'yes')
            {
                throw new Exception("Operation is aborted!");
            }
            AuthRule::destroy($ids);

            Cache::rm("__menu__");
            $output->info("Delete Successed");
            return;
        }
Karson authored
71 72 73 74 75 76 77

        if ($controller != 'all-controller')
        {
            $controllerArr = explode('/', $controller);
            end($controllerArr);
            $key = key($controllerArr);
            $controllerArr[$key] = ucfirst($controllerArr[$key]);
78
            $adminPath = dirname(__DIR__) . DS . 'controller' . DS . implode(DS, $controllerArr) . '.php';
Karson authored
79 80 81 82 83 84 85 86 87
            if (!is_file($adminPath))
            {
                $output->error("controller not found");
                return;
            }
            $this->importRule($controller);
        }
        else
        {
88
            $this->model->where('id', '>', 0)->delete();
Karson authored
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
            $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);
        foreach ($cdir as $value)
        {
            if (!in_array($value, array(".", "..")))
            {
110
                if (is_dir($dir . DS . $value))
Karson authored
111
                {
112
                    $result[$value] = $this->scandir($dir . DS . $value);
Karson authored
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
                }
                else
                {
                    $result[] = $value;
                }
            }
        }
        return $result;
    }

    /**
     * 导入规则节点
     * @param array $dirarr
     * @param array $parentdir
     * @return array
     */
    public function import($dirarr, $parentdir = [])
    {
        $menuarr = [];
        foreach ($dirarr as $k => $v)
        {
            if (is_array($v))
            {
                //当前是文件夹
                $nowparentdir = array_merge($parentdir, [$k]);
                $this->import($v, $nowparentdir);
            }
            else
            {
                //只匹配PHP文件
                if (!preg_match('/^(\w+)\.php$/', $v, $matchone))
                {
                    continue;
                }
                //导入文件
                $controller = ($parentdir ? implode('/', $parentdir) . '/' : '') . $matchone[1];
                $this->importRule($controller);
            }
        }

        return $menuarr;
    }

    protected function importRule($controller)
    {
        $controllerArr = explode('/', $controller);
        end($controllerArr);
        $key = key($controllerArr);
        $controllerArr[$key] = ucfirst($controllerArr[$key]);
162 163
        $classSuffix = Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '';
        $className = "\\app\\admin\\controller\\" . implode("\\", $controllerArr) . $classSuffix;
Karson authored
164 165 166 167 168 169 170 171 172 173 174 175 176

        $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;
Karson authored
177
        //反射机制调用类的注释和方法名
178 179 180 181 182 183 184 185
        $reflector = new ReflectionClass($className);

        if (isset($tempClassFile))
        {
            //删除临时文件
            @unlink($tempClassFile);
        }
Karson authored
186 187 188
        //只匹配公共的方法
        $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
        $classComment = $reflector->getDocComment();
Karson authored
189 190 191 192 193 194 195 196 197 198 199 200 201
        //判断是否有启用软删除
        $softDeleteMethods = ['destroy', 'restore', 'recyclebin'];
        $withSofeDelete = false;
        preg_match_all("/\\\$this\->model\s*=\s*model\('(\w+)'\);/", $classContent, $matches);
        if (isset($matches[1]) && isset($matches[1][0]) && $matches[1][0])
        {
            \think\Request::instance()->module('admin');
            $model = model($matches[1][0]);
            if (in_array('trashed', get_class_methods($model)))
            {
                $withSofeDelete = true;
            }
        }
Karson authored
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        //忽略的类
        if (stripos($classComment, "@internal") !== FALSE)
        {
            return;
        }
        preg_match_all('#(@.*?)\n#s', $classComment, $annotations);
        $controllerIcon = 'fa fa-circle-o';
        $controllerRemark = '';
        //判断注释中是否设置了icon值
        if (isset($annotations[1]))
        {
            foreach ($annotations[1] as $tag)
            {
                if (stripos($tag, '@icon') !== FALSE)
                {
                    $controllerIcon = substr($tag, stripos($tag, ' ') + 1);
                }
                if (stripos($tag, '@remark') !== FALSE)
                {
                    $controllerRemark = substr($tag, stripos($tag, ' ') + 1);
                }
            }
        }
        //过滤掉其它字符
226
        $controllerTitle = trim(preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $classComment));
Karson authored
227 228 229

        //导入中文语言包
        \think\Lang::load(dirname(__DIR__) . DS . 'lang/zh-cn.php');
230
Karson authored
231
        //先导入菜单的数据
Karson authored
232
        $pid = 0;
Karson authored
233
        foreach ($controllerArr as $k => $v)
Karson authored
234
        {
Karson authored
235 236 237 238 239
            $key = $k + 1;
            $name = strtolower(implode('/', array_slice($controllerArr, 0, $key)));
            $title = (!isset($controllerArr[$key]) ? $controllerTitle : '');
            $icon = (!isset($controllerArr[$key]) ? $controllerIcon : 'fa fa-list');
            $remark = (!isset($controllerArr[$key]) ? $controllerRemark : '');
240
            $title = $title ? $title : $v;
Karson authored
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
            $rulemodel = $this->model->get(['name' => $name]);
            if (!$rulemodel)
            {
                $this->model
                        ->data(['pid' => $pid, 'name' => $name, 'title' => $title, 'icon' => $icon, 'remark' => $remark, 'ismenu' => 1, 'status' => 'normal'])
                        ->isUpdate(false)
                        ->save();
                $pid = $this->model->id;
            }
            else
            {
                $pid = $rulemodel->id;
            }
        }
        $ruleArr = [];
        foreach ($methods as $m => $n)
        {
            //过滤特殊的类
            if (substr($n->name, 0, 2) == '__' || $n->name == '_initialize')
            {
                continue;
            }
Karson authored
263 264 265 266 267
            //未启用软删除时过滤相关方法
            if (!$withSofeDelete && in_array($n->name, $softDeleteMethods))
            {
                continue;
            }
Karson authored
268 269 270 271 272 273 274 275 276 277 278 279 280
            //只匹配符合的方法
            if (!preg_match('/^(\w+)' . Config::get('action_suffix') . '/', $n->name, $matchtwo))
            {
                unset($methods[$m]);
                continue;
            }
            $comment = $reflector->getMethod($n->name)->getDocComment();
            //忽略的方法
            if (stripos($comment, "@internal") !== FALSE)
            {
                continue;
            }
            //过滤掉其它字符
Karson authored
281
            $comment = preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $comment);
282
283
            $title = $comment ? $comment : ucfirst($n->name);
284 285 286 287 288

            //获取主键,作为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
289
        }
290
        $this->model->isUpdate(false)->saveAll($ruleArr);
Karson authored
291 292
    }
293
    //获取主键
294 295
    protected function getAuthRulePK($name)
    {
296 297
        if (!empty($name))
        {
298 299 300 301
            $id = $this->model
                    ->where('name', $name)
                    ->value('id');
            return $id ? $id : null;
302 303 304
        }
    }
Karson authored
305
}