Completed
Push — master ( a30f79...cb6756 )
by Alejandro
27s queued 13s
created

MercureInfoAction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 19
dl 0
loc 34
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A handle() 0 20 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Rest\Action;
6
7
use Cake\Chronos\Chronos;
8
use Laminas\Diactoros\Response\JsonResponse;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Shlinkio\Shlink\Common\Mercure\JwtProviderInterface;
12
use Shlinkio\Shlink\Rest\Exception\MercureException;
13
use Throwable;
14
15
use function sprintf;
16
17
class MercureInfoAction extends AbstractRestAction
18
{
19
    protected const ROUTE_PATH = '/mercure-info';
20
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
21
22
    private JwtProviderInterface $jwtProvider;
23
    private array $mercureConfig;
24
25 6
    public function __construct(JwtProviderInterface $jwtProvider, array $mercureConfig)
26
    {
27 6
        $this->jwtProvider = $jwtProvider;
28 6
        $this->mercureConfig = $mercureConfig;
29
    }
30
31 6
    public function handle(ServerRequestInterface $request): ResponseInterface
32
    {
33 6
        $hubUrl = $this->mercureConfig['public_hub_url'] ?? null;
34 6
        if ($hubUrl === null) {
35 2
            throw MercureException::mercureNotConfigured();
36
        }
37
38 4
        $days = $this->mercureConfig['jwt_days_duration'] ?? 1;
39 4
        $expiresAt = Chronos::now()->addDays($days);
40
41
        try {
42 4
            $jwt = $this->jwtProvider->buildSubscriptionToken($expiresAt);
43 2
        } catch (Throwable $e) {
44 2
            throw MercureException::mercureNotConfigured($e);
45
        }
46
47 2
        return new JsonResponse([
48 2
            'mercureHubUrl' => sprintf('%s/.well-known/mercure', $hubUrl),
49 2
            'token' => $jwt,
50 2
            'jwtExpiration' => $expiresAt->toAtomString(),
51
        ]);
52
    }
53
}
54