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 have I found:
There is a service security.role_hierarchy (Symfony\Component\Security\Core\Role\RoleHierarchy);
This service receives a roles array in constructor:
public function __construct(array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->buildRoleMap();
}
and the $hierarchy property is private.
This argument comes in constructor from \Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension::createRoleHierarchy()
which uses roles from config, as I understood:
$container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
It seems me that the best way is to compile an array of roles from database and set it as an argument for the service. But I haven’t yet understood how to do it.
The second way I see is to define my own RoleHierarchy class inherited from the base one. But since in the base RoleHierarchy class the $hierarchy property is defined as private, than I would have to redefine all the functions from the base RoleHierarchy class. But I don’t think it is a good OOP and Symfony way…
The solution was simple.
First I created a Role entity.
after that created a RoleHierarchy service, extended from the Symfony native one. I inherited the constructor, added an EntityManager there and provided an original constructor with a new roles array instead of the old one:
… and redefined it as a service:
That’s all.
Maybe, there is something unnecessary in my code. Maybe it is possible to write better. But I think, that main idea is evident now.