Skip to content

Instantly share code, notes, and snippets.

@kiaplayer
Created July 7, 2014 10:06
Show Gist options
  • Save kiaplayer/14f38392106d31e906fe to your computer and use it in GitHub Desktop.
Save kiaplayer/14f38392106d31e906fe to your computer and use it in GitHub Desktop.
<?php
namespace backend\components;
use yii\db\Query;
use yii\rbac\Item;
use yii\rbac\Role;
/**
* Class DbManager
*
* @package backend\components
*/
class DbManager extends \yii\rbac\DbManager
{
/**
* @var string имя роли с полными правами
*/
public $superRoleName = 'administrator';
/**
* @var string описание роли с полными правами
*/
public $superRoleDescription = 'Полные права';
/**
* @inheritdoc
*/
protected function addItem($item)
{
$result = parent::addItem($item);
if ($result && $item->type == Item::TYPE_PERMISSION) {
$superRole = $this->getRole($this->superRoleName);
$this->addChild($superRole, $item);
}
return $result;
}
/**
* @inheritdoc
*/
public function removeChild($parent, $child)
{
if ($child->type == Item::TYPE_PERMISSION && $parent->name == $this->superRoleName) {
return false;
}
return parent::removeChild($parent, $child);
}
/**
* @inheritdoc
*/
public function remove($object)
{
if ($object->type == Item::TYPE_ROLE && $object->name == $this->superRoleName) {
return false;
}
return parent::remove($object);
}
/**
* @inheritdoc
*/
public function revokeAll($userId)
{
if ($this->getAssignment($this->superRoleName, $userId)
&& count($this->getUsersByRole($this->getRole($this->superRoleName))) == 1) {
return false;
}
return parent::revokeAll($userId);
}
/**
* @inheritdoc
*/
public function revoke($role, $userId)
{
if ($role->name == $this->superRoleName && count($this->getUsersByRole($role)) == 1) {
return false;
}
return parent::revoke($role, $userId);
}
/**
* Возвращает массив идентификаторов пользователей, которые привязаны к роли
* @param Role $role
* @return array
*/
public function getUsersByRole($role)
{
return (new Query)
->select('user_id')
->from($this->assignmentTable)
->where(['item_name' => $role->name])
->column();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment