2021-11-30 13:54:58 +01:00

120 lines
2.9 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security;
use function array_fill_keys;
use function array_key_exists;
class RoleProvider
{
/**
* @var ProvideRoleInterface[]
*/
private $providers = [];
/**
* an array where keys are the role, and value is the title
* for the given role.
*
* Null when not initialized.
*
* @var array|null
*/
private $rolesTitlesCache;
/**
* Add a role provider.
*
* @internal This function is called by the dependency injector: it inject provider
*
* @param \Chill\MainBundle\Security\ProvideRoleInterface $provider
*/
public function addProvider(ProvideRoleInterface $provider)
{
$this->providers[] = $provider;
}
public function getRoles(): array
{
$roles = [];
foreach ($this->providers as $provider) {
if ($provider->getRoles() !== null) {
$roles = array_merge($roles, $provider->getRoles());
}
}
return $roles;
}
public function getRolesWithoutScopes(): array
{
$roles = [];
foreach ($this->providers as $provider) {
if ($provider->getRolesWithoutScope() !== null) {
$roles = array_merge($roles, $provider->getRolesWithoutScope());
}
}
return $roles;
}
/**
* Get the title for each role.
*
* @param string $role
*
* @return string the title of the role
*/
public function getRoleTitle($role)
{
$this->initializeRolesTitlesCache();
if (!array_key_exists($role, $this->rolesTitlesCache)) {
// this case might happens when the role is not described in
// `getRolesWithHierarchy`
return null;
}
return $this->rolesTitlesCache[$role];
}
/**
* initialize the array for caching role and titles.
*/
private function initializeRolesTitlesCache()
{
// break if already initialized
if (null !== $this->rolesTitlesCache) {
return;
}
foreach ($this->providers as $provider) {
if ($provider instanceof ProvideRoleHierarchyInterface) {
foreach ($provider->getRolesWithHierarchy() as $title => $roles) {
foreach ($roles as $role) {
$this->rolesTitlesCache[$role] = $title;
}
}
} else {
if ($provider->getRoles() !== null) {
$this->rolesTitlesCache = array_merge(
$this->rolesTitlesCache,
array_fill_keys($provider->getRoles(), null)
);
}
}
}
}
}