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

LcobucciJwtProvider::roundDateToCurrentSecond()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
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