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

HttpDiscoverer::sendRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 20
rs 9.8666
cc 4
nc 4
nop 1
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