0 關注者

類別 yii\rbac\PhpManager

繼承yii\rbac\PhpManager » yii\rbac\BaseManager » yii\base\Component » yii\base\BaseObject
實作yii\base\Configurable, yii\rbac\ManagerInterface
自此版本可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/rbac/PhpManager.php

PhpManager 代表一個授權管理器,以 PHP 腳本檔案的形式儲存授權資訊。

授權資料將會儲存至並從三個檔案載入,這些檔案由 $itemFile$assignmentFile$ruleFile 指定。

PhpManager 主要適用於不太大的授權資料(例如,個人部落格系統的授權資料)。對於更複雜的授權資料,請使用 yii\rbac\DbManager

請注意,PhpManager 與 Facebook 的 HHVM 不相容,因為它依賴於寫入 php 檔案,然後再將其包含進來,但 HHVM 不支援這個功能。

關於 PhpManager 的更多詳細資訊和使用方法,請參閱關於安全性授權的指南文章

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$assignmentFile 字串 包含授權指派的 PHP 腳本路徑。 yii\rbac\PhpManager
$assignments 陣列 yii\rbac\PhpManager
$behaviors yii\base\Behavior[] 附加到此組件的行為列表。 yii\base\Component
$children 陣列 yii\rbac\PhpManager
$defaultRoleInstances yii\rbac\Role[] 預設角色。 yii\rbac\BaseManager
$defaultRoles 陣列 自動指派給每位使用者的角色名稱列表,無需呼叫 assign() yii\rbac\BaseManager
$itemFile 字串 包含授權項目的 PHP 腳本路徑。 yii\rbac\PhpManager
$items yii\rbac\Item[] yii\rbac\PhpManager
$permissions yii\rbac\Permission[] 系統中的所有權限。 yii\rbac\BaseManager
$roles yii\rbac\Role[] 系統中的所有角色。 yii\rbac\BaseManager
$ruleFile 字串 包含授權規則的 PHP 腳本路徑。 yii\rbac\PhpManager
$rules yii\rbac\Rule[] yii\rbac\PhpManager

受保護的屬性

隱藏繼承的屬性

屬性 類型 描述 定義於

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫指定的非類別方法。 yii\base\Component
__clone() 在透過複製現有物件建立物件後,會呼叫此方法。 yii\base\Component
__construct() 建構子。 yii\base\BaseObject
__get() 傳回組件屬性的值。 yii\base\Component
__isset() 檢查屬性是否已設定,即已定義且非空值。 yii\base\Component
__set() 設定組件屬性的值。 yii\base\Component
__unset() 將組件屬性設定為空值。 yii\base\Component
add() 將角色、權限或規則新增至 RBAC 系統。 yii\rbac\BaseManager
addChild() 將項目新增為另一個項目的子項目。 yii\rbac\PhpManager
assign() 將角色指派給使用者。 yii\rbac\PhpManager
attachBehavior() 將行為附加到此組件。 yii\base\Component
attachBehaviors() 將行為列表附加到組件。 yii\base\Component
behaviors() 傳回此組件應表現為的行為列表。 yii\base\Component
canAddChild() 檢查是否可以將子項目新增至父項目。 yii\rbac\PhpManager
canGetProperty() 傳回一個值,指示屬性是否可讀取。 yii\base\Component
canSetProperty() 傳回一個值,指示屬性是否可設定。 yii\base\Component
checkAccess() yii\rbac\PhpManager
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
createPermission() 建立新的 Permission 物件。 yii\rbac\BaseManager
createRole() 建立新的 Role 物件。 yii\rbac\BaseManager
detachBehavior() 從組件分離行為。 yii\base\Component
detachBehaviors() 從組件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此組件。 yii\base\Component
getAssignment() 傳回關於角色和使用者的指派資訊。 yii\rbac\PhpManager
getAssignments() 傳回指定使用者的所有角色指派資訊。 yii\rbac\PhpManager
getBehavior() 傳回指定的行為物件。 yii\base\Component
getBehaviors() 傳回附加到此組件的所有行為。 yii\base\Component
getChildRoles() 傳回指定角色的子角色。深度不限。 yii\rbac\PhpManager
getChildren() 傳回子權限和/或角色。 yii\rbac\PhpManager
getDefaultRoleInstances() 以 Role 物件陣列形式傳回 defaultRoles。 yii\rbac\BaseManager
getDefaultRoles() 取得預設角色 yii\rbac\BaseManager
getItem() 傳回指定的授權項目。 yii\rbac\PhpManager
getItems() 傳回指定類型的項目。 yii\rbac\PhpManager
getPermission() 傳回指定的權限。 yii\rbac\BaseManager
getPermissions() 傳回系統中的所有權限。 yii\rbac\BaseManager
getPermissionsByRole() 傳回指定角色代表的所有權限。 yii\rbac\PhpManager
getPermissionsByUser() 傳回使用者擁有的所有權限。 yii\rbac\PhpManager
getRole() 傳回指定的角色。 yii\rbac\BaseManager
getRoles() 傳回系統中的所有角色。 yii\rbac\BaseManager
getRolesByUser() {@inheritdoc} 此方法傳回的角色包含透過 $defaultRoles 指派的角色。 yii\rbac\PhpManager
getRule() 傳回指定名稱的規則。 yii\rbac\PhpManager
getRules() 傳回系統中所有可用的規則。 yii\rbac\PhpManager
getUserIdsByRole() 傳回指派給指定角色的所有使用者 ID。 yii\rbac\PhpManager
hasChild() 傳回一個值,指示子項目是否已存在於父項目中。 yii\rbac\PhpManager
hasEventHandlers() 傳回一個值,指示是否有任何處理常式附加到指定的事件。 yii\base\Component
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 傳回一個值,指示是否已為此組件定義屬性。 yii\base\Component
init() 初始化應用程式組件。 yii\rbac\PhpManager
off() 從此組件分離現有的事件處理常式。 yii\base\Component
on() 將事件處理常式附加到事件。 yii\base\Component
remove() 從 RBAC 系統移除角色、權限或規則。 yii\rbac\BaseManager
removeAll() 移除所有授權資料,包括角色、權限、規則和指派。 yii\rbac\PhpManager
removeAllAssignments() 移除所有角色指派。 yii\rbac\PhpManager
removeAllPermissions() 移除所有權限。 yii\rbac\PhpManager
removeAllRoles() 移除所有角色。 yii\rbac\PhpManager
removeAllRules() 移除所有規則。 yii\rbac\PhpManager
removeChild() 從父項目中移除子項目。 yii\rbac\PhpManager
removeChildren() 從其父項目中移除所有子項目。 yii\rbac\PhpManager
removeItem() 從 RBAC 系統移除授權項目。 yii\rbac\PhpManager
revoke() 從使用者撤銷角色。 yii\rbac\PhpManager
revokeAll() 從使用者撤銷所有角色。 yii\rbac\PhpManager
setDefaultRoles() 設定預設角色 yii\rbac\BaseManager
trigger() 觸發事件。 yii\base\Component
update() 更新系統中指定的角色、權限或規則。 yii\rbac\BaseManager
updateRule() 將規則更新至 RBAC 系統。 yii\rbac\PhpManager

