控制台应用,yzncms本身基于tp5.1框架,里面的队列用不了,bug,坑
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Menu.php 11KB

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