UserInfoMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\OpenIdClient\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use TMV\OpenIdClient\Client\ClientInterface;
12
use TMV\OpenIdClient\Exception\LogicException;
13
use TMV\OpenIdClient\Exception\RuntimeException;
14
use TMV\OpenIdClient\Service\UserinfoService;
15
use TMV\OpenIdClient\Token\TokenSetInterface;
16
17
class UserInfoMiddleware implements MiddlewareInterface
18
{
19
    public const USERINFO_ATTRIBUTE = self::class;
20
21
    /** @var UserinfoService */
22
    private $userinfoService;
23
24
    /** @var null|ClientInterface */
25
    private $client;
26
27
    public function __construct(
28
        UserinfoService $userinfoService,
29
        ?ClientInterface $client = null
30
    ) {
31
        $this->userinfoService = $userinfoService;
32
        $this->client = $client;
33
    }
34
35
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
36
    {
37
        $tokenSet = $request->getAttribute(TokenSetInterface::class);
38
        $client = $this->client ?: $request->getAttribute(ClientInterface::class);
39
40
        if (! $client instanceof ClientInterface) {
41
            throw new LogicException('No OpenID client provided');
42
        }
43
44
        if (! $tokenSet instanceof TokenSetInterface) {
45
            throw new RuntimeException('Unable to get token response attribute');
46
        }
47
48
        $claims = $this->userinfoService->getUserInfo($client, $tokenSet);
49
50
        return $handler->handle($request->withAttribute(self::USERINFO_ATTRIBUTE, $claims));
51
    }
52
}
53