受保護的方法

隱藏繼承的方法

方法 描述 定義於
addItem() 將授權項目新增至 RBAC 系統。 yii\rbac\PhpManager
addRule() 將規則新增至 RBAC 系統。 yii\rbac\PhpManager
checkAccessRecursive() 對指定使用者執行存取檢查。 yii\rbac\PhpManager
detectLoop() 檢查授權項目層次結構中是否存在迴圈。 yii\rbac\PhpManager
executeRule() 執行與指定授權項目關聯的規則。 yii\rbac\BaseManager
getChildrenRecursive() 遞迴尋找指定項目的所有子項目和孫子項目。 yii\rbac\PhpManager
getDirectPermissionsByUser() 傳回直接指派給使用者的所有權限。 yii\rbac\PhpManager
getInheritedPermissionsByUser() 傳回使用者從指派給他的角色繼承的所有權限。 yii\rbac\PhpManager
hasNoAssignments() 檢查 $assignments 陣列是否為空,以及 $defaultRoles 屬性是否也為空。 yii\rbac\BaseManager
invalidateScriptCache() 使給定檔案的預編譯腳本快取(例如 OPCache 或 APC)失效。 yii\rbac\PhpManager
load() 從持久儲存載入授權資料。 yii\rbac\PhpManager
loadFromFile() 從 PHP 腳本檔案載入授權資料。 yii\rbac\PhpManager
removeAllItems() 移除指定類型的所有授權項目。 yii\rbac\PhpManager
removeRule() 從 RBAC 系統移除規則。 yii\rbac\PhpManager
save() 將授權資料儲存到持久儲存。 yii\rbac\PhpManager
saveAssignments() 將指派資料儲存到持久儲存。 yii\rbac\PhpManager
saveItems() 將項目資料儲存到持久儲存。 yii\rbac\PhpManager
saveRules() 將規則資料儲存到持久儲存。 yii\rbac\PhpManager
saveToFile() 將授權資料儲存到 PHP 腳本檔案。 yii\rbac\PhpManager
updateItem() 更新 RBAC 系統中的授權項目。 yii\rbac\PhpManager

屬性詳細資訊

隱藏繼承的屬性

$assignmentFile 公開屬性

包含授權指派的 PHP 腳本路徑。這可以是檔案路徑或路徑別名指向檔案。如果需要線上變更授權,請確保 Web 伺服器程序可以寫入此檔案。

另請參閱

public string $assignmentFile '@app/rbac/assignments.php'
$assignments 受保護的屬性
protected array $assignments = []
$children 受保護的屬性
protected array $children = []
$itemFile 公開屬性

包含授權項目的 PHP 腳本路徑。這可以是檔案路徑或路徑別名指向檔案。如果需要線上變更授權,請確保 Web 伺服器程序可以寫入此檔案。

另請參閱

public string $itemFile '@app/rbac/items.php'
$items 受保護的屬性
protected yii\rbac\Item[] $items = []
$ruleFile 公開屬性

包含授權規則的 PHP 腳本路徑。這可以是檔案路徑或路徑別名指向檔案。如果需要線上變更授權,請確保 Web 伺服器程序可以寫入此檔案。

另請參閱

public string $ruleFile '@app/rbac/rules.php'
$rules 受保護的屬性
protected yii\rbac\Rule[] $rules = []

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

定義於: yii\base\Component::__call()

呼叫指定的非類別方法。

此方法將檢查是否有任何附加的行為具有指定的方法,如果有,則會執行它。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時,會隱含地呼叫它。

public mixed __call ( $name, $params )
$name 字串

方法名稱

$params 陣列

方法參數

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()");
}

            
__clone() 公開方法

定義於: yii\base\Component::__clone()

在透過複製現有物件建立物件後,會呼叫此方法。

它會移除所有行為,因為它們附加到舊物件。

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() 公開方法

定義於: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的組態 $config 初始化物件。
  • 呼叫 init()

如果在子類別中覆寫此方法,建議

  • 建構子的最後一個參數是組態陣列,如同此處的 $config
  • 在建構子結尾呼叫父類別的實作。
