Completed
Push — master ( f5d9cb...35a455 )
by Gabriel
02:54
created

Bearer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 4
dl 0
loc 51
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isAuthorized() 0 4 1
A requestAccessToken() 0 4 1
A getAuthorizedRequest() 0 10 1
A getAuthorizationString() 0 4 1
1
<?php
2
3
namespace Somoza\OAuth2Middleware\TokenService;
4
5
use League\OAuth2\Client\Token\AccessToken;
6
use Psr\Http\Message\RequestInterface;
7
8
/**
9
 * Bearer PSR7 Middleware
10
 *
11
 * @author Gabriel Somoza <[email protected]>
12
 *
13
 * @see https://tools.ietf.org/html/rfc6750
14
 */
15
final class Bearer extends AbstractTokenService
16
{
17
    /** @string Name of the authorization header injected into the request */
18
    const HEADER_AUTHORIZATION = 'Authorization';
19
20
    /** @string Access Token type */
21
    const TOKEN_TYPE = 'Bearer';
22
23
    /**
24
     * @inheritdoc
25
     */
26 6
    public function isAuthorized(RequestInterface $request): bool
27
    {
28 6
        return $request->hasHeader(self::HEADER_AUTHORIZATION);
29
    }
30
31
    /**
32
     * @inheritdoc
33
     */
34 2
    protected function requestAccessToken(): AccessToken
35
    {
36 2
        return $this->getProvider()->getAccessToken(self::GRANT_CLIENT_CREDENTIALS);
37
    }
38
39
    /**
40
     * Returns an authorized copy of the request. Only gets called when necessary (i.e. not if the request is already
41
     * authorized), and always with a valid (fresh) Access Token. However, it SHOULD be idempotent.
42
     *
43
     * @param RequestInterface $request An unauthorized request
44
     *
45
     * @return RequestInterface An authorized copy of the request
46
     */
47 5
    protected function getAuthorizedRequest(RequestInterface $request): RequestInterface
48
    {
49
        /** @var RequestInterface $request */
50 5
        $request = $request->withHeader(
51 5
            self::HEADER_AUTHORIZATION,
52 5
            $this->getAuthorizationString()
53
        );
54
55 5
        return $request;
56
    }
57
58
    /**
59
     * @return string
60
     */
61 5
    private function getAuthorizationString(): string
62
    {
63 5
        return self::TOKEN_TYPE . ' ' . $this->getAccessToken()->getToken();
64
    }
65
}
66