Menu.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <?php
  2. namespace app\admin\command;
  3. use app\admin\model\AuthRule;
  4. use ReflectionClass;
  5. use ReflectionMethod;
  6. use think\Cache;
  7. use think\Config;
  8. use think\console\Command;
  9. use think\console\Input;
  10. use think\console\input\Option;
  11. use think\console\Output;
  12. use think\Exception;
  13. class Menu extends Command
  14. {
  15. protected $model = null;
  16. protected function configure()
  17. {
  18. $this
  19. ->setName('menu')
  20. ->addOption('controller', 'c', Option::VALUE_REQUIRED, 'controller name,use \'all-controller\' when build all menu', null)
  21. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete the specified menu', '')
  22. ->setDescription('Build auth menu from controller');
  23. }
  24. protected function execute(Input $input, Output $output)
  25. {
  26. $this->model = new AuthRule();
  27. $adminPath = dirname(__DIR__) . DS;
  28. //控制器名
  29. $controller = $input->getOption('controller') ?: '';
  30. if (!$controller)
  31. {
  32. throw new Exception("please input controller name");
  33. }
  34. //是否为删除模式
  35. $delete = $input->getOption('delete');
  36. if ($delete)
  37. {
  38. if ($controller == 'all-controller')
  39. {
  40. throw new Exception("could not delete all menu");
  41. }
  42. $ids = [];
  43. $list = $this->model->where('name', 'like', strtolower($controller) . "%")->select();
  44. foreach ($list as $k => $v)
  45. {
  46. $output->warning($v->name);
  47. $ids[] = $v->id;
  48. }
  49. if (!$ids)
  50. {
  51. throw new Exception("There is no menu to delete");
  52. }
  53. $readyMenu = [];
  54. $output->info("Are you sure you want to delete all those menu? Type 'yes' to continue: ");
  55. $line = fgets(STDIN);
  56. if (trim($line) != 'yes')
  57. {
  58. throw new Exception("Operation is aborted!");
  59. }
  60. AuthRule::destroy($ids);
  61. Cache::rm("__menu__");
  62. $output->info("Delete Successed");
  63. return;
  64. }
  65. if ($controller != 'all-controller')
  66. {
  67. $controllerArr = explode('/', $controller);
  68. end($controllerArr);
  69. $key = key($controllerArr);
  70. $controllerArr[$key] = ucfirst($controllerArr[$key]);
  71. $adminPath = dirname(__DIR__) . DS . 'controller' . DS . implode(DS, $controllerArr) . '.php';
  72. if (!is_file($adminPath))
  73. {
  74. $output->error("controller not found");
  75. return;
  76. }
  77. $this->importRule($controller);
  78. }
  79. else
  80. {
  81. $this->model->where('id', '>', 0)->delete();
  82. $controllerDir = $adminPath . 'controller' . DS;
  83. // 扫描新的节点信息并导入
  84. $treelist = $this->import($this->scandir($controllerDir));
  85. }
  86. Cache::rm("__menu__");
  87. $output->info("Build Successed!");
  88. }
  89. /**
  90. * 递归扫描文件夹
  91. * @param string $dir
  92. * @return array
  93. */
  94. public function scandir($dir)
  95. {
  96. $result = [];
  97. $cdir = scandir($dir);
  98. foreach ($cdir as $value)
  99. {
  100. if (!in_array($value, array(".", "..")))
  101. {
  102. if (is_dir($dir . DS . $value))
  103. {
  104. $result[$value] = $this->scandir($dir . DS . $value);
  105. }
  106. else
  107. {
  108. $result[] = $value;
  109. }
  110. }
  111. }
  112. return $result;
  113. }
  114. /**
  115. * 导入规则节点
  116. * @param array $dirarr
  117. * @param array $parentdir
  118. * @return array
  119. */
  120. public function import($dirarr, $parentdir = [])
  121. {
  122. $menuarr = [];
  123. foreach ($dirarr as $k => $v)
  124. {
  125. if (is_array($v))
  126. {
  127. //当前是文件夹
  128. $nowparentdir = array_merge($parentdir, [$k]);
  129. $this->import($v, $nowparentdir);
  130. }
  131. else
  132. {
  133. //只匹配PHP文件
  134. if (!preg_match('/^(\w+)\.php$/', $v, $matchone))
  135. {
  136. continue;
  137. }
  138. //导入文件
  139. $controller = ($parentdir ? implode('/', $parentdir) . '/' : '') . $matchone[1];
  140. $this->importRule($controller);
  141. }
  142. }
  143. return $menuarr;
  144. }
  145. protected function importRule($controller)
  146. {
  147. $controllerArr = explode('/', $controller);
  148. end($controllerArr);
  149. $key = key($controllerArr);
  150. $controllerArr[$key] = ucfirst($controllerArr[$key]);
  151. $classSuffix = Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : '';
  152. $className = "\\app\\admin\\controller\\" . implode("\\", $controllerArr) . $classSuffix;
  153. $pathArr = $controllerArr;
  154. array_unshift($pathArr, '', 'application', 'admin', 'controller');
  155. $classFile = ROOT_PATH . implode(DS, $pathArr) . $classSuffix . ".php";
  156. $classContent = file_get_contents($classFile);
  157. $uniqueName = uniqid("FastAdmin") . $classSuffix;
  158. $classContent = str_replace("class " . $controllerArr[$key] . $classSuffix . " ", 'class ' . $uniqueName . ' ', $classContent);
  159. $classContent = preg_replace("/namespace\s(.*);/", 'namespace ' . __NAMESPACE__ . ";", $classContent);
  160. //临时的类文件
  161. $tempClassFile = __DIR__ . DS . $uniqueName . ".php";
  162. file_put_contents($tempClassFile, $classContent);
  163. $className = "\\app\\admin\\command\\" . $uniqueName;
  164. //反射机制调用类的注释和方法名
  165. $reflector = new ReflectionClass($className);
  166. if (isset($tempClassFile))
  167. {
  168. //删除临时文件
  169. @unlink($tempClassFile);
  170. }
  171. //只匹配公共的方法
  172. $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
  173. $classComment = $reflector->getDocComment();
  174. //忽略的类
  175. if (stripos($classComment, "@internal") !== FALSE)
  176. {
  177. return;
  178. }
  179. preg_match_all('#(@.*?)\n#s', $classComment, $annotations);
  180. $controllerIcon = 'fa fa-circle-o';
  181. $controllerRemark = '';
  182. //判断注释中是否设置了icon值
  183. if (isset($annotations[1]))
  184. {
  185. foreach ($annotations[1] as $tag)
  186. {
  187. if (stripos($tag, '@icon') !== FALSE)
  188. {
  189. $controllerIcon = substr($tag, stripos($tag, ' ') + 1);
  190. }
  191. if (stripos($tag, '@remark') !== FALSE)
  192. {
  193. $controllerRemark = substr($tag, stripos($tag, ' ') + 1);
  194. }
  195. }
  196. }
  197. //过滤掉其它字符
  198. $controllerTitle = trim(preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $classComment));
  199. //导入中文语言包
  200. \think\Lang::load(dirname(__DIR__) . DS . 'lang/zh-cn.php');
  201. //先定入菜单的数据
  202. $pid = 0;
  203. foreach ($controllerArr as $k => $v)
  204. {
  205. $key = $k + 1;
  206. $name = strtolower(implode('/', array_slice($controllerArr, 0, $key)));
  207. $title = (!isset($controllerArr[$key]) ? $controllerTitle : '');
  208. $icon = (!isset($controllerArr[$key]) ? $controllerIcon : 'fa fa-list');
  209. $remark = (!isset($controllerArr[$key]) ? $controllerRemark : '');
  210. $title = $title ? $title : $v;
  211. $rulemodel = $this->model->get(['name' => $name]);
  212. if (!$rulemodel)
  213. {
  214. $this->model
  215. ->data(['pid' => $pid, 'name' => $name, 'title' => $title, 'icon' => $icon, 'remark' => $remark, 'ismenu' => 1, 'status' => 'normal'])
  216. ->isUpdate(false)
  217. ->save();
  218. $pid = $this->model->id;
  219. }
  220. else
  221. {
  222. $pid = $rulemodel->id;
  223. }
  224. }
  225. $ruleArr = [];
  226. foreach ($methods as $m => $n)
  227. {
  228. //过滤特殊的类
  229. if (substr($n->name, 0, 2) == '__' || $n->name == '_initialize')
  230. {
  231. continue;
  232. }
  233. //只匹配符合的方法
  234. if (!preg_match('/^(\w+)' . Config::get('action_suffix') . '/', $n->name, $matchtwo))
  235. {
  236. unset($methods[$m]);
  237. continue;
  238. }
  239. $comment = $reflector->getMethod($n->name)->getDocComment();
  240. //忽略的方法
  241. if (stripos($comment, "@internal") !== FALSE)
  242. {
  243. continue;
  244. }
  245. //过滤掉其它字符
  246. $comment = preg_replace(array('/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'), '', $comment);
  247. $title = $comment ? $comment : ucfirst($n->name);
  248. //获取主键,作为AuthRule更新依据
  249. $id = $this->getAuthRulePK($name . "/" . strtolower($n->name));
  250. $ruleArr[] = array('id' => $id, 'pid' => $pid, 'name' => $name . "/" . strtolower($n->name), 'icon' => 'fa fa-circle-o', 'title' => $title, 'ismenu' => 0, 'status' => 'normal');
  251. }
  252. $this->model->isUpdate(false)->saveAll($ruleArr);
  253. }
  254. //获取主键
  255. protected function getAuthRulePK($name)
  256. {
  257. if (!empty($name))
  258. {
  259. $id = $this->model
  260. ->where('name', $name)
  261. ->value('id');
  262. return $id ? $id : null;
  263. }
  264. }
  265. }