mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-09-08 07:44:59 +00:00
Refactor authorization helper to separate some methods
Methods regarding to role hierarchi are now delegated to a parent role helper.
This commit is contained in:
71
src/Bundle/ChillMainBundle/Security/ParentRoleHelper.php
Normal file
71
src/Bundle/ChillMainBundle/Security/ParentRoleHelper.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Security;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
||||
use Symfony\Component\Security\Core\Role\Role;
|
||||
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
|
||||
|
||||
/**
|
||||
* Helper which traverse all role to find parents
|
||||
*/
|
||||
class ParentRoleHelper
|
||||
{
|
||||
protected RoleHierarchyInterface $roleHierarchy;
|
||||
|
||||
/**
|
||||
* The role in a hierarchy, given by the parameter
|
||||
* `security.role_hierarchy.roles` from the container.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected array $hierarchy;
|
||||
|
||||
public function __construct(
|
||||
RoleHierarchyInterface $roleHierarchy,
|
||||
ParameterBagInterface $parameterBag
|
||||
) {
|
||||
$this->roleHierarchy = $roleHierarchy;
|
||||
$this->hierarchy = $parameterBag->get('security.role_hierarchy.roles');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all the role which give access to the given role. Only the role
|
||||
* which are registered into Chill are taken into account.
|
||||
*
|
||||
* @param string $role
|
||||
* @return string[] the role which give access to the given $role
|
||||
*/
|
||||
public function getParentRoles(string $role): array
|
||||
{
|
||||
$parentRoles = [];
|
||||
// transform the roles from role hierarchy from string to Role
|
||||
$roles = \array_keys($this->hierarchy);
|
||||
|
||||
foreach ($roles as $r) {
|
||||
$childRoles = $this->roleHierarchy->getReachableRoleNames([$r]);
|
||||
|
||||
if (\in_array($role, $childRoles)) {
|
||||
$parentRoles[] = $r;
|
||||
}
|
||||
}
|
||||
|
||||
return $parentRoles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a parent role may give access to a given child role
|
||||
*
|
||||
* @param string $childRole The role we want to test if he is reachable
|
||||
* @param string $parentRole The role which should give access to $childRole
|
||||
* @return bool true if the child role is granted by parent role
|
||||
*/
|
||||
public function isRoleReached($childRole, $parentRole): bool
|
||||
{
|
||||
$reachableRoles = $this->roleHierarchy
|
||||
->getReachableRoleNames([$parentRole]);
|
||||
|
||||
return in_array($childRole, $reachableRoles);
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user