Passed
Push — 0.x ( 689b78...ec4bb9 )
by Pavel
02:17
created

HttpDiscoverer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 16
c 1
b 0
f 0
dl 0
loc 40
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A discover() 0 6 1
A sendRequest() 0 20 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DigitalCz\OpenIDConnect\Discovery;
6
7
use DigitalCz\OpenIDConnect\Discovery\Exception\DiscoveryException;
8
use JsonException;
9
use Psr\Http\Client\ClientExceptionInterface;
10
use Psr\Http\Client\ClientInterface;
11
use Psr\Http\Message\RequestFactoryInterface;
12
13
final class HttpDiscoverer implements Discoverer
14
{
15
    public function __construct(private ClientInterface $client, private RequestFactoryInterface $requestFactory)
16
    {
17
    }
18
19
    /**
20
     * @throws DiscoveryException
21
     */
22
    public function discover(string $uri): ProviderMetadata
23
    {
24
        $configuration = $this->sendRequest($uri);
25
        $jwks = $this->sendRequest($configuration['jwks_uri']);
26
27
        return new ProviderMetadata($configuration, JWKs::fromArray($jwks));
28
    }
29
30
    /**
31
     * @return array<string, mixed>
32
     */
33
    private function sendRequest(string $uri): array
34
    {
35
        $request = $this->requestFactory->createRequest('GET', $uri);
36
37
        try {
38
            $response = $this->client->sendRequest($request);
39
        } catch (ClientExceptionInterface $e) {
40
            throw new DiscoveryException($e->getMessage(), $e->getCode(), $e);
41
        }
42
43
        $statusCode = $response->getStatusCode();
44
45
        if ($statusCode !== 200) {
46
            throw new DiscoveryException('Bad response status code ' . $response->getStatusCode() . ' on ' . $uri);
47
        }
48
49
        try {
50
            return json_decode((string)$response->getBody(), true, 512, JSON_THROW_ON_ERROR);
51
        } catch (JsonException $e) {
52
            throw new DiscoveryException('Unable to parse response from ' . $uri, $e->getCode(), $e);
53
        }
54
    }
55
}
56