public void __construct ( $config = [] )
$config 陣列

將用於初始化物件屬性的名稱-值配對

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() 公開方法

定義於: yii\base\Component::__get()

傳回組件屬性的值。

此方法將依以下順序檢查並採取相應行動

  • getter 定義的屬性:傳回 getter 結果
  • 行為的屬性:傳回行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property; 時,會隱含地呼叫它。

另請參閱 __set()

public mixed __get ( $name )
$name 字串

屬性名稱

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);
}

            
__isset() 公開方法

定義於: yii\base\Component::__isset()

檢查屬性是否已設定,即已定義且非空值。

此方法將依以下順序檢查並採取相應行動

  • setter 定義的屬性:傳回屬性是否已設定
  • 行為的屬性:傳回屬性是否已設定
  • 對於不存在的屬性,傳回 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name 字串

屬性名稱或事件名稱

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;
}

            
__set() 公開方法

定義於: yii\base\Component::__set()

設定組件屬性的值。

此方法將依以下順序檢查並採取相應行動

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value; 時,會隱含地呼叫它。

另請參閱 __get()

public void __set ( $name, $value )
$name 字串

屬性名稱或事件名稱

$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);
}

            
__unset() 公開方法

定義於: yii\base\Component::__unset()

將組件屬性設定為空值。

此方法將依以下順序檢查並採取相應行動

  • setter 定義的屬性:將屬性值設定為空值
  • 行為的屬性:將屬性值設定為空值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name 字串

屬性名稱

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);
}

            
add() 公開方法

定義於: yii\rbac\BaseManager::add()

將角色、權限或規則新增至 RBAC 系統。

public boolean add ( $object )
$object yii\rbac\Role|yii\rbac\Permission|yii\rbac\Rule
return boolean

角色、權限或規則是否成功新增至系統

throws Exception

如果資料驗證或儲存失敗(例如角色或權限的名稱不是唯一的)

                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.');
}

            
addChild() 公開方法

將項目新增為另一個項目的子項目。

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 (!isset($this->items[$parent->name], $this->items[$child->name])) {
        throw new InvalidArgumentException("Either '{$parent->name}' or '{$child->name}' does not exist.");
    }
    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.");
    }
    if (isset($this->children[$parent->name][$child->name])) {
        throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
    }
    $this->children[$parent->name][$child->name] = $this->items[$child->name];
    $this->saveItems();
    return true;
}

            
addItem() 受保護的方法

將授權項目新增至 RBAC 系統。

protected boolean addItem ( $item )
$item yii\rbac\Item

要新增的項目

return boolean

授權項目是否成功新增至系統

throws Exception

如果資料驗證或儲存失敗(例如角色或權限的名稱不是唯一的)

                protected function addItem($item)
{
    $time = time();
    if ($item->createdAt === null) {
        $item->createdAt = $time;
    }
    if ($item->updatedAt === null) {
        $item->updatedAt = $time;
    }
    $this->items[$item->name] = $item;
    $this->saveItems();
    return true;
}

            
addRule() 受保護的方法

將規則新增至 RBAC 系統。

protected boolean addRule ( $rule )
$rule yii\rbac\Rule

要新增的規則

return boolean

規則是否成功新增至系統

throws Exception

如果資料驗證或儲存失敗(例如規則的名稱不是唯一的)

                protected function addRule($rule)
{
    $this->rules[$rule->name] = $rule;
    $this->saveRules();
    return true;
}

            
assign() 公開方法

將角色指派給使用者。

public yii\rbac\Assignment assign ( $role, $userId )
$role yii\rbac\Role|yii\rbac\Permission
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Assignment

角色指派資訊。

throws Exception

如果角色已指派給使用者

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

            
attachBehavior() public 方法

定義於: yii\base\Component::attachBehavior()

將行為附加到此組件。

此方法會根據給定的配置建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此元件。

另請參閱 detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name 字串

行為的名稱。

$behavior string|array|yii\base\Behavior

行為配置。可以是下列其中一種

return yii\base\Behavior

行為物件

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public 方法

定義於: yii\base\Component::attachBehaviors()

將行為列表附加到組件。

每個行為都以其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的配置陣列。

另請參閱 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors 陣列

要附加到元件的行為列表

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public 方法

定義於: yii\base\Component::behaviors()

傳回此組件應表現為的行為列表。

子類別可以覆寫此方法,以指定它們想要表現為的行為。

此方法的傳回值應為行為物件或配置的陣列,並以行為名稱索引。行為配置可以是指定行為類別的字串,或是以下結構的陣列

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

請注意,行為類別必須繼承自 yii\base\Behavior。行為可以使用名稱或匿名方式附加。當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。

在此方法中宣告的行為將會自動(依需求)附加到元件。

public array behaviors ( )
return 陣列

行為配置。

                public function behaviors()
{
    return [];
}

            
canAddChild() public 方法 (自版本 2.0.8 起可用)

檢查是否可以將子項目新增至父項目。

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);
}

            
canGetProperty() public 方法

定義於: yii\base\Component::canGetProperty()

傳回一個值,指示屬性是否可讀取。

如果符合以下條件,則可以讀取屬性

  • 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$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;
}

            
canSetProperty() public 方法

定義於: yii\base\Component::canSetProperty()

傳回一個值,指示屬性是否可設定。

如果符合以下條件,則可以寫入屬性

  • 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫屬性(當 $checkBehaviors 為 true 時)。

另請參閱 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$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;
}

            
checkAccess() public 方法

