Completed
Pull Request — master (#8)
by
unknown
04:47
created

AddAuthorizationHeader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
namespace Softonic\OAuth2\Guzzle\Middleware;
4
5
use League\OAuth2\Client\Provider\AbstractProvider as OAuth2Provider;
6
use League\OAuth2\Client\Token\AccessToken;
7
use Psr\Http\Message\RequestInterface;
8
9
class AddAuthorizationHeader
10
{
11
    const CACHE_KEY_PREFIX = 'oauth2-token-';
12
13
    private $provider;
14
    private $cacheHandler;
15
    private $config;
16
17 8
    public function __construct(OAuth2Provider $provider, array $config, AccessTokenCacheHandler $cacheHandler)
18
    {
19 8
        $this->provider = $provider;
20 8
        $this->config = $config;
21 8
        $this->cacheHandler = $cacheHandler;
22 8
    }
23
24 4
    public function __invoke(RequestInterface $request): RequestInterface
25
    {
26 4
        $token = $this->cacheHandler->getTokenByProvider($this->provider, $this->config);
27 4
        if (false === $token) {
28 2
            $accessToken = $this->getAccessToken();
29
            $token = $accessToken->getToken();
30
            $this->cacheHandler->saveTokenByProvider($accessToken, $this->provider, $this->config);
31
        }
32
33 2
        return $request->withHeader('Authorization', 'Bearer ' . $token);
34
    }
35
36 2
    private function getAccessToken(): AccessToken
37
    {
38 2
        $grantType = $this->getGrantType();
39
        return $this->provider->getAccessToken($grantType, $this->config);
40
    }
41
42 2
    private function getGrantType(): string
43
    {
44 2
        if (empty($this->config['grant_type'])) {
45 2
            throw new \InvalidArgumentException('Config value `grant_type` needs to be specified.');
46
        }
47
        return $this->config['grant_type'];
48
    }
49
}
50