Passed
Push — master ( ae7595...89e794 )
by Alejandro
02:26
created

LcobucciJwtProvider   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 28
ccs 14
cts 14
cp 1
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __invoke() 0 11 2
A roundDateToCurrentSecond() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Common\Mercure;
6
7
use Cake\Chronos\Chronos;
8
use DateTimeImmutable;
9
use Lcobucci\JWT\Configuration;
10
11
class LcobucciJwtProvider
12
{
13
    private Configuration $jwtConfig;
14
    private array $mercureConfig;
15
16 2
    public function __construct(Configuration $jwtConfig, array $mercureConfig)
17
    {
18 2
        $this->jwtConfig = $jwtConfig;
19 2
        $this->mercureConfig = $mercureConfig;
20
    }
21
22 2
    public function __invoke(?DateTimeImmutable $expiresAt = null): string
23
    {
24 2
        $now = $this->roundDateToCurrentSecond(Chronos::now());
25 2
        $expiresAt = $expiresAt === null ? $now->addMinutes(10) : $this->roundDateToCurrentSecond($expiresAt);
26
27 2
        return (string) $this->jwtConfig
28 2
            ->createBuilder()
29 2
            ->issuedBy($this->mercureConfig['jwt_issuer'] ?? 'Shlink')
30 2
            ->issuedAt($now)
31 2
            ->expiresAt($expiresAt)
32 2
            ->getToken($this->jwtConfig->getSigner(), $this->jwtConfig->getSigningKey());
33
    }
34
35 2
    public function roundDateToCurrentSecond(DateTimeImmutable $date): Chronos
36
    {
37
        // This removes the microseconds, rounding down to the second, and working around how Lcobucci\JWT parses dates
38 2
        return Chronos::parse($date->format('Y-m-d h:i:s'));
39
    }
40
}
41