public void checkAccess ( $userId, $permissionName, $params = [] )
$userId
$permissionName
$params

                public function checkAccess($userId, $permissionName, $params = [])
{
    $assignments = $this->getAssignments($userId);
    if ($this->hasNoAssignments($assignments)) {
        return false;
    }
    return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
}

            
checkAccessRecursive() protected 方法

對指定使用者執行存取檢查。

此方法由 checkAccess() 內部呼叫。

protected boolean checkAccessRecursive ( $user, $itemName, $params, $assignments )
$user 字串|整數

使用者 ID。這應該是表示使用者唯一識別碼的整數或字串。請參閱 yii\web\User::$id

$itemName 字串

需要存取檢查的操作名稱

$params 陣列

將傳遞給與指派給使用者的任務和角色相關聯的規則的名稱-值配對。名稱為 'user' 的參數會新增至此陣列,其中包含 $userId 的值。

$assignments yii\rbac\Assignment[]

指派給指定使用者的項目

return boolean

使用者是否可以執行操作。

                protected function checkAccessRecursive($user, $itemName, $params, $assignments)
{
    if (!isset($this->items[$itemName])) {
        return false;
    }
    /* @var $item Item */
    $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;
    }
    foreach ($this->children as $parentName => $children) {
        if (isset($children[$itemName]) && $this->checkAccessRecursive($user, $parentName, $params, $assignments)) {
            return true;
        }
    }
    return false;
}

            
className() public static 方法
自 2.0.14 版本起已棄用。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整限定名稱。

public static string className ( )
return 字串

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
createPermission() public 方法

定義於: yii\rbac\BaseManager::createPermission()

建立新的 Permission 物件。

請注意,新建立的權限尚未新增至 RBAC 系統。您必須填寫所需的資料並呼叫 add() 以將其新增至系統。

public yii\rbac\Permission createPermission ( $name )
$name 字串

權限名稱

return yii\rbac\Permission

新的 Permission 物件

                public function createPermission($name)
{
    $permission = new Permission();
    $permission->name = $name;
    return $permission;
}

            
createRole() public 方法

定義於: yii\rbac\BaseManager::createRole()

建立新的 Role 物件。

請注意,新建立的角色尚未新增至 RBAC 系統。您必須填寫所需的資料並呼叫 add() 以將其新增至系統。

public yii\rbac\Role createRole ( $name )
$name 字串

角色名稱

return yii\rbac\Role

新的 Role 物件

                public function createRole($name)
{
    $role = new Role();
    $role->name = $name;
    return $role;
}

            
detachBehavior() public 方法

定義於: yii\base\Component::detachBehavior()

從組件分離行為。

將會調用行為的 yii\base\Behavior::detach() 方法。

public yii\base\Behavior|null detachBehavior ( $name )
$name 字串

行為的名稱。

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;
}

            
detachBehaviors() public 方法

定義於: yii\base\Component::detachBehaviors()

從組件分離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
detectLoop() protected 方法

檢查授權項目層次結構中是否存在迴圈。

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;
    }
    if (!isset($this->children[$child->name], $this->items[$parent->name])) {
        return false;
    }
    foreach ($this->children[$child->name] as $grandchild) {
        /* @var $grandchild Item */
        if ($this->detectLoop($parent, $grandchild)) {
            return true;
        }
    }
    return false;
}

            
ensureBehaviors() public 方法

定義於: 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);
        }
    }
}

            
executeRule() protected 方法

定義於: yii\rbac\BaseManager::executeRule()

執行與指定授權項目關聯的規則。

如果項目未指定規則,此方法將傳回 true。否則,它將傳回 yii\rbac\Rule::execute() 的值。

protected boolean executeRule ( $user, $item, $params )
$user 字串|整數

使用者 ID。這應該是表示使用者唯一識別碼的整數或字串。請參閱 yii\web\User::$id

$item yii\rbac\Item

需要執行其規則的授權項目

$params 陣列

傳遞給 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}");
}

            
getAssignment() public 方法

傳回關於角色和使用者的指派資訊。

public yii\rbac\Assignment|null getAssignment ( $roleName, $userId )
$roleName 字串

角色名稱

$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Assignment|null

指派資訊。如果角色未指派給使用者,則傳回 Null。

                public function getAssignment($roleName, $userId)
{
    return isset($this->assignments[$userId][$roleName]) ? $this->assignments[$userId][$roleName] : null;
}

            
getAssignments() public 方法

傳回指定使用者的所有角色指派資訊。

public yii\rbac\Assignment[] getAssignments ( $userId )
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Assignment[]

以角色名稱索引的指派項目。如果沒有角色指派給使用者,將傳回空陣列。

                public function getAssignments($userId)
{
    return isset($this->assignments[$userId]) ? $this->assignments[$userId] : [];
}

            
getBehavior() public 方法

定義於: yii\base\Component::getBehavior()

傳回指定的行為物件。

public yii\base\Behavior|null getBehavior ( $name )
$name 字串

行為名稱

return yii\base\Behavior|null

行為物件,如果行為不存在則為 null

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public 方法

定義於: yii\base\Component::getBehaviors()

傳回附加到此組件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

附加到此元件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getChildRoles() public 方法 (自版本 2.0.10 起可用)

傳回指定角色的子角色。深度不限。

public yii\rbac\Role[] getChildRoles ( $roleName )
$roleName 字串

要尋找子角色的角色名稱

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, $result);
    $roles = [$roleName => $role];
    $roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
        return array_key_exists($roleItem->name, $result);
    });
    return $roles;
}

            
getChildren() public 方法

傳回子權限和/或角色。

public yii\rbac\Item[] getChildren ( $name )
$name 字串

父名稱

return yii\rbac\Item[]

