Skip to content

Instantly share code, notes, and snippets.

@cystbear
Last active March 6, 2018 14:53
Show Gist options
  • Save cystbear/134fb5a3955d79f5512f to your computer and use it in GitHub Desktop.
Save cystbear/134fb5a3955d79f5512f to your computer and use it in GitHub Desktop.
Example of DynamicRoleHierarchy, how to fetch roles stored in DB and use them in regular Symfony2 security component
<?php
namespace Acme\SecurityBundle\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Acme\SecurityBundle\Entity\RoleRepository;
class DynamicRoleHierarchy implements RoleHierarchyInterface
{
protected $roleRepository;
protected $roleHierarchy = null;
public function __construct(RoleRepository $roleRepository)
{
$this->roleRepository = $roleRepository;
}
public function getReachableRoles(array $roles)
{
if (null === $this->roleHierarchy) {
$this->roleHierarchy = new RoleHierarchy($this->fetchRoleHierarchy());
}
return $this->roleHierarchy->getReachableRoles($roles);
}
protected function fetchRoleHierarchy()
{
$hierarchy = array();
$this->roleRepository;
// do your stuff with $this->roleRepository
return $hierarchy;
}
}
<!--
Probably you should not overwrite native Symfony services.
There will be better add your DynamicRoleHierarchy to RoleHierarchyVoter via CompilerPass
-->
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="security.role_hierarchy" class="Acme\SecurityBundle\Role\DynamicRoleHierarchy" public="false">
<argument type="service" id="your.role.repository" />
</service>
</services>
</container>
@cystbear
Copy link
Author

Did improvements that @stof noted

@tomtone
Copy link

tomtone commented Sep 4, 2016

while overwriting this service, you will get an error on cache:clear/warmup in prod environment. Role_hierarchy seems to be instantiated before proxy classes are generated...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment