Passed
Push — master ( 106006...c1ddb5 )
by Thomas Mauro
06:38 queued 11s
created

IntrospectionService::introspect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 13
nc 2
nop 3
dl 0
loc 22
ccs 0
cts 17
cp 0
crap 6
rs 9.8333
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\OpenIdClient\Service;
6
7
use Http\Discovery\Psr17FactoryDiscovery;
8
use Http\Discovery\Psr18ClientDiscovery;
9
use Psr\Http\Client\ClientExceptionInterface;
10
use Psr\Http\Client\ClientInterface;
11
use Psr\Http\Message\RequestFactoryInterface;
12
use TMV\OpenIdClient\Client\ClientInterface as OpenIDClient;
13
use TMV\OpenIdClient\Exception\RuntimeException;
14
use function TMV\OpenIdClient\get_endpoint_uri;
15
use function TMV\OpenIdClient\parse_metadata_response;
16
17
/**
18
 * RFC 7662 Token Introspection
19
 *
20
 * @link https://tools.ietf.org/html/rfc7662 RFC 7662
21
 */
22
class IntrospectionService
23
{
24
    /** @var ClientInterface */
25
    private $client;
26
27
    /** @var RequestFactoryInterface */
28
    private $requestFactory;
29
30
    public function __construct(
31
        ?ClientInterface $client = null,
32
        ?RequestFactoryInterface $requestFactory = null
33
    ) {
34
        $this->client = $client ?: Psr18ClientDiscovery::find();
35
        $this->requestFactory = $requestFactory ?: Psr17FactoryDiscovery::findRequestFactory();
36
    }
37
38
    public function introspect(OpenIDClient $client, string $token, array $params = []): array
39
    {
40
        $endpointUri = get_endpoint_uri($client, 'introspection_endpoint');
41
42
        $authMethod = $client->getAuthMethodFactory()
43
            ->create($client->getMetadata()->getRevocationEndpointAuthMethod());
44
45
        $tokenRequest = $this->requestFactory->createRequest('POST', $endpointUri)
46
            ->withHeader('content-type', 'application/x-www-form-urlencoded');
47
48
        $tokenRequest = $authMethod->createRequest($tokenRequest, $client, $params);
49
        $tokenRequest->getBody()->write(http_build_query(array_merge($params, [
50
            'token' => $token,
51
        ])));
52
53
        try {
54
            $response = $this->client->sendRequest($tokenRequest);
55
        } catch (ClientExceptionInterface $e) {
56
            throw new RuntimeException('Unable to get revocation response', 0, $e);
57
        }
58
59
        return parse_metadata_response($response, 200);
60
    }
61
}
62