Completed
Pull Request — develop (#726)
by Alejandro
05:51
created

MercureInfoAction::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 20
rs 9.8333
c 0
b 0
f 0
ccs 13
cts 13
cp 1
cc 3
nc 3
nop 1
crap 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 Psr\Log\LoggerInterface;
12
use Shlinkio\Shlink\Common\Mercure\JwtProviderInterface;
13
use Shlinkio\Shlink\Rest\Exception\MercureException;
14
use Throwable;
15
16
use function sprintf;
17
18
class MercureInfoAction extends AbstractRestAction
19
{
20
    protected const ROUTE_PATH = '/mercure-info';
21
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
22
23
    private JwtProviderInterface $jwtProvider;
24
    private array $mercureConfig;
25
26 6
    public function __construct(
27
        JwtProviderInterface $jwtProvider,
28
        array $mercureConfig,
29
        ?LoggerInterface $logger = null
30
    ) {
31 6
        parent::__construct($logger);
32 6
        $this->jwtProvider = $jwtProvider;
33 6
        $this->mercureConfig = $mercureConfig;
34
    }
35
36 6
    public function handle(ServerRequestInterface $request): ResponseInterface
37
    {
38 6
        $hubUrl = $this->mercureConfig['public_hub_url'] ?? null;
39 6
        if ($hubUrl === null) {
40 2
            throw MercureException::mercureNotConfigured();
41
        }
42
43 4
        $days = $this->mercureConfig['jwt_days_duration'] ?? 3;
44 4
        $expiresAt = Chronos::now()->addDays($days);
45
46
        try {
47 4
            $jwt = $this->jwtProvider->buildSubscriptionToken($expiresAt);
48 2
        } catch (Throwable $e) {
49 2
            throw MercureException::mercureNotConfigured($e);
50
        }
51
52 2
        return new JsonResponse([
53 2
            'mercureHubUrl' => sprintf('%s/.well-known/mercure', $hubUrl),
54 2
            'token' => $jwt,
55 2
            'jwtExpiration' => $expiresAt->toAtomString(),
56
        ]);
57
    }
58
}
59