子權限和/或角色

                public function getChildren($name)
{
    return isset($this->children[$name]) ? $this->children[$name] : [];
}

            
getChildrenRecursive() protected 方法

遞迴尋找指定項目的所有子項目和孫子項目。

protected void getChildrenRecursive ( $name, &$result )
$name 字串

要尋找其子項目的項目名稱。

$result 陣列

子項目和孫子項目(在陣列鍵中)

                protected function getChildrenRecursive($name, &$result)
{
    if (isset($this->children[$name])) {
        foreach ($this->children[$name] as $child) {
            $result[$child->name] = true;
            $this->getChildrenRecursive($child->name, $result);
        }
    }
}

            
getDefaultRoleInstances() public 方法 (自版本 2.0.12 起可用)

定義於: 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;
}

            
getDefaultRoles() public 方法 (自版本 2.0.14 起可用)

定義於: yii\rbac\BaseManager::getDefaultRoles()

取得預設角色

public string[] getDefaultRoles ( )
return 字串[]

預設角色

                public function getDefaultRoles()
{
    return $this->defaultRoles;
}

            
getDirectPermissionsByUser() protected 方法 (自版本 2.0.7 起可用)

傳回直接指派給使用者的所有權限。

protected yii\rbac\Permission[] getDirectPermissionsByUser ( $userId )
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Permission[]

使用者擁有的所有直接權限。陣列以權限名稱索引。

                protected function getDirectPermissionsByUser($userId)
{
    $permissions = [];
    foreach ($this->getAssignments($userId) as $name => $assignment) {
        $permission = $this->items[$assignment->roleName];
        if ($permission->type === Item::TYPE_PERMISSION) {
            $permissions[$name] = $permission;
        }
    }
    return $permissions;
}

            
getInheritedPermissionsByUser() protected 方法 (自版本 2.0.7 起可用)

傳回使用者從指派給他的角色繼承的所有權限。

protected yii\rbac\Permission[] getInheritedPermissionsByUser ( $userId )
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Permission[]

使用者擁有的所有繼承權限。陣列以權限名稱索引。

                protected function getInheritedPermissionsByUser($userId)
{
    $assignments = $this->getAssignments($userId);
    $result = [];
    foreach (array_keys($assignments) as $roleName) {
        $this->getChildrenRecursive($roleName, $result);
    }
    if (empty($result)) {
        return [];
    }
    $permissions = [];
    foreach (array_keys($result) as $itemName) {
        if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
            $permissions[$itemName] = $this->items[$itemName];
        }
    }
    return $permissions;
}

            
getItem() public 方法

傳回指定的授權項目。

public yii\rbac\Item|null getItem ( $name )
$name 字串

授權項目名稱。

return yii\rbac\Item|null

對應於指定名稱的授權項目。如果沒有此項目,則傳回 Null。

                public function getItem($name)
{
    return isset($this->items[$name]) ? $this->items[$name] : null;
}

            
getItems() public 方法

傳回指定類型的項目。

public yii\rbac\Item[] getItems ( $type )
$type integer(整數)

授權項目類型 (可以是 yii\rbac\Item::TYPE_ROLE 或是 yii\rbac\Item::TYPE_PERMISSION)

return yii\rbac\Item[]

指定類型的授權項目。

                public function getItems($type)
{
    $items = [];
    foreach ($this->items as $name => $item) {
        /* @var $item Item */
        if ($item->type == $type) {
            $items[$name] = $item;
        }
    }
    return $items;
}

            
getPermission() public 方法

定義於: yii\rbac\BaseManager::getPermission()

傳回指定的權限。

public yii\rbac\Permission|null getPermission ( $name )
$name 字串

權限名稱。

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;
}

            
getPermissions() public 方法

定義於: yii\rbac\BaseManager::getPermissions()

傳回系統中的所有權限。

public yii\rbac\Permission[] getPermissions ( )
return yii\rbac\Permission[]

系統中的所有權限。陣列以權限名稱索引。

                public function getPermissions()
{
    return $this->getItems(Item::TYPE_PERMISSION);
}

            
getPermissionsByRole() public 方法

傳回指定角色代表的所有權限。

public yii\rbac\Permission[] getPermissionsByRole ( $roleName )
$roleName 字串

角色名稱

return yii\rbac\Permission[]

角色代表的所有權限。陣列以權限名稱索引。

                public function getPermissionsByRole($roleName)
{
    $result = [];
    $this->getChildrenRecursive($roleName, $result);
    if (empty($result)) {
        return [];
    }
    $permissions = [];
    foreach (array_keys($result) as $itemName) {
        if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
            $permissions[$itemName] = $this->items[$itemName];
        }
    }
    return $permissions;
}

            
getPermissionsByUser() public 方法

傳回使用者擁有的所有權限。

public yii\rbac\Permission[] getPermissionsByUser ( $userId )
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return yii\rbac\Permission[]

使用者擁有的所有權限。陣列以權限名稱索引。

                public function getPermissionsByUser($userId)
{
    $directPermission = $this->getDirectPermissionsByUser($userId);
    $inheritedPermission = $this->getInheritedPermissionsByUser($userId);
    return array_merge($directPermission, $inheritedPermission);
}

            
getRole() public 方法

定義於: yii\rbac\BaseManager::getRole()

傳回指定的角色。

public yii\rbac\Role|null getRole ( $name )
$name 字串

角色名稱。

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;
}

            
getRoles() public 方法

定義於: yii\rbac\BaseManager::getRoles()

傳回系統中的所有角色。

public yii\rbac\Role[] getRoles ( )
return yii\rbac\Role[]

