JWKSetHandler   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 81.82%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
eloc 26
c 2
b 0
f 0
dl 0
loc 59
ccs 18
cts 22
cp 0.8182
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 2
A handle() 0 26 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\JWTModule\Middleware;
6
7
use Jose\Component\Core\JWK;
8
use Jose\Component\Core\JWKSet;
9
use Psr\Http\Message\ResponseFactoryInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Message\StreamFactoryInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use TMV\JWTModule\Exception\RuntimeException;
15
16
class JWKSetHandler implements RequestHandlerInterface
17
{
18
    /** @var ResponseFactoryInterface */
19
    private $responseFactory;
20
21
    /** @var StreamFactoryInterface */
22
    private $streamFactory;
23
24
    /** @var JWKSet */
25
    private $jwkset;
26
27
    /** @var int */
28
    private $maxAge;
29
30
    /** @var callable */
31
    private $jwkSetFactory;
32
33 2
    public function __construct(
34
        ResponseFactoryInterface $responseFactory,
35
        StreamFactoryInterface $streamFactory,
36
        JWKSet $jwkset,
37
        int $maxAge = 0,
38
        callable $jwkSetFactory = null
39
    ) {
40 2
        $this->responseFactory = $responseFactory;
41 2
        $this->streamFactory = $streamFactory;
42 2
        $this->jwkset = $jwkset;
43 2
        $this->maxAge = $maxAge;
44
        $this->jwkSetFactory = $jwkSetFactory ?: static function (array $keys) {
45
            return new JWKSet($keys);
46
        };
47 2
    }
48
49 2
    public function handle(ServerRequestInterface $request): ResponseInterface
50
    {
51 2
        $response = $this->responseFactory->createResponse();
52
53 2
        if ($this->maxAge > 0) {
54 1
            $response = $response->withHeader('Cache-Control', 'max-age=' . $this->maxAge);
55
        }
56
57
        $keys = \array_map(static function (JWK $jwk) {
58 2
            return $jwk->toPublic();
59 2
        }, $this->jwkset->all());
60
61 2
        $jwks = ($this->jwkSetFactory)($keys);
62
63 2
        if (! $jwks instanceof JWKSet) {
64
            throw new RuntimeException('Invalid JWKSet created');
65
        }
66
67 2
        $jwks = \json_encode($jwks->jsonSerialize());
68
69 2
        if (false === $jwks) {
70
            throw new RuntimeException('Unable to create jwk set json content');
71
        }
72
73 2
        return $response->withHeader('Content-Type', 'application/jwk-set+json; charset=UTF-8')
74 2
            ->withBody($this->streamFactory->createStream($jwks));
75
    }
76
}
77