Example #1
0
 /**
  * Assign route to role via permission and create permission or route if it don't exists
  * Helper mainly for migrations
  *
  * @param string      $roleName
  * @param string      $permissionName
  * @param array       $routes
  * @param null|string $permissionDescription
  * @param null|string $groupCode
  *
  * @throws \InvalidArgumentException
  * @return true|static|string
  */
 public static function assignRoutesViaPermission($roleName, $permissionName, $routes, $permissionDescription = null, $groupCode = null)
 {
     $role = static::findOne(['name' => $roleName]);
     if (!$role) {
         throw new \InvalidArgumentException("Role with name = {$roleName} not found");
     }
     $permission = Permission::findOne(['name' => $permissionName]);
     if (!$permission) {
         $permission = Permission::create($permissionName, $permissionDescription, $groupCode);
         if ($permission->hasErrors()) {
             return $permission;
         }
     }
     try {
         Yii::$app->db->createCommand()->insert(Yii::$app->getModule('user-management')->auth_item_child_table, ['parent' => $role->name, 'child' => $permission->name])->execute();
     } catch (Exception $e) {
         // Don't throw Exception because we may have this permission for this role,
         // but need to add new routes to it
     }
     $routes = (array) $routes;
     foreach ($routes as $route) {
         Route::create($route);
         try {
             Yii::$app->db->createCommand()->insert(Yii::$app->getModule('user-management')->auth_item_child_table, ['parent' => $permission->name, 'child' => $route])->execute();
         } catch (Exception $e) {
             // Don't throw Exception because this permission may already have this route,
             // so just go to the next route
         }
     }
     AuthHelper::invalidatePermissions();
     return true;
 }
Example #2
0
 /**
  * Refresh list of all routes from controllers, modules, etc
  */
 public static function refreshRoutes()
 {
     $allRoutes = AuthHelper::getRoutes();
     $currentRoutes = ArrayHelper::map(Route::find()->asArray()->all(), 'name', 'name');
     $toAdd = array_diff(array_keys($allRoutes), array_keys($currentRoutes));
     $toRemove = array_diff(array_keys($currentRoutes), array_keys($allRoutes));
     foreach ($toAdd as $addItem) {
         Route::create($addItem);
     }
     if ($toRemove) {
         Route::deleteAll(['in', 'name', $toRemove]);
     }
     if ($toAdd or $toRemove) {
         Yii::$app->cache->delete('__commonRoutes');
     }
 }