Completed
Pull Request — master (#763)
by Alejandro
13:02 queued 07:46
created

MercureInfoAction::__construct()   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
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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