Menu.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // | Original reference: https://gitee.com/karson/fastadmin
  12. // +----------------------------------------------------------------------
  13. // +----------------------------------------------------------------------
  14. // | 菜单主程序
  15. // +----------------------------------------------------------------------
  16. namespace app\admin\command;
  17. use app\admin\model\AuthRule;
  18. use ReflectionClass;
  19. use ReflectionMethod;
  20. use think\console\Command;
  21. use think\console\Input;
  22. use think\console\input\Option;
  23. use think\console\Output;
  24. use think\Exception;
  25. use think\facade\Cache;
  26. use think\facade\Config;
  27. class Menu extends Command
  28. {
  29. protected $model = null;
  30. protected function configure()
  31. {
  32. $this
  33. ->setName('menu')
  34. ->addOption('controller', 'c', Option::VALUE_REQUIRED | Option::VALUE_IS_ARRAY, 'controller name,use \'all-controller\' when build all menu', null)
  35. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete the specified menu', '')
  36. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force delete menu,without tips', null)
  37. ->addOption('equal', 'e', Option::VALUE_OPTIONAL, 'the controller must be equal', null)
  38. ->setDescription('Build auth menu from controller');
  39. //要执行的controller必须一样,不适用模糊查询
  40. }
  41. protected function execute(Input $input, Output $output)
  42. {
  43. $this->model = new AuthRule();
  44. $adminPath = dirname(__DIR__) . DS;
  45. //控制器名
  46. $controller = $input->getOption('controller') ?: '';
  47. if (!$controller) {
  48. throw new Exception("please input controller name");
  49. }
  50. $force = $input->getOption('force');
  51. //是否为删除模式
  52. $delete = $input->getOption('delete');
  53. //是否控制器完全匹配
  54. $equal = $input->getOption('equal');
  55. if ($delete) {
  56. $ids = [];
  57. $list = $this->model->where(function ($query) use ($controller, $equal) {
  58. foreach ($controller as $index => $item) {
  59. if (stripos($item, '_') !== false) {
  60. $item = parse_name($item, 1);
  61. }
  62. if (stripos($item, '/') !== false) {
  63. $controllerArr = explode('/', $item);
  64. end($controllerArr);
  65. $key = key($controllerArr);
  66. $controllerArr[$key] = parse_name($controllerArr[$key]);
  67. } else {
  68. $controllerArr = [parse_name($item)];
  69. }
  70. $item = str_replace('_', '\_', implode('.', $controllerArr));
  71. if ($equal) {
  72. $query->whereOr('name', 'eq', $item);
  73. } else {
  74. $query->whereOr('name', 'like', strtolower($item) . "%");
  75. }
  76. }
  77. })->select();
  78. foreach ($list as $k => $v) {
  79. $output->warning($v->name);
  80. $ids[] = $v->id;
  81. }
  82. if (!$ids) {
  83. throw new Exception("There is no menu to delete");
  84. }
  85. if (!$force) {
  86. $question = $output->confirm($input, "Are you sure you want to delete all those menu? Type 'yes' to continue: ", false);
  87. if (!$question) {
  88. throw new Exception("Operation is aborted!");
  89. }
  90. }
  91. AuthRule::destroy($ids);
  92. Cache::delete("__menu__");
  93. $output->info("Delete Successed");
  94. return;
  95. }
  96. foreach ($controller as $index => $item) {
  97. if (stripos($item, '_') !== false) {
  98. $item = parse_name($item, 1);
  99. }
  100. if (stripos($item, '/') !== false) {
  101. $controllerArr = explode('/', $item);
  102. end($controllerArr);
  103. $key = key($controllerArr);
  104. $controllerArr[$key] = ucfirst($controllerArr[$key]);
  105. } else {
  106. $controllerArr = [ucfirst($item)];
  107. }
  108. $adminPath = dirname(__DIR__) . DS . 'controller' . DS . implode(DS, $controllerArr) . '.php';
  109. if (!is_file($adminPath)) {
  110. $output->error("controller not found");
  111. return;
  112. }
  113. $this->importRule($item);
  114. }
  115. Cache::delete("__menu__");
  116. $output->info("Build Successed!");
  117. }
  118. protected function importRule($controller)
  119. {
  120. $controller = str_replace('\\', '/', $controller);
  121. if (stripos($controller, '/') !== false) {
  122. $controllerArr = explode('/', $controller);
  123. end($controllerArr);
  124. $key = key($controllerArr);
  125. $controllerArr[$key] = ucfirst($controllerArr[$key]);
  126. } else {
  127. $key = 0;
  128. $controllerArr = [ucfirst($controller)];
  129. }
  130. $classSuffix = Config::get('route.controller_suffix') ? ucfirst(Config::get('route.url_controller_layer')) : '';
  131. $className = "\\app\\admin\\controller\\" . implode("\\", $controllerArr) . $classSuffix;
  132. $pathArr = $controllerArr;
  133. array_unshift($pathArr, '', 'app', 'admin', 'controller');
  134. $classFile = app()->getRootPath() . implode(DS, $pathArr) . $classSuffix . ".php";
  135. $classContent = file_get_contents($classFile);
  136. $uniqueName = uniqid("YznCMS") . $classSuffix;
  137. $classContent = str_replace("class " . $controllerArr[$key] . $classSuffix . " ", 'class ' . $uniqueName . ' ', $classContent);
  138. $classContent = preg_replace("/namespace\s(.*);/", 'namespace ' . __NAMESPACE__ . ";", $classContent);
  139. //临时的类文件
  140. $tempClassFile = __DIR__ . DS . $uniqueName . ".php";
  141. file_put_contents($tempClassFile, $classContent);
  142. $className = "\\app\\admin\\command\\" . $uniqueName;
  143. //删除临时文件
  144. register_shutdown_function(function () use ($tempClassFile) {
  145. if ($tempClassFile) {
  146. //删除临时文件
  147. @unlink($tempClassFile);
  148. }
  149. });
  150. //反射机制调用类的注释和方法名
  151. $reflector = new ReflectionClass($className);
  152. //只匹配公共的方法
  153. $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
  154. $classComment = $reflector->getDocComment();
  155. //判断是否有启用软删除
  156. $softDeleteMethods = ['destroy', 'restore', 'recyclebin'];
  157. $withSofeDelete = false;
  158. $modelRegexArr = ["/\\\$this\->model\s*=\s*model\(['|\"](\w+)['|\"]\);/", "/\\\$this\->model\s*=\s*new\s+([a-zA-Z\\\]+);/"];
  159. $modelRegex = preg_match($modelRegexArr[0], $classContent) ? $modelRegexArr[0] : $modelRegexArr[1];
  160. preg_match_all($modelRegex, $classContent, $matches);
  161. if (isset($matches[1]) && isset($matches[1][0]) && $matches[1][0]) {
  162. $model = model($matches[1][0]);
  163. if (in_array('trashed', get_class_methods($model))) {
  164. $withSofeDelete = true;
  165. }
  166. }
  167. //忽略的类
  168. if (stripos($classComment, "@internal") !== false) {
  169. return;
  170. }
  171. preg_match_all('#(@.*?)\n#s', $classComment, $annotations);
  172. $controllerIcon = 'iconfont icon-list-unordered';
  173. $controllerRemark = '';
  174. //判断注释中是否设置了icon值
  175. if (isset($annotations[1])) {
  176. foreach ($annotations[1] as $tag) {
  177. if (stripos($tag, '@icon') !== false) {
  178. $controllerIcon = substr($tag, stripos($tag, ' ') + 1);
  179. }
  180. if (stripos($tag, '@remark') !== false) {
  181. $controllerRemark = substr($tag, stripos($tag, ' ') + 1);
  182. }
  183. }
  184. }
  185. //过滤掉其它字符
  186. $controllerTitle = trim(preg_replace(['/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'], '', $classComment));
  187. //先导入菜单的数据
  188. $pid = 0;
  189. foreach ($controllerArr as $k => $v) {
  190. $key = $k + 1;
  191. //驼峰转下划线
  192. $controllerNameArr = array_slice($controllerArr, 0, $key);
  193. foreach ($controllerNameArr as &$val) {
  194. $val = strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $val), "_"));
  195. }
  196. unset($val);
  197. $name = implode('.', $controllerNameArr);
  198. $title = (!isset($controllerArr[$key]) ? $controllerTitle : '');
  199. $icon = (!isset($controllerArr[$key]) ? $controllerIcon : 'iconfont icon-list-unordered');
  200. $remark = (!isset($controllerArr[$key]) ? $controllerRemark : '');
  201. $title = $title ? $title : $v;
  202. $rulemodel = $this->model->where('name', $name)->find();
  203. if (!$rulemodel) {
  204. $pid = $this->model
  205. ->insertGetId([
  206. 'parentid' => $pid,
  207. 'name' => $name,
  208. 'title' => $title,
  209. 'icon' => $icon,
  210. 'remark' => $remark,
  211. 'ismenu' => 1,
  212. 'status' => 1,
  213. ]);
  214. } else {
  215. $pid = $rulemodel->id;
  216. }
  217. }
  218. $ruleArr = [];
  219. foreach ($methods as $m => $n) {
  220. //过滤特殊的类
  221. if (in_array($n->name, ['initialize', '_empty', 'registerMiddleware']) || substr($n->name, 0, 2) == '__') {
  222. continue;
  223. }
  224. //未启用软删除时过滤相关方法
  225. if (!$withSofeDelete && in_array($n->name, $softDeleteMethods)) {
  226. continue;
  227. }
  228. //只匹配符合的方法
  229. if (!preg_match('/^(\w+)' . Config::get('route.action_suffix') . '/', $n->name, $matchtwo)) {
  230. unset($methods[$m]);
  231. continue;
  232. }
  233. $comment = $reflector->getMethod($n->name)->getDocComment();
  234. //忽略的方法
  235. if (stripos($comment, "@internal") !== false) {
  236. continue;
  237. }
  238. //过滤掉其它字符
  239. $comment = preg_replace(['/^\/\*\*(.*)[\n\r\t]/u', '/[\s]+\*\//u', '/\*\s@(.*)/u', '/[\s|\*]+/u'], '', $comment);
  240. $title = $comment ? $comment : ucfirst($n->name);
  241. //获取主键,作为AuthRule更新依据
  242. $id = $this->getAuthRulePK($name . "/" . strtolower($n->name));
  243. $ruleArr[] = ['id' => $id, 'parentid' => $pid, 'name' => $name . "/" . strtolower($n->name), 'icon' => 'iconfont icon-circle-line', 'title' => $title, 'ismenu' => 0, 'status' => 1];
  244. }
  245. $this->model->insertAll($ruleArr);
  246. }
  247. //获取主键
  248. protected function getAuthRulePK($name)
  249. {
  250. if (!empty($name)) {
  251. $id = $this->model
  252. ->where('name', $name)
  253. ->value('id');
  254. return $id ? $id : null;
  255. }
  256. }
  257. }