Passed
Push — master ( 70a6cc...47c822 )
by Thomas Mauro
03:20
created

JWKSetHandler::handle()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 22
ccs 0
cts 12
cp 0
rs 9.8666
cc 3
nc 4
nop 1
crap 12
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
    public function __construct(
31
        ResponseFactoryInterface $responseFactory,
32
        StreamFactoryInterface $streamFactory,
33
        JWKSet $jwkset,
34
        int $maxAge = 0
35
    ) {
36
        $this->responseFactory = $responseFactory;
37
        $this->streamFactory = $streamFactory;
38
        $this->jwkset = $jwkset;
39
        $this->maxAge = $maxAge;
40
    }
41
42
    public function handle(ServerRequestInterface $request): ResponseInterface
43
    {
44
        $response = $this->responseFactory->createResponse();
45
46
        if ($this->maxAge > 0) {
47
            $response = $response->withHeader('Cache-Control', 'max-age=' . $this->maxAge);
48
        }
49
50
        $keys = \array_map(static function (JWK $jwk) {
51
            return $jwk->toPublic();
52
        }, $this->jwkset->all());
53
54
        $jwks = new JWKSet($keys);
55
56
        $jwks = \json_encode($jwks->jsonSerialize());
57
58
        if (false === $jwks) {
59
            throw new RuntimeException('Unable to create jwk set json content');
60
        }
61
62
        return $response->withHeader('Content-Type', 'application/jwk-set+json; charset=UTF-8')
63
            ->withBody($this->streamFactory->createStream($jwks));
64
    }
65
}
66