Completed
Push — master ( 0be8e1...585ca2 )
by Daniel
59:26 queued 46:02
created

JwtEventSubscriber   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 14
dl 0
loc 26
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 3 1
A __construct() 0 3 1
A updateTokenRoles() 0 12 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
        $rolesAsEntities = array_map(function ($role) {
30
            return new Role($role);
31
        }, $user->getRoles());
32
        $reachableRoles = $this->roleHierarchy->getReachableRoles($rolesAsEntities);
33
        $data['roles'] = array_map(function (Role $role) {
34
            return (string) $role->getRole();
35
        }, $reachableRoles);
36
        $event->setData($data);
37
    }
38
}
39