Passed
Push — develop ( 9096ce...05150f )
by Daniel
05:42
created

JwtEventSubscriber::updateTokenRoles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Silverback\ApiComponentBundle\EventSubscriber;
4
5
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
6
use Lexik\Bundle\JWTAuthenticationBundle\Events;
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
use Symfony\Component\Security\Core\Role\Role;
9
use Symfony\Component\Security\Core\Role\RoleHierarchy;
10
11
class JwtEventSubscriber implements EventSubscriberInterface
12
{
13
    private $roleHierarchy;
14
15
    public function __construct(RoleHierarchy $roleHierarchy)
16
    {
17
        $this->roleHierarchy = $roleHierarchy;
18
    }
19
20
    public static function getSubscribedEvents(): array
21
    {
22
        return [ Events::JWT_CREATED => 'updateTokenRoles' ];
23
    }
24
25
    public function updateTokenRoles(JWTCreatedEvent $event): void
26
    {
27
        $user = $event->getUser();
28
        $data = $event->getData();
29
        $reachableRoles = $this->roleHierarchy->getReachableRoles($user->getRoles());
30
        $data['roles'] = array_map(function(Role $role) { return (string) $role->getRole(); }, $reachableRoles);
31
        $event->setData($data);
32
    }
33
}
34