Passed
Push — master ( 693cc1...43872d )
by Alexander
02:10
created

QueryParameter::withTokenType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Auth\Method;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Yiisoft\Auth\AuthenticationMethodInterface;
10
use Yiisoft\Auth\IdentityInterface;
11
use Yiisoft\Auth\IdentityWithTokenRepositoryInterface;
12
13
use function is_string;
14
15
/**
16
 * QueryParameter supports the authentication based on the access token passed through a query parameter.
17
 */
18
final class QueryParameter implements AuthenticationMethodInterface
19
{
20
    private string $parameterName = 'access-token';
21
    private ?string $tokenType = null;
22
23
    private IdentityWithTokenRepositoryInterface $identityRepository;
24
25 10
    public function __construct(IdentityWithTokenRepositoryInterface $identityRepository)
26
    {
27 10
        $this->identityRepository = $identityRepository;
28 10
    }
29
30 7
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
31
    {
32 7
        $accessToken = $request->getQueryParams()[$this->parameterName] ?? null;
33 7
        if (is_string($accessToken)) {
34 6
            return $this->identityRepository->findIdentityByToken($accessToken, $this->tokenType);
35
        }
36
37 3
        return null;
38
    }
39
40 2
    public function challenge(ResponseInterface $response): ResponseInterface
41
    {
42 2
        return $response;
43
    }
44
45
    /**
46
     * @param string $name The parameter name for passing the access token.
47
     *
48
     * @return $this
49
     *
50
     * @psalm-immutable
51
     */
52 2
    public function withParameterName(string $name): self
53
    {
54 2
        $new = clone $this;
55 2
        $new->parameterName = $name;
56 2
        return $new;
57
    }
58
59
    /**
60
     * @param string|null $type Identity token type
61
     *
62
     * @return $this
63
     *
64
     * @psalm-immutable
65
     */
66 2
    public function withTokenType(?string $type): self
67
    {
68 2
        $new = clone $this;
69 2
        $new->tokenType = $type;
70 2
        return $new;
71
    }
72
}
73