Menu.php 10 KB

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