Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
OidcDiscoveryService
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
2 / 2
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 discover
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2
3/**
4 * OIDC discovery document loader.
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public License,
7 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
8 * obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * @package   phpMyFAQ
11 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
12 * @copyright 2026 phpMyFAQ Team
13 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
14 * @link      https://www.phpmyfaq.de
15 * @since     2026-04-18
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Auth\Oidc;
21
22use JsonException;
23use RuntimeException;
24use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
25use Symfony\Contracts\HttpClient\HttpClientInterface;
26
27final readonly class OidcDiscoveryService
28{
29    public function __construct(
30        private HttpClientInterface $httpClient,
31    ) {
32    }
33
34    /**
35     * @throws ExceptionInterface
36     */
37    public function discover(OidcProviderConfig $config): OidcDiscoveryDocument
38    {
39        $response = $this->httpClient->request('GET', $config->discoveryUrl);
40        $content = $response->getContent(false);
41
42        if ($response->getStatusCode() >= 400) {
43            throw new RuntimeException(sprintf(
44                'OIDC discovery request failed for %s with status %d',
45                $config->provider,
46                $response->getStatusCode(),
47            ));
48        }
49
50        try {
51            $payload = json_decode($content, associative: true, depth: 512, flags: JSON_THROW_ON_ERROR);
52        } catch (JsonException $exception) {
53            throw new RuntimeException('OIDC discovery response is not valid JSON', previous: $exception);
54        }
55
56        if (!is_array($payload)) {
57            throw new RuntimeException(sprintf(
58                'OIDC discovery response is not a JSON object/array, got %s',
59                gettype($payload),
60            ));
61        }
62
63        $normalizedPayload = [];
64        foreach ($payload as $payloadKey => $payloadValue) {
65            $normalizedPayload[(string) $payloadKey] = $payloadValue;
66        }
67
68        return OidcDiscoveryDocument::fromArray($normalizedPayload);
69    }
70}