This package provides RBAC (Role-Based Access Control) library. It is used in Yii Framework but is supposed to be usable separately.
composer require yiisoft/rbac
$manager = new Manager($storage, new ClassNameRuleFactory());
In the directory config will contain permissions and rules.
$manager->addPermission(new Permission('createPost'));
$manager->addPermission(new Permission('readPost'));
$manager->addPermission(new Permission('deletePost'));
After executing this code, this configuration will be saved in ../config/items.php
$manager->addRole(new Role('author'));
$manager->addRole(new Role('reader'));
$manager->addChild(
$storage->getRoleByName('reader'),
$storage->getPermissionByName('readPost')
);
$manager->addChild(
$storage->getRoleByName('author'),
$storage->getPermissionByName('createPost')
);
$manager->addChild(
$storage->getRoleByName('author'),
$storage->getRoleByName('reader')
);
$userId = 100;
$manager->assign($storage->getRoleByName('author'), $userId);
After executing this code, this configuration will be saved in ../config/assignments.php
if ($manager->userHasPermission($userId, 'createPost')) {
echo 'author has permission createPost';
}
$manager->addRule(new ActionRule());
$manager->addPermission(
(new Permission('viewList'))->withRuleName('action_rule')
);
The role will also support the rules.
class ActionRule extends Rule
{
public function __construct()
{
parent::__construct('action_rule');
}
public function execute(string $userId, Item $item, array $parameters = []): bool
{
return isset($parameters['action']) && $parameters['action'] === 'home';
}
}
$anotherUserId = 103;
if (!$manager->userHasPermission($anotherUserId, 'viewList', ['action' => 'home'])) {
echo 'reader not has permission index';
}
Storage | Description |
---|---|
PhpStorage | PHP file storage |
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
The package tests are checked with Infection mutation framework. To run it:
./vendor/bin/infection
The code is statically analyzed with Psalm. To run static analysis:
./vendor/bin/psalm
The Yii Role-Based Access Control Library is free software. It is released under the terms of the BSD License.
Please see LICENSE
for more information.
Maintained by Yii Software.