類別 yii\rbac\DbManager
DbManager 代表一個授權管理器,將授權資訊儲存在資料庫中。
資料庫連線由 $db 指定。資料庫結構可以透過套用遷移來初始化
yii migrate --migrationPath=@yii/rbac/migrations/
如果您不想使用遷移,而是需要 SQL,所有資料庫的檔案都在 migrations 目錄中。
您可以透過設定 $itemTable、$itemChildTable、$assignmentTable 和 $ruleTable 來變更用於儲存授權和規則資料的表格名稱。
有關 DbManager 的更多詳細資訊和使用方法,請參閱關於安全授權的指南文章。
公開屬性
公用方法
受保護的方法
屬性詳細資訊
儲存授權項目指派的表格名稱。預設為 "auth_assignment"。
用於提升 RBAC 效能的快取。這可以是下列其中之一
- 應用程式元件 ID (例如
cache
) - 組態陣列
- yii\caching\Cache 物件
當未設定此項時,表示未啟用快取。
請注意,透過啟用 RBAC 快取,所有授權項目、規則和授權項目父子關係都將被快取並載入記憶體。這將提升 RBAC 權限檢查的效能。但是,它確實需要額外的記憶體,因此如果您的 RBAC 系統包含過多的授權項目,則可能不適合。在這種情況下,您應該尋找其他 RBAC 實作 (例如,基於 Redis 儲存的 RBAC)。
另請注意,如果您從此元件外部修改 RBAC 項目、規則或父子關係,則必須手動呼叫 invalidateCache() 以確保資料一致性。
使用者指派 (使用者 ID => Assignment[])
DB 連線物件或 DB 連線的應用程式元件 ID。在建立 DbManager 物件後,如果您想要變更此屬性,則應僅將其指派為 DB 連線物件。從 2.0.2 版開始,這也可以是用於建立物件的組態陣列。
儲存授權項目階層的表格名稱。預設為 "auth_item_child"。
用於在快取中儲存使用者 RBAC 角色的金鑰
方法詳細資訊
定義於: yii\base\Component::__call()
呼叫非類別方法的指定名稱方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,並在可用時執行它。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在叫用未知方法時隱式呼叫。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
定義於: yii\base\BaseObject::__construct()
建構子。
預設實作會執行兩件事
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果子類別中覆寫了此方法,建議
- 建構子的最後一個參數是組態陣列,如這裡的
$config
。 - 在建構子的末尾呼叫父實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的名稱-值配對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
定義於: yii\base\Component::__get()
傳回元件屬性的值。
此方法將依下列順序檢查並採取相應措施
- getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 $value = $component->property;
時隱式呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | mixed |
屬性值或行為屬性的值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | yii\base\InvalidCallException |
如果屬性是唯寫的。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\Component::__isset()
檢查屬性是否已設定,即已定義且非 null。
此方法將依下列順序檢查並採取相應措施
- setter 定義的屬性:傳回屬性是否已設定
- 行為的屬性:傳回屬性是否已設定
- 針對不存在的屬性傳回
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 isset($component->property)
時隱式呼叫。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
指定的屬性是否已設定 |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
定義於: yii\base\Component::__set()
設定元件屬性的值。
此方法將依下列順序檢查並採取相應措施
- setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
- 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
- 行為的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 $component->property = $value;
時隱式呼叫。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | yii\base\InvalidCallException |
如果屬性是唯讀的。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\Component::__unset()
將元件屬性設定為 null。
此方法將依下列順序檢查並採取相應措施
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,將在執行 unset($component->property)
時隱式呼叫。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | yii\base\InvalidCallException |
如果屬性是唯讀的。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\rbac\BaseManager::add()
將角色、權限或規則新增至 RBAC 系統。
public boolean add ( $object ) | ||
$object | yii\rbac\Role|yii\rbac\Permission|yii\rbac\Rule | |
return | boolean |
角色、權限或規則是否成功新增至系統 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如角色或權限名稱不唯一) |
public function add($object)
{
if ($object instanceof Item) {
if ($object->ruleName && $this->getRule($object->ruleName) === null) {
$rule = \Yii::createObject($object->ruleName);
$rule->name = $object->ruleName;
$this->addRule($rule);
}
return $this->addItem($object);
} elseif ($object instanceof Rule) {
return $this->addRule($object);
}
throw new InvalidArgumentException('Adding unsupported object type.');
}
將項目新增為另一個項目的子項目。
public boolean addChild ( $parent, $child ) | ||
$parent | yii\rbac\Item | |
$child | yii\rbac\Item | |
return | boolean |
子項目是否成功新增 |
---|---|---|
throws | yii\base\Exception |
如果父子關係已存在或偵測到迴圈。 |
public function addChild($parent, $child)
{
if ($parent->name === $child->name) {
throw new InvalidArgumentException("Cannot add '{$parent->name}' as a child of itself.");
}
if ($parent instanceof Permission && $child instanceof Role) {
throw new InvalidArgumentException('Cannot add a role as a child of a permission.');
}
if ($this->detectLoop($parent, $child)) {
throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
}
$this->db->createCommand()
->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
->execute();
$this->invalidateCache();
return true;
}
將授權項目新增至 RBAC 系統。
protected boolean addItem ( $item ) | ||
$item | yii\rbac\Item |
要新增的項目 |
return | boolean |
驗證項目是否成功新增至系統 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如角色或權限名稱不唯一) |
protected function addItem($item)
{
$time = time();
if ($item->createdAt === null) {
$item->createdAt = $time;
}
if ($item->updatedAt === null) {
$item->updatedAt = $time;
}
$this->db->createCommand()
->insert($this->itemTable, [
'name' => $item->name,
'type' => $item->type,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'created_at' => $item->createdAt,
'updated_at' => $item->updatedAt,
])->execute();
$this->invalidateCache();
return true;
}
將規則新增至 RBAC 系統。
protected boolean addRule ( $rule ) | ||
$rule | yii\rbac\Rule |
要新增的規則 |
return | boolean |
規則是否成功新增至系統 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如規則名稱不唯一) |
protected function addRule($rule)
{
$time = time();
if ($rule->createdAt === null) {
$rule->createdAt = $time;
}
if ($rule->updatedAt === null) {
$rule->updatedAt = $time;
}
$this->db->createCommand()
->insert($this->ruleTable, [
'name' => $rule->name,
'data' => serialize($rule),
'created_at' => $rule->createdAt,
'updated_at' => $rule->updatedAt,
])->execute();
$this->invalidateCache();
return true;
}
將角色指派給使用者。
public yii\rbac\Assignment assign ( $role, $userId ) | ||
$role | yii\rbac\Role|yii\rbac\Permission | |
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Assignment |
角色指派資訊。 |
---|---|---|
throws | 例外 |
如果角色已經指派給使用者 |
public function assign($role, $userId)
{
$assignment = new Assignment([
'userId' => $userId,
'roleName' => $role->name,
'createdAt' => time(),
]);
$this->db->createCommand()
->insert($this->assignmentTable, [
'user_id' => $assignment->userId,
'item_name' => $assignment->roleName,
'created_at' => $assignment->createdAt,
])->execute();
unset($this->checkAccessAssignments[(string) $userId]);
$this->invalidateCache();
return $assignment;
}
Defined in: yii\base\Component::attachBehavior()
將行為附加到此元件。
此方法會根據給定的配置建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此元件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為配置。這可以是下列其中之一
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
將行為列表附加到元件。
每個行為都以其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的配置陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
要附加到元件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
傳回此元件應表現為的行為列表。
子類別可以覆寫此方法來指定它們想要表現為的行為。
此方法的傳回值應該是以行為名稱索引的行為物件或配置陣列。行為配置可以是指定行為類別的字串,或是具有以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須繼承自 yii\base\Behavior。行為可以使用名稱或匿名方式附加。當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動 (按需) 附加到元件。
public array behaviors ( ) | ||
return | array |
行為配置。 |
---|
public function behaviors()
{
return [];
}
檢查是否可能將子項目新增至父項目。
public boolean canAddChild ( $parent, $child ) | ||
$parent | yii\rbac\Item |
父項目 |
$child | yii\rbac\Item |
要新增至階層的子項目 |
return | boolean |
新增的可能性 |
---|
public function canAddChild($parent, $child)
{
return !$this->detectLoop($parent, $child);
}
Defined in: yii\base\Component::canGetProperty()
傳回指示是否可以讀取屬性的值。
如果符合以下條件,則可以讀取屬性
- 類別具有與指定名稱相關聯的 getter 方法 (在此情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可讀 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
傳回指示是否可以設定屬性的值。
如果符合以下條件,則可以寫入屬性
- 類別具有與指定名稱相關聯的 setter 方法 (在此情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否可寫 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
public void checkAccess ( $userId, $permissionName, $params = [] ) | ||
$userId | ||
$permissionName | ||
$params |
public function checkAccess($userId, $permissionName, $params = [])
{
if (isset($this->checkAccessAssignments[(string) $userId])) {
$assignments = $this->checkAccessAssignments[(string) $userId];
} else {
$assignments = $this->getAssignments($userId);
$this->checkAccessAssignments[(string) $userId] = $assignments;
}
if ($this->hasNoAssignments($assignments)) {
return false;
}
$this->loadFromCache();
if ($this->items !== null) {
return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments);
}
return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
}
根據從快取載入的資料,對指定使用者執行存取檢查。
當啟用 $cache 時,此方法會在內部由 checkAccess() 呼叫。
protected boolean checkAccessFromCache ( $user, $itemName, $params, $assignments ) | ||
$user | string|integer |
使用者 ID。這應該是整數或字串,代表使用者的唯一識別碼。請參閱 yii\web\User::$id。 |
$itemName | string |
需要存取檢查的操作名稱 |
$params | array |
將傳遞給與指派給使用者的任務和角色相關聯的規則的名稱-值對。名稱為 'user' 的參數會新增至此陣列,其中包含 |
$assignments | yii\rbac\Assignment[] |
指派給指定使用者的指派 |
return | boolean |
使用者是否可以執行操作。 |
---|
protected function checkAccessFromCache($user, $itemName, $params, $assignments)
{
if (!isset($this->items[$itemName])) {
return false;
}
$item = $this->items[$itemName];
Yii::debug($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
if (!$this->executeRule($user, $item, $params)) {
return false;
}
if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
return true;
}
if (!empty($this->parents[$itemName])) {
foreach ($this->parents[$itemName] as $parent) {
if ($this->checkAccessFromCache($user, $parent, $params, $assignments)) {
return true;
}
}
}
return false;
}
對指定使用者執行存取檢查。
此方法會在內部由 checkAccess() 呼叫。
protected boolean checkAccessRecursive ( $user, $itemName, $params, $assignments ) | ||
$user | string|integer |
使用者 ID。這應該是整數或字串,代表使用者的唯一識別碼。請參閱 yii\web\User::$id。 |
$itemName | string |
需要存取檢查的操作名稱 |
$params | array |
將傳遞給與指派給使用者的任務和角色相關聯的規則的名稱-值對。名稱為 'user' 的參數會新增至此陣列,其中包含 |
$assignments | yii\rbac\Assignment[] |
指派給指定使用者的指派 |
return | boolean |
使用者是否可以執行操作。 |
---|
protected function checkAccessRecursive($user, $itemName, $params, $assignments)
{
if (($item = $this->getItem($itemName)) === null) {
return false;
}
Yii::debug($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
if (!$this->executeRule($user, $item, $params)) {
return false;
}
if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
return true;
}
$query = new Query();
$parents = $query->select(['parent'])
->from($this->itemChildTable)
->where(['child' => $itemName])
->column($this->db);
foreach ($parents as $parent) {
if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
return true;
}
}
return false;
}
::class
。
Defined in: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
Defined in: yii\rbac\BaseManager::createPermission()
建立新的 Permission 物件。
請注意,新建立的權限尚未新增至 RBAC 系統。您必須填寫需要的資料並呼叫 add() 以將其新增至系統。
public yii\rbac\Permission createPermission ( $name ) | ||
$name | string |
權限名稱 |
return | yii\rbac\Permission |
新的 Permission 物件 |
---|
public function createPermission($name)
{
$permission = new Permission();
$permission->name = $name;
return $permission;
}
Defined in: yii\rbac\BaseManager::createRole()
建立新的 Role 物件。
請注意,新建立的角色尚未新增至 RBAC 系統。您必須填寫需要的資料並呼叫 add() 以將其新增至系統。
public yii\rbac\Role createRole ( $name ) | ||
$name | string |
角色名稱 |
return | yii\rbac\Role |
新的 Role 物件 |
---|
public function createRole($name)
{
$role = new Role();
$role->name = $name;
return $role;
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
return | yii\base\Behavior|null |
已分離的行為。如果行為不存在,則為 Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
從元件卸離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
檢查授權項目階層中是否存在循環。
protected boolean detectLoop ( $parent, $child ) | ||
$parent | yii\rbac\Item |
父項目 |
$child | yii\rbac\Item |
要新增至階層的子項目 |
return | boolean |
是否存在迴圈 |
---|
protected function detectLoop($parent, $child)
{
if ($child->name === $parent->name) {
return true;
}
foreach ($this->getChildren($child->name) as $grandchild) {
if ($this->detectLoop($parent, $grandchild)) {
return true;
}
}
return false;
}
Defined in: yii\base\Component::ensureBehaviors()
確保在 behaviors() 中宣告的行為已附加到此元件。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Defined in: yii\rbac\BaseManager::executeRule()
執行與指定授權項目關聯的規則。
如果項目未指定規則,則此方法將傳回 true。否則,它將傳回 yii\rbac\Rule::execute() 的值。
protected boolean executeRule ( $user, $item, $params ) | ||
$user | string|integer |
使用者 ID。這應該是整數或字串,代表使用者的唯一識別碼。請參閱 yii\web\User::$id。 |
$item | yii\rbac\Item |
需要執行其規則的驗證項目 |
$params | array |
傳遞給 yii\rbac\CheckAccessInterface::checkAccess() 的參數,並將傳遞給規則 |
return | boolean |
yii\rbac\Rule::execute() 的傳回值。如果驗證項目未指定規則,則將傳回 true。 |
---|---|---|
throws | yii\base\InvalidConfigException |
如果驗證項目具有無效規則。 |
protected function executeRule($user, $item, $params)
{
if ($item->ruleName === null) {
return true;
}
$rule = $this->getRule($item->ruleName);
if ($rule instanceof Rule) {
return $rule->execute($user, $item, $params);
}
throw new InvalidConfigException("Rule not found: {$item->ruleName}");
}
傳回關於角色和使用者的指派資訊。
public yii\rbac\Assignment|null getAssignment ( $roleName, $userId ) | ||
$roleName | string |
角色名稱 |
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Assignment|null |
指派資訊。如果角色未指派給使用者,則傳回 Null。 |
---|
public function getAssignment($roleName, $userId)
{
if ($this->isEmptyUserId($userId)) {
return null;
}
$row = (new Query())->from($this->assignmentTable)
->where(['user_id' => (string) $userId, 'item_name' => $roleName])
->one($this->db);
if ($row === false) {
return null;
}
return new Assignment([
'userId' => $row['user_id'],
'roleName' => $row['item_name'],
'createdAt' => $row['created_at'],
]);
}
傳回指定使用者的所有角色指派資訊。
public yii\rbac\Assignment[] getAssignments ( $userId ) | ||
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Assignment[] |
以角色名稱索引的指派。如果沒有角色指派給使用者,則會傳回空陣列。 |
---|
public function getAssignments($userId)
{
if ($this->isEmptyUserId($userId)) {
return [];
}
$query = (new Query())
->from($this->assignmentTable)
->where(['user_id' => (string) $userId]);
$assignments = [];
foreach ($query->all($this->db) as $row) {
$assignments[$row['item_name']] = new Assignment([
'userId' => $row['user_id'],
'roleName' => $row['item_name'],
'createdAt' => $row['created_at'],
]);
}
return $assignments;
}
Defined in: yii\base\Component::getBehavior()
傳回指定的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
行為名稱 |
return | yii\base\Behavior|null |
行為物件;如果行為不存在,則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
傳回附加到此元件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
附加到此元件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
傳回指定角色的子角色。深度不受限制。
public yii\rbac\Role[] getChildRoles ( $roleName ) | ||
$roleName | string |
要為其尋找子角色的角色名稱 |
return | yii\rbac\Role[] |
子角色。陣列依角色名稱索引。第一個元素是父 Role 本身的實例。 |
---|---|---|
throws | yii\base\InvalidParamException |
如果找不到透過 $roleName 取得的角色 |
public function getChildRoles($roleName)
{
$role = $this->getRole($roleName);
if ($role === null) {
throw new InvalidArgumentException("Role \"$roleName\" not found.");
}
$result = [];
$this->getChildrenRecursive($roleName, $this->getChildrenList(), $result);
$roles = [$roleName => $role];
$roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
return array_key_exists($roleItem->name, $result);
});
return $roles;
}
傳回子權限和/或角色。
public yii\rbac\Item[] getChildren ( $name ) | ||
$name | string |
父層名稱 |
return | yii\rbac\Item[] |
子權限和/或角色 |
---|
public function getChildren($name)
{
$query = (new Query())
->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
->from([$this->itemTable, $this->itemChildTable])
->where(['parent' => $name, 'name' => new Expression('[[child]]')]);
$children = [];
foreach ($query->all($this->db) as $row) {
$children[$row['name']] = $this->populateItem($row);
}
return $children;
}
傳回每個父項目的子項目。
protected array getChildrenList ( ) | ||
return | array |
子層列表。每個陣列鍵名是父層項目名稱,而對應的陣列值是子層項目名稱的列表。 |
---|
protected function getChildrenList()
{
$query = (new Query())->from($this->itemChildTable);
$parents = [];
foreach ($query->all($this->db) as $row) {
$parents[$row['parent']][] = $row['child'];
}
return $parents;
}
遞迴尋找指定項目的所有子項目和孫子項目。
protected void getChildrenRecursive ( $name, $childrenList, &$result ) | ||
$name | string |
要尋找其子項目的項目名稱。 |
$childrenList | array |
透過 getChildrenList() 建立的子層列表 |
$result | array |
子項目和孫子項目(在陣列鍵名中) |
protected function getChildrenRecursive($name, $childrenList, &$result)
{
if (isset($childrenList[$name])) {
foreach ($childrenList[$name] as $child) {
$result[$child] = true;
$this->getChildrenRecursive($child, $childrenList, $result);
}
}
}
定義於: yii\rbac\BaseManager::getDefaultRoleInstances()
以 Role 物件陣列形式傳回 defaultRoles。
public yii\rbac\Role[] getDefaultRoleInstances ( ) | ||
return | yii\rbac\Role[] |
預設角色。陣列以角色名稱索引。 |
---|
public function getDefaultRoleInstances()
{
$result = [];
foreach ($this->defaultRoles as $roleName) {
$result[$roleName] = $this->createRole($roleName);
}
return $result;
}
定義於: yii\rbac\BaseManager::getDefaultRoles()
取得預設角色
public string[] getDefaultRoles ( ) | ||
return | string[] |
預設角色 |
---|
public function getDefaultRoles()
{
return $this->defaultRoles;
}
傳回直接指派給使用者的所有權限。
protected yii\rbac\Permission[] getDirectPermissionsByUser ( $userId ) | ||
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Permission[] |
使用者擁有的所有直接權限。陣列以權限名稱索引。 |
---|
protected function getDirectPermissionsByUser($userId)
{
$query = (new Query())->select('b.*')
->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
->where('{{a}}.[[item_name]]={{b}}.[[name]]')
->andWhere(['a.user_id' => (string) $userId])
->andWhere(['b.type' => Item::TYPE_PERMISSION]);
$permissions = [];
foreach ($query->all($this->db) as $row) {
$permissions[$row['name']] = $this->populateItem($row);
}
return $permissions;
}
傳回使用者從指派給他的角色繼承的所有權限。
protected yii\rbac\Permission[] getInheritedPermissionsByUser ( $userId ) | ||
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Permission[] |
使用者擁有的所有繼承權限。陣列以權限名稱索引。 |
---|
protected function getInheritedPermissionsByUser($userId)
{
$query = (new Query())->select('item_name')
->from($this->assignmentTable)
->where(['user_id' => (string) $userId]);
$childrenList = $this->getChildrenList();
$result = [];
foreach ($query->column($this->db) as $roleName) {
$this->getChildrenRecursive($roleName, $childrenList, $result);
}
if (empty($result)) {
return [];
}
$query = (new Query())->from($this->itemTable)->where([
'type' => Item::TYPE_PERMISSION,
'name' => array_keys($result),
]);
$permissions = [];
foreach ($query->all($this->db) as $row) {
$permissions[$row['name']] = $this->populateItem($row);
}
return $permissions;
}
傳回指定的授權項目。
protected yii\rbac\Item|null getItem ( $name ) | ||
$name | string |
授權項目名稱。 |
return | yii\rbac\Item|null |
與指定名稱相對應的授權項目。如果沒有此項目,則傳回 Null。 |
---|
protected function getItem($name)
{
if (empty($name)) {
return null;
}
if (!empty($this->items[$name])) {
return $this->items[$name];
}
$row = (new Query())->from($this->itemTable)
->where(['name' => $name])
->one($this->db);
if ($row === false) {
return null;
}
return $this->populateItem($row);
}
傳回指定類型的項目。
protected yii\rbac\Item[] getItems ( $type ) | ||
$type | integer |
授權項目類型(yii\rbac\Item::TYPE_ROLE 或 yii\rbac\Item::TYPE_PERMISSION) |
return | yii\rbac\Item[] |
指定類型的授權項目。 |
---|
protected function getItems($type)
{
$query = (new Query())
->from($this->itemTable)
->where(['type' => $type]);
$items = [];
foreach ($query->all($this->db) as $row) {
$items[$row['name']] = $this->populateItem($row);
}
return $items;
}
定義於: yii\rbac\BaseManager::getPermission()
傳回指定的權限。
public yii\rbac\Permission|null getPermission ( $name ) | ||
$name | string |
權限名稱。 |
return | yii\rbac\Permission|null |
與指定名稱相對應的權限。如果沒有此權限,則傳回 Null。 |
---|
public function getPermission($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_PERMISSION ? $item : null;
}
定義於: yii\rbac\BaseManager::getPermissions()
傳回系統中的所有權限。
public yii\rbac\Permission[] getPermissions ( ) | ||
return | yii\rbac\Permission[] |
系統中的所有權限。陣列以權限名稱索引。 |
---|
public function getPermissions()
{
return $this->getItems(Item::TYPE_PERMISSION);
}
傳回指定角色代表的所有權限。
public yii\rbac\Permission[] getPermissionsByRole ( $roleName ) | ||
$roleName | string |
角色名稱 |
return | yii\rbac\Permission[] |
角色代表的所有權限。陣列以權限名稱索引。 |
---|
public function getPermissionsByRole($roleName)
{
$childrenList = $this->getChildrenList();
$result = [];
$this->getChildrenRecursive($roleName, $childrenList, $result);
if (empty($result)) {
return [];
}
$query = (new Query())->from($this->itemTable)->where([
'type' => Item::TYPE_PERMISSION,
'name' => array_keys($result),
]);
$permissions = [];
foreach ($query->all($this->db) as $row) {
$permissions[$row['name']] = $this->populateItem($row);
}
return $permissions;
}
傳回使用者擁有的所有權限。
public yii\rbac\Permission[] getPermissionsByUser ( $userId ) | ||
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | yii\rbac\Permission[] |
使用者擁有的所有權限。陣列以權限名稱索引。 |
---|
public function getPermissionsByUser($userId)
{
if ($this->isEmptyUserId($userId)) {
return [];
}
$directPermission = $this->getDirectPermissionsByUser($userId);
$inheritedPermission = $this->getInheritedPermissionsByUser($userId);
return array_merge($directPermission, $inheritedPermission);
}
定義於: yii\rbac\BaseManager::getRole()
傳回指定的角色。
public yii\rbac\Role|null getRole ( $name ) | ||
$name | string |
角色名稱。 |
return | yii\rbac\Role|null |
與指定名稱相對應的角色。如果沒有此角色,則傳回 Null。 |
---|
public function getRole($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_ROLE ? $item : null;
}
定義於: yii\rbac\BaseManager::getRoles()
傳回系統中的所有角色。
public yii\rbac\Role[] getRoles ( ) | ||
return | yii\rbac\Role[] |
系統中的所有角色。陣列以角色名稱索引。 |
---|
public function getRoles()
{
return $this->getItems(Item::TYPE_ROLE);
}
{@inheritdoc} 這個方法傳回的角色包含透過 $defaultRoles 指派的角色。
public void getRolesByUser ( $userId ) | ||
$userId |
public function getRolesByUser($userId)
{
if ($this->isEmptyUserId($userId)) {
return [];
}
if ($this->cache !== null) {
$data = $this->cache->get($this->getUserRolesCacheKey($userId));
if ($data !== false) {
return $data;
}
}
$query = (new Query())->select('b.*')
->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
->where('{{a}}.[[item_name]]={{b}}.[[name]]')
->andWhere(['a.user_id' => (string) $userId])
->andWhere(['b.type' => Item::TYPE_ROLE]);
$roles = $this->getDefaultRoleInstances();
foreach ($query->all($this->db) as $row) {
$roles[$row['name']] = $this->populateItem($row);
}
if ($this->cache !== null) {
$this->cacheUserRolesData($userId, $roles);
}
return $roles;
}
傳回指定名稱的規則。
public yii\rbac\Rule|null getRule ( $name ) | ||
$name | string |
規則名稱 |
return | yii\rbac\Rule|null |
規則物件,如果指定的名稱未對應到規則,則為 null。 |
---|
public function getRule($name)
{
if ($this->rules !== null) {
return isset($this->rules[$name]) ? $this->rules[$name] : null;
}
$row = (new Query())->select(['data'])
->from($this->ruleTable)
->where(['name' => $name])
->one($this->db);
if ($row === false) {
return null;
}
$data = $row['data'];
if (is_resource($data)) {
$data = stream_get_contents($data);
}
if (!$data) {
return null;
}
return unserialize($data);
}
傳回系統中所有可用的規則。
public yii\rbac\Rule[] getRules ( ) | ||
return | yii\rbac\Rule[] |
以規則名稱索引的規則 |
---|
public function getRules()
{
if ($this->rules !== null) {
return $this->rules;
}
$query = (new Query())->from($this->ruleTable);
$rules = [];
foreach ($query->all($this->db) as $row) {
$data = $row['data'];
if (is_resource($data)) {
$data = stream_get_contents($data);
}
if ($data) {
$rules[$row['name']] = unserialize($data);
}
}
return $rules;
}
傳回指定角色的所有角色指派資訊。
public string[] getUserIdsByRole ( $roleName ) | ||
$roleName | string | |
return | string[] |
ID。如果角色未分配給任何使用者,將傳回空陣列。 |
---|
public function getUserIdsByRole($roleName)
{
if (empty($roleName)) {
return [];
}
return (new Query())->select('[[user_id]]')
->from($this->assignmentTable)
->where(['item_name' => $roleName])->column($this->db);
}
傳回指示父項目是否已存在子項目的值。
public boolean hasChild ( $parent, $child ) | ||
$parent | yii\rbac\Item | |
$child | yii\rbac\Item | |
return | boolean |
|
---|
public function hasChild($parent, $child)
{
return (new Query())
->from($this->itemChildTable)
->where(['parent' => $parent->name, 'child' => $child->name])
->one($this->db) !== false;
}
定義於: yii\base\Component::hasEventHandlers()
傳回指示是否有任何處理常式附加到指定名稱事件的值。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
return | boolean |
是否有任何處理常式附加到事件。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義於: yii\base\Component::hasMethod()
傳回指示是否已定義方法的值。
如果滿足以下條件,則定義方法
- 類別具有指定名稱的方法
- 附加的行為具有給定名稱的方法(當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為的方法視為此組件的方法 |
return | boolean |
方法是否已定義 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義於: yii\rbac\BaseManager::hasNoAssignments()
檢查 $assignments 陣列是否為空,且 $defaultRoles 屬性是否也為空。
protected boolean hasNoAssignments ( array $assignments ) | ||
$assignments | yii\rbac\Assignment[] |
使用者分配的陣列 |
return | boolean |
陣列 $assignments 是否為空,且 $defaultRoles 屬性也為空 |
---|
protected function hasNoAssignments(array $assignments)
{
return empty($assignments) && empty($this->defaultRoles);
}
定義於: yii\base\Component::hasProperty()
傳回指示是否已為此元件定義屬性的值。
如果滿足以下條件,則定義屬性
- 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性(當
$checkBehaviors
為 true 時)。
參見
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此元件的屬性 |
return | boolean |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
初始化應用程式元件。
此方法透過建立資料庫連線來覆寫父層實作。
public void init ( ) |
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
}
}
public void invalidateCache ( ) |
public function invalidateCache()
{
if ($this->cache !== null) {
$this->cache->delete($this->cacheKey);
$this->items = null;
$this->rules = null;
$this->parents = null;
$cachedUserIds = $this->cache->get($this->getUserRolesCachedSetKey());
if ($cachedUserIds !== false) {
foreach ($cachedUserIds as $userId) {
$this->cache->delete($this->getUserRolesCacheKey($userId));
}
$this->cache->delete($this->getUserRolesCachedSetKey());
}
}
$this->checkAccessAssignments = [];
}
檢查 $userId 是否為空。
protected boolean isEmptyUserId ( $userId ) | ||
$userId | mixed |
protected function isEmptyUserId($userId)
{
return !isset($userId) || $userId === '';
}
public void loadFromCache ( ) |
public function loadFromCache()
{
if ($this->items !== null || !$this->cache instanceof CacheInterface) {
return;
}
$data = $this->cache->get($this->cacheKey);
if (is_array($data) && isset($data[0], $data[1], $data[2])) {
list($this->items, $this->rules, $this->parents) = $data;
return;
}
$query = (new Query())->from($this->itemTable);
$this->items = [];
foreach ($query->all($this->db) as $row) {
$this->items[$row['name']] = $this->populateItem($row);
}
$query = (new Query())->from($this->ruleTable);
$this->rules = [];
foreach ($query->all($this->db) as $row) {
$data = $row['data'];
if (is_resource($data)) {
$data = stream_get_contents($data);
}
if ($data) {
$this->rules[$row['name']] = unserialize($data);
}
}
$query = (new Query())->from($this->itemChildTable);
$this->parents = [];
foreach ($query->all($this->db) as $row) {
if (isset($this->items[$row['child']])) {
$this->parents[$row['child']][] = $row['parent'];
}
}
$this->cache->set($this->cacheKey, [$this->items, $this->rules, $this->parents]);
}
定義於: yii\base\Component::off()
從此元件卸離現有的事件處理常式。
此方法與 on() 相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純名稱註冊的處理常式將保持不變。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理常式。如果為 null,則會移除附加到具名事件的所有處理常式。 |
return | boolean |
如果找到並分離處理常式 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
將事件處理常式附加到事件。
事件處理常式必須是有效的 PHP 回呼。以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理常式必須使用以下簽章定義,
function ($event)
其中 $event
是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。
自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
另請參閱 off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
事件名稱 |
$handler | callable |
事件處理常式 |
$data | mixed |
事件觸發時要傳遞給事件處理常式的資料。當調用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新的處理常式將插入到現有處理常式列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
使用從資料庫擷取的資料填入授權項目。
protected yii\rbac\Item populateItem ( $row ) | ||
$row | array |
授權項目表格中的資料 |
return | yii\rbac\Item |
已填充的授權項目實例(Role 或 Permission) |
---|
protected function populateItem($row)
{
$class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
if (!isset($row['data']) || ($data = @unserialize(is_resource($row['data']) ? stream_get_contents($row['data']) : $row['data'])) === false) {
$data = null;
}
return new $class([
'name' => $row['name'],
'type' => $row['type'],
'description' => $row['description'],
'ruleName' => $row['rule_name'] ?: null,
'data' => $data,
'createdAt' => $row['created_at'],
'updatedAt' => $row['updated_at'],
]);
}
定義於: yii\rbac\BaseManager::remove()
從 RBAC 系統移除角色、權限或規則。
public boolean remove ( $object ) | ||
$object | yii\rbac\Role|yii\rbac\Permission|yii\rbac\Rule | |
return | boolean |
角色、權限或規則是否成功移除 |
---|
public function remove($object)
{
if ($object instanceof Item) {
return $this->removeItem($object);
} elseif ($object instanceof Rule) {
return $this->removeRule($object);
}
throw new InvalidArgumentException('Removing unsupported object type.');
}
移除所有授權資料,包括角色、權限、規則和指派。
public void removeAll ( ) |
public function removeAll()
{
$this->removeAllAssignments();
$this->db->createCommand()->delete($this->itemChildTable)->execute();
$this->db->createCommand()->delete($this->itemTable)->execute();
$this->db->createCommand()->delete($this->ruleTable)->execute();
$this->invalidateCache();
}
移除所有角色指派。
public void removeAllAssignments ( ) |
public function removeAllAssignments()
{
$this->checkAccessAssignments = [];
$this->db->createCommand()->delete($this->assignmentTable)->execute();
}
移除指定類型的所有授權項目。
protected void removeAllItems ( $type ) | ||
$type | integer |
授權項目類型(Item::TYPE_PERMISSION 或 Item::TYPE_ROLE) |
protected function removeAllItems($type)
{
if (!$this->supportsCascadeUpdate()) {
$names = (new Query())
->select(['name'])
->from($this->itemTable)
->where(['type' => $type])
->column($this->db);
if (empty($names)) {
return;
}
$key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
$this->db->createCommand()
->delete($this->itemChildTable, [$key => $names])
->execute();
$this->db->createCommand()
->delete($this->assignmentTable, ['item_name' => $names])
->execute();
}
$this->db->createCommand()
->delete($this->itemTable, ['type' => $type])
->execute();
$this->invalidateCache();
}
移除所有權限。
所有父子關係將會相應地調整。
public void removeAllPermissions ( ) |
public function removeAllPermissions()
{
$this->removeAllItems(Item::TYPE_PERMISSION);
}
移除所有角色。
所有父子關係將會相應地調整。
public void removeAllRoles ( ) |
public function removeAllRoles()
{
$this->removeAllItems(Item::TYPE_ROLE);
}
移除所有規則。
所有具有規則的角色和權限將會相應地調整。
public void removeAllRules ( ) |
public function removeAllRules()
{
if (!$this->supportsCascadeUpdate()) {
$this->db->createCommand()
->update($this->itemTable, ['rule_name' => null])
->execute();
}
$this->db->createCommand()->delete($this->ruleTable)->execute();
$this->invalidateCache();
}
從父項目移除子項目。
請注意,子項目不會被刪除。僅移除父子關係。
public boolean removeChild ( $parent, $child ) | ||
$parent | yii\rbac\Item | |
$child | yii\rbac\Item | |
return | boolean |
移除是否成功 |
---|
public function removeChild($parent, $child)
{
$result = $this->db->createCommand()
->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
->execute() > 0;
$this->invalidateCache();
return $result;
}
從父項目移除所有子項目。
請注意,子項目不會被刪除。僅移除父子關係。
public boolean removeChildren ( $parent ) | ||
$parent | yii\rbac\Item | |
return | boolean |
移除是否成功 |
---|
public function removeChildren($parent)
{
$result = $this->db->createCommand()
->delete($this->itemChildTable, ['parent' => $parent->name])
->execute() > 0;
$this->invalidateCache();
return $result;
}
從 RBAC 系統移除授權項目。
protected boolean removeItem ( $item ) | ||
$item | yii\rbac\Item |
要移除的項目 |
return | boolean |
角色或權限是否成功移除 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如角色或權限名稱不唯一) |
protected function removeItem($item)
{
if (!$this->supportsCascadeUpdate()) {
$this->db->createCommand()
->delete($this->itemChildTable, ['or', '[[parent]]=:parent', '[[child]]=:child'], [':parent' => $item->name, ':child' => $item->name])
->execute();
$this->db->createCommand()
->delete($this->assignmentTable, ['item_name' => $item->name])
->execute();
}
$this->db->createCommand()
->delete($this->itemTable, ['name' => $item->name])
->execute();
$this->invalidateCache();
return true;
}
從 RBAC 系統移除規則。
protected boolean removeRule ( $rule ) | ||
$rule | yii\rbac\Rule |
要移除的規則 |
return | boolean |
規則是否成功移除 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如規則名稱不唯一) |
protected function removeRule($rule)
{
if (!$this->supportsCascadeUpdate()) {
$this->db->createCommand()
->update($this->itemTable, ['rule_name' => null], ['rule_name' => $rule->name])
->execute();
}
$this->db->createCommand()
->delete($this->ruleTable, ['name' => $rule->name])
->execute();
$this->invalidateCache();
return true;
}
從使用者撤銷角色。
public boolean revoke ( $role, $userId ) | ||
$role | yii\rbac\Role|yii\rbac\Permission | |
$userId | string|integer |
使用者 ID (請參閱 yii\web\User::$id) |
return | boolean |
撤銷是否成功 |
---|
public function revoke($role, $userId)
{
if ($this->isEmptyUserId($userId)) {
return false;
}
unset($this->checkAccessAssignments[(string) $userId]);
$result = $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
->execute() > 0;
$this->invalidateCache();
return $result;
}
從使用者撤銷所有角色。
public boolean revokeAll ( $userId ) | ||
$userId | mixed |
使用者 ID (請參閱 yii\web\User::$id) |
return | boolean |
撤銷是否成功 |
---|
public function revokeAll($userId)
{
if ($this->isEmptyUserId($userId)) {
return false;
}
unset($this->checkAccessAssignments[(string) $userId]);
$result = $this->db->createCommand()
->delete($this->assignmentTable, ['user_id' => (string) $userId])
->execute() > 0;
$this->invalidateCache();
return $result;
}
定義於: yii\rbac\BaseManager::setDefaultRoles()
設定預設角色
public void setDefaultRoles ( $roles ) | ||
$roles | string[]|Closure |
角色陣列或返回角色陣列的可呼叫函式 |
throws | yii\base\InvalidArgumentException |
當 $roles 既非陣列也非 Closure 時 |
---|---|---|
throws | yii\base\InvalidValueException |
當 Closure 返回值不是陣列時 |
public function setDefaultRoles($roles)
{
if (is_array($roles)) {
$this->defaultRoles = $roles;
} elseif ($roles instanceof \Closure) {
$roles = call_user_func($roles);
if (!is_array($roles)) {
throw new InvalidValueException('Default roles closure must return an array');
}
$this->defaultRoles = $roles;
} else {
throw new InvalidArgumentException('Default roles must be either an array or a callable');
}
}
傳回指示資料庫是否支援串聯更新和刪除的值。
預設實作對於 SQLite 資料庫將返回 false,對於所有其他資料庫則返回 true。
protected boolean supportsCascadeUpdate ( ) | ||
return | boolean |
資料庫是否支援級聯更新與刪除。 |
---|
protected function supportsCascadeUpdate()
{
return strncmp($this->db->getDriverName(), 'sqlite', 6) !== 0;
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
事件名稱 |
$event | yii\base\Event|null |
事件實例。若未設定,將會建立預設的 yii\base\Event 物件。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
定義於: yii\rbac\BaseManager::update()
更新系統中指定的角色、權限或規則。
public boolean update ( $name, $object ) | ||
$name | string |
角色、權限或規則的舊名稱 |
$object | yii\rbac\Role|yii\rbac\Permission|yii\rbac\Rule | |
return | boolean |
更新是否成功 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如角色或權限名稱不唯一) |
public function update($name, $object)
{
if ($object instanceof Item) {
if ($object->ruleName && $this->getRule($object->ruleName) === null) {
$rule = \Yii::createObject($object->ruleName);
$rule->name = $object->ruleName;
$this->addRule($rule);
}
return $this->updateItem($name, $object);
} elseif ($object instanceof Rule) {
return $this->updateRule($name, $object);
}
throw new InvalidArgumentException('Updating unsupported object type.');
}
在 RBAC 系統中更新授權項目。
protected boolean updateItem ( $name, $item ) | ||
$name | string |
正在更新的項目名稱 |
$item | yii\rbac\Item |
已更新的項目 |
return | boolean |
授權項目是否成功更新 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如角色或權限名稱不唯一) |
protected function updateItem($name, $item)
{
if ($item->name !== $name && !$this->supportsCascadeUpdate()) {
$this->db->createCommand()
->update($this->itemChildTable, ['parent' => $item->name], ['parent' => $name])
->execute();
$this->db->createCommand()
->update($this->itemChildTable, ['child' => $item->name], ['child' => $name])
->execute();
$this->db->createCommand()
->update($this->assignmentTable, ['item_name' => $item->name], ['item_name' => $name])
->execute();
}
$item->updatedAt = time();
$this->db->createCommand()
->update($this->itemTable, [
'name' => $item->name,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'updated_at' => $item->updatedAt,
], [
'name' => $name,
])->execute();
$this->invalidateCache();
return true;
}
更新 RBAC 系統的規則。
protected boolean updateRule ( $name, $rule ) | ||
$name | string |
正在更新的規則名稱 |
$rule | yii\rbac\Rule |
已更新的規則 |
return | boolean |
規則是否成功更新 |
---|---|---|
throws | 例外 |
如果資料驗證或儲存失敗 (例如規則名稱不唯一) |
protected function updateRule($name, $rule)
{
if ($rule->name !== $name && !$this->supportsCascadeUpdate()) {
$this->db->createCommand()
->update($this->itemTable, ['rule_name' => $rule->name], ['rule_name' => $name])
->execute();
}
$rule->updatedAt = time();
$this->db->createCommand()
->update($this->ruleTable, [
'name' => $rule->name,
'data' => serialize($rule),
'updated_at' => $rule->updatedAt,
], [
'name' => $name,
])->execute();
$this->invalidateCache();
return true;
}
註冊 或 登入 以進行評論。