Menu.php 10 KB

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