系統中的所有角色。陣列以角色名稱索引。

                public function getRoles()
{
    return $this->getItems(Item::TYPE_ROLE);
}

            
getRolesByUser() public 方法

{@inheritdoc} 此方法傳回的角色包含透過 $defaultRoles 指派的角色。

public void getRolesByUser ( $userId )
$userId

                public function getRolesByUser($userId)
{
    $roles = $this->getDefaultRoleInstances();
    foreach ($this->getAssignments($userId) as $name => $assignment) {
        $role = $this->items[$assignment->roleName];
        if ($role->type === Item::TYPE_ROLE) {
            $roles[$name] = $role;
        }
    }
    return $roles;
}

            
getRule() public 方法

傳回指定名稱的規則。

public yii\rbac\Rule|null getRule ( $name )
$name 字串

規則名稱

return yii\rbac\Rule|null

規則物件,如果指定名稱不對應於規則,則為 null。

                public function getRule($name)
{
    return isset($this->rules[$name]) ? $this->rules[$name] : null;
}

            
getRules() public 方法

傳回系統中所有可用的規則。

public yii\rbac\Rule[] getRules ( )
return yii\rbac\Rule[]

以規則名稱索引的規則

                public function getRules()
{
    return $this->rules;
}

            
getUserIdsByRole() public 方法 (自版本 2.0.7 起可用)

傳回指派給指定角色的所有使用者 ID。

public array getUserIdsByRole ( $roleName )
$roleName 字串
return 陣列

使用者 ID 字串陣列

                public function getUserIdsByRole($roleName)
{
    $result = [];
    foreach ($this->assignments as $userID => $assignments) {
        foreach ($assignments as $userAssignment) {
            if ($userAssignment->roleName === $roleName && $userAssignment->userId == $userID) {
                $result[] = (string) $userID;
            }
        }
    }
    return $result;
}

            
hasChild() public 方法

傳回一個值,指示子項目是否已存在於父項目中。

public boolean hasChild ( $parent, $child )
$parent yii\rbac\Item
$child yii\rbac\Item
return boolean

`$child` 是否已是 `$parent` 的子項目

                public function hasChild($parent, $child)
{
    return isset($this->children[$parent->name][$child->name]);
}

            
hasEventHandlers() public 方法

定義於: yii\base\Component::hasEventHandlers()

傳回一個值,指示是否有任何處理常式附加到指定的事件。

public boolean hasEventHandlers ( $name )
$name 字串

事件名稱

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);
}

            
hasMethod() public 方法

定義於: yii\base\Component::hasMethod()

傳回一個值,指示是否已定義方法。

方法在以下情況下定義:

  • 類別具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 `$checkBehaviors` 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name 字串

屬性名稱

$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;
}

            
hasNoAssignments() protected 方法 (自版本 2.0.11 起可用)

定義於: yii\rbac\BaseManager::hasNoAssignments()

檢查 $assignments 陣列是否為空,以及 $defaultRoles 屬性是否也為空。

protected array hasNoAssignments ( array $assignments )
$assignments yii\rbac\Assignment[]

使用者的指派陣列

return boolean

`$assignments` 陣列是否為空,且 $defaultRoles 屬性也為空

                protected function hasNoAssignments(array $assignments)
{
    return empty($assignments) && empty($this->defaultRoles);
}

            
hasProperty() public 方法

定義於: yii\base\Component::hasProperty()

傳回一個值,指示是否已為此組件定義屬性。

屬性在以下情況下定義:

  • 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 `$checkBehaviors` 為 true 時)。

另請參閱

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name 字串

屬性名稱

$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);
}

            
init() public 方法

初始化應用程式組件。

此方法通過從 PHP 腳本載入授權資料來覆寫父類別的實作。

public void init ( )

                public function init()
{
    parent::init();
    $this->itemFile = Yii::getAlias($this->itemFile);
    $this->assignmentFile = Yii::getAlias($this->assignmentFile);
    $this->ruleFile = Yii::getAlias($this->ruleFile);
    $this->load();
}

            
invalidateScriptCache() protected 方法 (自版本 2.0.9 起可用)

使給定檔案的預編譯腳本快取(例如 OPCache 或 APC)失效。

protected void invalidateScriptCache ( $file )
$file 字串

檔案路徑。

                protected function invalidateScriptCache($file)
{
    if (function_exists('opcache_invalidate')) {
        opcache_invalidate($file, true);
    }
    if (function_exists('apc_delete_file')) {
        @apc_delete_file($file);
    }
}

            
load() protected 方法

從持久儲存載入授權資料。

protected void load ( )

                protected function load()
{
    $this->children = [];
    $this->rules = [];
    $this->assignments = [];
    $this->items = [];
    $items = $this->loadFromFile($this->itemFile);
    $itemsMtime = @filemtime($this->itemFile);
    $assignments = $this->loadFromFile($this->assignmentFile);
    $assignmentsMtime = @filemtime($this->assignmentFile);
    $rules = $this->loadFromFile($this->ruleFile);
    foreach ($items as $name => $item) {
        $class = $item['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
        $this->items[$name] = new $class([
            'name' => $name,
            'description' => isset($item['description']) ? $item['description'] : null,
            'ruleName' => isset($item['ruleName']) ? $item['ruleName'] : null,
            'data' => isset($item['data']) ? $item['data'] : null,
            'createdAt' => $itemsMtime,
            'updatedAt' => $itemsMtime,
        ]);
    }
    foreach ($items as $name => $item) {
        if (isset($item['children'])) {
            foreach ($item['children'] as $childName) {
                if (isset($this->items[$childName])) {
                    $this->children[$name][$childName] = $this->items[$childName];
                }
            }
        }
    }
    foreach ($assignments as $userId => $roles) {
        foreach ($roles as $role) {
            $this->assignments[$userId][$role] = new Assignment([
                'userId' => $userId,
                'roleName' => $role,
                'createdAt' => $assignmentsMtime,
            ]);
        }
    }
    foreach ($rules as $name => $ruleData) {
        $this->rules[$name] = unserialize($ruleData);
    }
}

            
loadFromFile() protected 方法

從 PHP 腳本檔案載入授權資料。

另請參閱 saveToFile()

protected array loadFromFile ( $file )
$file 字串

檔案路徑。

return 陣列

授權資料

                protected function loadFromFile($file)
{
    if (is_file($file)) {
        return require $file;
    }
    return [];
}

            
off() public 方法

定義於: yii\base\Component::off()

從此組件分離現有的事件處理常式。

此方法與 on() 相反。

注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純文字名稱註冊的處理常式將保留。

另請參閱 on()

public boolean off ( $name, $handler null )
$name 字串

事件名稱

$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;
}

            
on() public 方法

