Created
April 25, 2023 15:46
-
-
Save tasiot/90da1369d73b7f176d754ac796b88d47 to your computer and use it in GitHub Desktop.
Symfony user roles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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