RouteController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. namespace common\modules\rbac\controllers;
  3. use Exception;
  4. use common\modules\rbac\components\Configs;
  5. use common\modules\rbac\components\MenuHelper;
  6. use common\modules\rbac\components\RouteRule;
  7. use common\modules\rbac\models\Route;
  8. use Yii;
  9. use yii\caching\TagDependency;
  10. use yii\helpers\Inflector;
  11. use yii\helpers\VarDumper;
  12. use yii\web\Response;
  13. /**
  14. * Description of RuleController.
  15. *
  16. * @author Misbahul D Munir <misbahuldmunir@gmail.com>
  17. *
  18. * @since 1.0
  19. */
  20. class RouteController extends \yii\web\Controller
  21. {
  22. const CACHE_TAG = 'mdm.admin.route';
  23. /**
  24. * Lists all Route models.
  25. *
  26. * @return mixed
  27. */
  28. public function actionIndex()
  29. {
  30. return $this->render('index');
  31. }
  32. /**
  33. * Creates a new AuthItem model.
  34. * If creation is successful, the browser will be redirected to the 'view' page.
  35. *
  36. * @return mixed
  37. */
  38. public function actionCreate()
  39. {
  40. $model = new Route();
  41. if ($model->load(Yii::$app->getRequest()->post())) {
  42. if ($model->validate()) {
  43. $routes = preg_split('/\s*,\s*/', trim($model->route), -1, PREG_SPLIT_NO_EMPTY);
  44. $this->saveNew($routes);
  45. MenuHelper::invalidate();
  46. $this->redirect(['index']);
  47. }
  48. }
  49. return $this->render('create', ['model' => $model]);
  50. }
  51. /**
  52. * Assign or remove items.
  53. *
  54. * @param string $action
  55. *
  56. * @return array
  57. */
  58. public function actionAssign()
  59. {
  60. $post = Yii::$app->getRequest()->post();
  61. $action = $post['action'];
  62. $routes = $post['routes'];
  63. $manager = Yii::$app->getAuthManager();
  64. $error = [];
  65. if ($action == 'assign') {
  66. $this->saveNew($routes);
  67. } else {
  68. foreach ($routes as $route) {
  69. $child = $manager->getPermission($route);
  70. try {
  71. $manager->remove($child);
  72. } catch (Exception $exc) {
  73. $error[] = $exc->getMessage();
  74. }
  75. }
  76. }
  77. MenuHelper::invalidate();
  78. Yii::$app->getResponse()->format = Response::FORMAT_JSON;
  79. return[
  80. 'type' => 'S',
  81. 'errors' => $error,
  82. ];
  83. }
  84. /**
  85. * Search Route.
  86. *
  87. * @param string $target
  88. * @param string $term
  89. * @param string $refresh
  90. *
  91. * @return array
  92. */
  93. public function actionSearch($target, $term = '', $refresh = '0')
  94. {
  95. if ($refresh == '1') {
  96. $this->invalidate();
  97. }
  98. $result = [];
  99. $manager = Yii::$app->getAuthManager();
  100. $exists = array_keys($manager->getPermissions());
  101. $routes = $this->getAppRoutes();
  102. if ($target == 'avaliable') {
  103. foreach ($routes as $route) {
  104. if (in_array($route, $exists)) {
  105. continue;
  106. }
  107. if (empty($term) or strpos($route, $term) !== false) {
  108. $result[$route] = true;
  109. }
  110. }
  111. } else {
  112. foreach ($exists as $name) {
  113. if ($name[0] !== '/') {
  114. continue;
  115. }
  116. if (empty($term) or strpos($name, $term) !== false) {
  117. $r = explode('&', $name);
  118. $result[$name] = !empty($r[0]) && in_array($r[0], $routes);
  119. }
  120. }
  121. }
  122. Yii::$app->response->format = 'json';
  123. return $result;
  124. }
  125. /**
  126. * Save one or more route(s).
  127. *
  128. * @param array $routes
  129. */
  130. private function saveNew($routes)
  131. {
  132. $manager = Yii::$app->getAuthManager();
  133. foreach ($routes as $route) {
  134. try {
  135. $r = explode('&', $route);
  136. $item = $manager->createPermission('/'.trim($route, '/'));
  137. if (count($r) > 1) {
  138. $action = '/'.trim($r[0], '/');
  139. if (($itemAction = $manager->getPermission($action)) === null) {
  140. $itemAction = $manager->createPermission($action);
  141. $manager->add($itemAction);
  142. }
  143. unset($r[0]);
  144. foreach ($r as $part) {
  145. $part = explode('=', $part);
  146. $item->data['params'][$part[0]] = isset($part[1]) ? $part[1] : '';
  147. }
  148. $this->setDefaultRule();
  149. $item->ruleName = RouteRule::RULE_NAME;
  150. $manager->add($item);
  151. $manager->addChild($item, $itemAction);
  152. } else {
  153. $manager->add($item);
  154. }
  155. } catch (Exception $e) {
  156. }
  157. }
  158. }
  159. /**
  160. * Get list of application routes.
  161. *
  162. * @return array
  163. */
  164. public function getAppRoutes()
  165. {
  166. $key = __METHOD__;
  167. $cache = Configs::instance()->cache;
  168. $cache = null;
  169. if ($cache === null || ($result = $cache->get($key)) === false) {
  170. $result = [];
  171. $this->getRouteRecrusive(Yii::$app, $result);
  172. if ($cache !== null) {
  173. $cache->set($key, $result, Configs::instance()->cacheDuration, new TagDependency([
  174. 'tags' => self::CACHE_TAG,
  175. ]));
  176. }
  177. }
  178. return $result;
  179. }
  180. /**
  181. * Get route(s) recrusive.
  182. *
  183. * @param \yii\base\Module $module
  184. * @param array $result
  185. */
  186. private function getRouteRecrusive($module, &$result)
  187. {
  188. $token = "Get Route of '".get_class($module)."' with id '".$module->uniqueId."'";
  189. Yii::beginProfile($token, __METHOD__);
  190. try {
  191. foreach ($module->getModules() as $id => $child) {
  192. if (($child = $module->getModule($id)) !== null) {
  193. $this->getRouteRecrusive($child, $result);
  194. }
  195. }
  196. foreach ($module->controllerMap as $id => $type) {
  197. $this->getControllerActions($type, $id, $module, $result);
  198. }
  199. $namespace = trim($module->controllerNamespace, '\\').'\\';
  200. $this->getControllerFiles($module, $namespace, '', $result);
  201. if ($module->uniqueId === '') {
  202. $result[] = '/*';
  203. }
  204. } catch (\Exception $exc) {
  205. Yii::error($exc->getMessage(), __METHOD__);
  206. }
  207. Yii::endProfile($token, __METHOD__);
  208. }
  209. /**
  210. * Get list controller under module.
  211. *
  212. * @param \yii\base\Module $module
  213. * @param string $namespace
  214. * @param string $prefix
  215. * @param mixed $result
  216. *
  217. * @return mixed
  218. */
  219. private function getControllerFiles($module, $namespace, $prefix, &$result)
  220. {
  221. $path = @Yii::getAlias('@'.str_replace('\\', '/', $namespace));
  222. $token = "Get controllers from '$path'";
  223. Yii::beginProfile($token, __METHOD__);
  224. try {
  225. if (!is_dir($path)) {
  226. return;
  227. }
  228. foreach (scandir($path) as $file) {
  229. if ($file == '.' || $file == '..') {
  230. continue;
  231. }
  232. if (is_dir($path.'/'.$file)) {
  233. $this->getControllerFiles($module, $namespace.$file.'\\', $prefix.$file.'/', $result);
  234. } elseif (strcmp(substr($file, -14), 'Controller.php') === 0) {
  235. $id = Inflector::camel2id(substr(basename($file), 0, -14));
  236. $className = $namespace.Inflector::id2camel($id).'Controller';
  237. if (strpos($className, '-') === false && class_exists($className) && is_subclass_of($className, 'yii\base\Controller')) {
  238. $this->getControllerActions($className, $prefix.$id, $module, $result);
  239. }
  240. }
  241. }
  242. } catch (\Exception $exc) {
  243. Yii::error($exc->getMessage(), __METHOD__);
  244. }
  245. Yii::endProfile($token, __METHOD__);
  246. }
  247. /**
  248. * Get list action of controller.
  249. *
  250. * @param mixed $type
  251. * @param string $id
  252. * @param \yii\base\Module $module
  253. * @param string $result
  254. */
  255. private function getControllerActions($type, $id, $module, &$result)
  256. {
  257. $token = 'Create controller with cofig='.VarDumper::dumpAsString($type)." and id='$id'";
  258. Yii::beginProfile($token, __METHOD__);
  259. try {
  260. /* @var $controller \yii\base\Controller */
  261. $controller = Yii::createObject($type, [$id, $module]);
  262. $this->getActionRoutes($controller, $result);
  263. // $result[] = '/'.$controller->uniqueId.'/*';
  264. } catch (\Exception $exc) {
  265. Yii::error($exc->getMessage(), __METHOD__);
  266. }
  267. Yii::endProfile($token, __METHOD__);
  268. }
  269. /**
  270. * Get route of action.
  271. *
  272. * @param \yii\base\Controller $controller
  273. * @param array $result all controller action.
  274. */
  275. private function getActionRoutes($controller, &$result)
  276. {
  277. $token = "Get actions of controller '".$controller->uniqueId."'";
  278. Yii::beginProfile($token, __METHOD__);
  279. try {
  280. $prefix = '/'.$controller->uniqueId.'/';
  281. foreach ($controller->actions() as $id => $value) {
  282. $result[] = $prefix.$id;
  283. }
  284. $class = new \ReflectionClass($controller);
  285. foreach ($class->getMethods() as $method) {
  286. $name = $method->getName();
  287. if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') {
  288. $result[] = $prefix.Inflector::camel2id(substr($name, 6));
  289. }
  290. }
  291. } catch (\Exception $exc) {
  292. Yii::error($exc->getMessage(), __METHOD__);
  293. }
  294. Yii::endProfile($token, __METHOD__);
  295. }
  296. /**
  297. * Ivalidate cache.
  298. */
  299. protected function invalidate()
  300. {
  301. if (Configs::instance()->cache !== null) {
  302. TagDependency::invalidate(Configs::instance()->cache, self::CACHE_TAG);
  303. }
  304. }
  305. /**
  306. * Set default rule of parameterize route.
  307. */
  308. protected function setDefaultRule()
  309. {
  310. if (Yii::$app->authManager->getRule(RouteRule::RULE_NAME) === null) {
  311. Yii::$app->authManager->add(Yii::createObject([
  312. 'class' => RouteRule::className(),
  313. 'name' => RouteRule::RULE_NAME, ]
  314. ));
  315. }
  316. }
  317. }