定義於: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理常式必須是有效的 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 字串

事件名稱

$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]);
    }
}

            
remove() public 方法

定義於: 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.');
}

            
removeAll() public 方法

移除所有授權資料,包括角色、權限、規則和指派。

public void removeAll ( )

                public function removeAll()
{
    $this->children = [];
    $this->items = [];
    $this->assignments = [];
    $this->rules = [];
    $this->save();
}

            
removeAllAssignments() public 方法

移除所有角色指派。

public void removeAllAssignments ( )

                public function removeAllAssignments()
{
    $this->assignments = [];
    $this->saveAssignments();
}

            
removeAllItems() protected 方法

移除指定類型的所有授權項目。

protected void removeAllItems ( $type )
$type integer(整數)

授權項目類型 (可以是 Item::TYPE_PERMISSION 或是 Item::TYPE_ROLE)

                protected function removeAllItems($type)
{
    $names = [];
    foreach ($this->items as $name => $item) {
        if ($item->type == $type) {
            unset($this->items[$name]);
            $names[$name] = true;
        }
    }
    if (empty($names)) {
        return;
    }
    foreach ($this->assignments as $i => $assignments) {
        foreach ($assignments as $n => $assignment) {
            if (isset($names[$assignment->roleName])) {
                unset($this->assignments[$i][$n]);
            }
        }
    }
    foreach ($this->children as $name => $children) {
        if (isset($names[$name])) {
            unset($this->children[$name]);
        } else {
            foreach ($children as $childName => $item) {
                if (isset($names[$childName])) {
                    unset($children[$childName]);
                }
            }
            $this->children[$name] = $children;
        }
    }
    $this->saveItems();
}

            
removeAllPermissions() public 方法

移除所有權限。

所有父子關係將相應地調整。

public void removeAllPermissions ( )

                public function removeAllPermissions()
{
    $this->removeAllItems(Item::TYPE_PERMISSION);
}

            
removeAllRoles() public 方法

移除所有角色。

所有父子關係將相應地調整。

public void removeAllRoles ( )

                public function removeAllRoles()
{
    $this->removeAllItems(Item::TYPE_ROLE);
}

            
removeAllRules() public 方法

移除所有規則。

具有規則的所有角色和權限將相應地調整。

public void removeAllRules ( )

                public function removeAllRules()
{
    foreach ($this->items as $item) {
        $item->ruleName = null;
    }
    $this->rules = [];
    $this->saveRules();
}

            
removeChild() public 方法

從父項目中移除子項目。

注意,子項目不會被刪除。僅移除父子關係。

public boolean removeChild ( $parent, $child )
$parent yii\rbac\Item
$child yii\rbac\Item
return boolean

移除是否成功

                public function removeChild($parent, $child)
{
    if (isset($this->children[$parent->name][$child->name])) {
        unset($this->children[$parent->name][$child->name]);
        $this->saveItems();
        return true;
    }
    return false;
}

            
removeChildren() public 方法

從其父項目中移除所有子項目。

注意,子項目不會被刪除。僅移除父子關係。

public boolean removeChildren ( $parent )
$parent yii\rbac\Item
return boolean

移除是否成功

                public function removeChildren($parent)
{
    if (isset($this->children[$parent->name])) {
        unset($this->children[$parent->name]);
        $this->saveItems();
        return true;
    }
    return false;
}

            
removeItem() public 方法

從 RBAC 系統移除授權項目。

public boolean removeItem ( $item )
$item yii\rbac\Item

要移除的項目

return boolean

角色或權限是否已成功移除

throws Exception

如果資料驗證或儲存失敗(例如角色或權限的名稱不是唯一的)

                public function removeItem($item)
{
    if (isset($this->items[$item->name])) {
        foreach ($this->children as &$children) {
            unset($children[$item->name]);
        }
        foreach ($this->assignments as &$assignments) {
            unset($assignments[$item->name]);
        }
        unset($this->items[$item->name]);
        $this->saveItems();
        $this->saveAssignments();
        return true;
    }
    return false;
}

            
removeRule() protected 方法

從 RBAC 系統移除規則。

protected boolean removeRule ( $rule )
$rule yii\rbac\Rule

要移除的規則

return boolean

規則是否已成功移除

throws Exception

如果資料驗證或儲存失敗(例如規則的名稱不是唯一的)

                protected function removeRule($rule)
{
    if (isset($this->rules[$rule->name])) {
        unset($this->rules[$rule->name]);
        foreach ($this->items as $item) {
            if ($item->ruleName === $rule->name) {
                $item->ruleName = null;
            }
        }
        $this->saveRules();
        return true;
    }
    return false;
}

            
revoke() public 方法

