Menu.php 9.2 KB

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