Completed
Push — master ( 89e794...3178fd )
by Alejandro
02:10
created

LcobucciJwtProvider::buildPublishToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 implements JwtProviderInterface
12
{
13
    private Configuration $jwtConfig;
14
    private array $mercureConfig;
15
16 4
    public function __construct(Configuration $jwtConfig, array $mercureConfig)
17
    {
18 4
        $this->jwtConfig = $jwtConfig;
19 4
        $this->mercureConfig = $mercureConfig;
20
    }
21
22 2
    public function __invoke(): string
23
    {
24 2
        return $this->buildPublishToken();
25
    }
26
27 2
    public function buildPublishToken(): string
28
    {
29 2
        $expiresAt = $this->roundDateToTheSecond(Chronos::now()->addMinutes(10));
30 2
        return $this->buildToken(['publish' => []], $expiresAt);
31
    }
32
33 2
    public function buildSubscriptionToken(?DateTimeImmutable $expiresAt = null): string
34
    {
35 2
        $expiresAt = $this->roundDateToTheSecond($expiresAt ?? Chronos::now()->addDays(3));
36 2
        return $this->buildToken(['subscribe' => []], $expiresAt);
37
    }
38
39 4
    private function buildToken(array $mercureClaim, DateTimeImmutable $expiresAt): string
40
    {
41 4
        $now = $this->roundDateToTheSecond(Chronos::now());
42
43 4
        return (string) $this->jwtConfig
44 4
            ->createBuilder()
45 4
            ->issuedBy($this->mercureConfig['jwt_issuer'] ?? 'Shlink')
46 4
            ->issuedAt($now)
47 4
            ->expiresAt($expiresAt)
48 4
            ->withClaim('mercure', $mercureClaim)
49 4
            ->getToken($this->jwtConfig->getSigner(), $this->jwtConfig->getSigningKey());
50
    }
51
52 4
    public function roundDateToTheSecond(DateTimeImmutable $date): Chronos
53
    {
54
        // This removes the microseconds, rounding down to the second, and working around how Lcobucci\JWT parses dates
55 4
        return Chronos::parse($date->format('Y-m-d h:i:s'));
56
    }
57
}
58