Skip to content

Fix deprecation for TokenInterface::getRoles #526

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/UserContext/RoleProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@ public function updateUserContext(UserContext $context)
return;
}

$roles = array_map(function (Role $role) {
return $role->getRole();
}, $token->getRoles());
if (method_exists($token, 'getRoleNames')) {
$roles = $token->getRoleNames();
} else {
$roles = array_map(function (Role $role) {
return $role->getRole();
}, $token->getRoles());
}

// Order is not important for roles and should not change hash.
sort($roles);
Expand Down
14 changes: 10 additions & 4 deletions tests/Unit/UserContext/RoleProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use FOS\HttpCacheBundle\UserContext\RoleProvider;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\Role;
Expand All @@ -25,13 +26,18 @@ class RoleProviderTest extends TestCase

public function testProvider()
{
$roles = [new Role('ROLE_USER')];

$token = \Mockery::mock(TokenInterface::class);
if (method_exists(AnonymousToken::class, 'getRoleNames')) {
$token = \Mockery::mock(AnonymousToken::class);
$token->shouldReceive('getRoleNames')->andReturn(['ROLE_USER']);
$token->shouldNotReceive('getRoles');
} else {
$token = \Mockery::mock(TokenInterface::class);
$token->shouldReceive('getRoles')->andReturn([new Role('ROLE_USER')]);
$token->shouldNotReceive('getRoleNames');
}

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

$userContext = new UserContext();
$provider = new RoleProvider($securityContext);
Expand Down