Skip to content

Instantly share code, notes, and snippets.

@tasiot
Created April 25, 2023 15:46
Show Gist options
  • Save tasiot/90da1369d73b7f176d754ac796b88d47 to your computer and use it in GitHub Desktop.
Save tasiot/90da1369d73b7f176d754ac796b88d47 to your computer and use it in GitHub Desktop.
Symfony user roles
<?php
declare(strict_types=1);
namespace App\Service;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityHelper
{
public function __construct(
private readonly RoleHierarchyInterface $roleHierarchy
) {
}
/** @return string[] */
public function getRoles(UserInterface $user): array
{
$userRoles = $user->getRoles();
return $this->roleHierarchy->getReachableRoleNames($userRoles);
}
public function hasRole(UserInterface $user, string $role): bool
{
$allRoles = $this->getRoles($user);
return in_array($role, $allRoles, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment