Builder   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 36
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromUser() 0 15 3
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Bundle\ApiAuthBundle\Jwt\Lcobucci;
6
7
use Damax\Bundle\ApiAuthBundle\Jwt\Claims;
8
use Damax\Bundle\ApiAuthBundle\Jwt\TokenBuilder;
9
use Lcobucci\JWT\Configuration as JwtConfiguration;
10
use Symfony\Component\Security\Core\User\UserInterface;
11
12
final class Builder implements TokenBuilder
13
{
14
    private const CLAIM_TO_METHOD = [
15
        Claims::SUBJECT => 'relatedTo',
16
        Claims::ISSUER => 'issuedBy',
17
        Claims::AUDIENCE => 'permittedFor',
18
        Claims::ISSUED_AT => 'issuedAt',
19
        Claims::NOT_BEFORE => 'canOnlyBeUsedAfter',
20
        Claims::EXPIRATION_TIME => 'expiresAt',
21
        Claims::ID => 'identifiedBy',
22
    ];
23
24
    private $config;
25
    private $claims;
26
27
    public function __construct(JwtConfiguration $config, Claims $claims)
28
    {
29
        $this->config = $config;
30
        $this->claims = $claims;
31
    }
32
33
    public function fromUser(UserInterface $user): string
34
    {
35
        $builder = $this->config->createBuilder();
36
37
        foreach ($this->claims->resolve($user) as $name => $value) {
38
            $method = self::CLAIM_TO_METHOD[$name] ?? null;
39
40
            if ($method) {
41
                $builder->{$method}($value);
42
            } else {
43
                $builder->withClaim($name, $value);
44
            }
45
        }
46
47
        return (string) $builder->getToken($this->config->getSigner(), $this->config->getSigningKey());
48
    }
49
}
50