yii\rbac\PhpManager::assign PHP Method

assign() public method

public assign ( $role, $userId )
    public function assign($role, $userId)
    {
        if (!isset($this->items[$role->name])) {
            throw new InvalidParamException("Unknown role '{$role->name}'.");
        } elseif (isset($this->assignments[$userId][$role->name])) {
            throw new InvalidParamException("Authorization item '{$role->name}' has already been assigned to user '{$userId}'.");
        } else {
            $this->assignments[$userId][$role->name] = new Assignment(['userId' => $userId, 'roleName' => $role->name, 'createdAt' => time()]);
            $this->saveAssignments();
            return $this->assignments[$userId][$role->name];
        }
    }

Usage Example

Example #1
0
 /**
  * Непосредственно привязка роли к юзеру
  *
  * @param $userid
  *
  * @return bool|string
  */
 public function userAssign($userid)
 {
     $role = $this->getItem($this->forassign, self::TYPE_ROLE);
     $oldroles = $this->_authMan->getRolesByUser($userid);
     $this->_authMan->revokeAll($userid);
     try {
         if ($this->beforeAssign($userid, $role, $oldroles)) {
             $this->_authMan->assign($role, $userid);
             $this->afterAssign($userid, $role, $oldroles);
             return true;
         } else {
             return false;
         }
     } catch (\yii\base\Exception $e) {
         foreach ($oldroles as $orole) {
             $this->_authMan->assign($orole, $userid);
         }
         return RbacModule::t('simplerbac', 'Can`t assign this item for this user');
     }
 }