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

JwtEventSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
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
        $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