In my project I need to store role hierarchy in database and create new roles dynamically.
In Symfony2 role hierarchy is stored in security.yml by default.
What
Since role hierarchy don't change often, this a quick class to cache to memcached.
hierarchy = $hierarchy;
$roleMap = $memcache->get('roleMap');
if ($roleMap) {
$this->map = unserialize($roleMap);
} else {
$this->buildRoleMap();
// cache to memcache
$memcache->set('roleMap', serialize($this->map));
}
}
/**
* {@inheritdoc}
*/
public function getReachableRoles(array $roles)
{
$reachableRoles = $roles;
foreach ($roles as $role) {
if (!isset($this->map[$role->getRole()])) {
continue;
}
foreach ($this->map[$role->getRole()] as $r) {
$reachableRoles[] = new Role($r);
}
}
return $reachableRoles;
}
protected function buildRoleMap()
{
$this->map = array();
foreach ($this->hierarchy as $main => $roles) {
$this->map[$main] = $roles;
$visited = array();
$additionalRoles = $roles;
while ($role = array_shift($additionalRoles)) {
if (!isset($this->hierarchy[$role])) {
continue;
}
$visited[] = $role;
$this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
$additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
}
}
}
}