從使用者撤銷角色。

public boolean revoke ( $role, $userId )
$role yii\rbac\Role|yii\rbac\Permission
$userId 字串|整數

使用者 ID(請參閱 yii\web\User::$id

return boolean

撤銷是否成功

                public function revoke($role, $userId)
{
    if (isset($this->assignments[$userId][$role->name])) {
        unset($this->assignments[$userId][$role->name]);
        $this->saveAssignments();
        return true;
    }
    return false;
}

            
revokeAll() public 方法

從使用者撤銷所有角色。

public boolean revokeAll ( $userId )
$userId mixed

使用者 ID(請參閱 yii\web\User::$id

return boolean

撤銷是否成功

                public function revokeAll($userId)
{
    if (isset($this->assignments[$userId]) && is_array($this->assignments[$userId])) {
        foreach ($this->assignments[$userId] as $itemName => $value) {
            unset($this->assignments[$userId][$itemName]);
        }
        $this->saveAssignments();
        return true;
    }
    return false;
}

            
save() protected method

將授權資料儲存到持久儲存。

protected void save ( )

                protected function save()
{
    $this->saveItems();
    $this->saveAssignments();
    $this->saveRules();
}

            
saveAssignments() protected method

將指派資料儲存到持久儲存。

protected void saveAssignments ( )

                protected function saveAssignments()
{
    $assignmentData = [];
    foreach ($this->assignments as $userId => $assignments) {
        foreach ($assignments as $name => $assignment) {
            /* @var $assignment Assignment */
            $assignmentData[$userId][] = $assignment->roleName;
        }
    }
    $this->saveToFile($assignmentData, $this->assignmentFile);
}

            
saveItems() protected method

將項目資料儲存到持久儲存。

protected void saveItems ( )

                protected function saveItems()
{
    $items = [];
    foreach ($this->items as $name => $item) {
        /* @var $item Item */
        $items[$name] = array_filter(
            [
                'type' => $item->type,
                'description' => $item->description,
                'ruleName' => $item->ruleName,
                'data' => $item->data,
            ]
        );
        if (isset($this->children[$name])) {
            foreach ($this->children[$name] as $child) {
                /* @var $child Item */
                $items[$name]['children'][] = $child->name;
            }
        }
    }
    $this->saveToFile($items, $this->itemFile);
}

            
saveRules() protected method

將規則資料儲存到持久儲存。

protected void saveRules ( )

                protected function saveRules()
{
    $rules = [];
    foreach ($this->rules as $name => $rule) {
        $rules[$name] = serialize($rule);
    }
    $this->saveToFile($rules, $this->ruleFile);
}

            
saveToFile() protected method

將授權資料儲存到 PHP 腳本檔案。

另請參閱 loadFromFile()

protected void saveToFile ( $data, $file )
$data 陣列

授權資料

$file 字串

檔案路徑。

                protected function saveToFile($data, $file)
{
    file_put_contents($file, "<?php\n\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
    $this->invalidateScriptCache($file);
}

            
setDefaultRoles() public method (自版本 2.0.14 起可用)

定義於: 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');
    }
}

            
trigger() public method

定義於: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它會調用事件的所有附加處理程序,包括類別層級的處理程序。

public void trigger ( $name, yii\base\Event $event null )
$name 字串

事件名稱

$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);
}

            
update() public method

定義於: yii\rbac\BaseManager::update()

更新系統中指定的角色、權限或規則。

public boolean update ( $name, $object )
$name 字串

角色、權限或規則的舊名稱

$object yii\rbac\Role|yii\rbac\Permission|yii\rbac\Rule
return boolean

更新是否成功

throws Exception

如果資料驗證或儲存失敗(例如角色或權限的名稱不是唯一的)

                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.');
}

            
updateItem() protected method

更新 RBAC 系統中的授權項目。

protected boolean updateItem ( $name, $item )
$name 字串

正在更新的項目的名稱

$item yii\rbac\Item

已更新的項目

return boolean

授權項目是否成功更新

throws Exception

如果資料驗證或儲存失敗(例如角色或權限的名稱不是唯一的)

                protected function updateItem($name, $item)
{
    if ($name !== $item->name) {
        if (isset($this->items[$item->name])) {
            throw new InvalidArgumentException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
        }
        // Remove old item in case of renaming
        unset($this->items[$name]);
        if (isset($this->children[$name])) {
            $this->children[$item->name] = $this->children[$name];
            unset($this->children[$name]);
        }
        foreach ($this->children as &$children) {
            if (isset($children[$name])) {
                $children[$item->name] = $children[$name];
                unset($children[$name]);
            }
        }
        foreach ($this->assignments as &$assignments) {
            if (isset($assignments[$name])) {
                $assignments[$item->name] = $assignments[$name];
                $assignments[$item->name]->roleName = $item->name;
                unset($assignments[$name]);
            }
        }
        $this->saveAssignments();
    }
    $this->items[$item->name] = $item;
    $this->saveItems();
    return true;
}

            
updateRule() public method

將規則更新至 RBAC 系統。

public boolean updateRule ( $name, $rule )
$name 字串

正在更新的規則的名稱

$rule yii\rbac\Rule

已更新的規則

return boolean

規則是否成功更新

throws Exception

如果資料驗證或儲存失敗(例如規則的名稱不是唯一的)

                public function updateRule($name, $rule)
{
    if ($rule->name !== $name) {
        unset($this->rules[$name]);
    }
    $this->rules[$rule->name] = $rule;
    $this->saveRules();
    return true;
}