Skip to content

Commit 0b2d8f0

Browse files
committed
Fix deprecation for TokenInterface::getRoles
1 parent 9fd07c2 commit 0b2d8f0

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

src/UserContext/RoleProvider.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,13 @@ public function updateUserContext(UserContext $context)
5656
return;
5757
}
5858

59-
$roles = array_map(function (Role $role) {
60-
return $role->getRole();
61-
}, $token->getRoles());
59+
if (method_exists($token, 'getRoleNames')) {
60+
$roles = $token->getRoleNames();
61+
} else {
62+
$roles = array_map(function (Role $role) {
63+
return $role->getRole();
64+
}, $token->getRoles());
65+
}
6266

6367
// Order is not important for roles and should not change hash.
6468
sort($roles);

tests/Unit/UserContext/RoleProviderTest.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use PHPUnit\Framework\TestCase;
1818
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
1919
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
20+
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
2021
use Symfony\Component\Security\Core\Role\Role;
2122

2223
class RoleProviderTest extends TestCase
@@ -25,13 +26,18 @@ class RoleProviderTest extends TestCase
2526

2627
public function testProvider()
2728
{
28-
$roles = [new Role('ROLE_USER')];
29-
30-
$token = \Mockery::mock(TokenInterface::class);
29+
if (method_exists(AnonymousToken::class, 'getRoleNames')) {
30+
$token = \Mockery::mock(AnonymousToken::class);
31+
$token->shouldReceive('getRoleNames')->andReturn(['ROLE_USER']);
32+
$token->shouldNotReceive('getRoles');
33+
} else {
34+
$token = \Mockery::mock(TokenInterface::class);
35+
$token->shouldReceive('getRoles')->andReturn([new Role('ROLE_USER')]);
36+
$token->shouldNotReceive('getRoleNames');
37+
}
3138

3239
$securityContext = $this->getTokenStorageMock();
3340
$securityContext->shouldReceive('getToken')->andReturn($token);
34-
$token->shouldReceive('getRoles')->andReturn($roles);
3541

3642
$userContext = new UserContext();
3743
$provider = new RoleProvider($securityContext);

0 commit comments

Comments
 (0)