AddAuthorizationHeader   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __invoke() 0 15 3
A getAccessToken() 0 6 1
A getGrantType() 0 7 2
A getOptions() 0 16 4
1
<?php
2
3
namespace Softonic\OAuth2\Guzzle\Middleware;
4
5
use InvalidArgumentException;
6
use League\OAuth2\Client\Provider\AbstractProvider as OAuth2Provider;
7
use League\OAuth2\Client\Token\AccessToken;
8
use Psr\Http\Message\RequestInterface;
9
10
class AddAuthorizationHeader
11
{
12
    const CACHE_KEY_PREFIX = 'oauth2-token-';
13
14
    private $provider;
15
    private $cacheHandler;
16
    private $config;
17
18 18
    public function __construct(OAuth2Provider $provider, array $config, AccessTokenCacheHandler $cacheHandler)
19
    {
20 18
        $this->provider = $provider;
21 18
        $this->config = $config;
22 18
        $this->cacheHandler = $cacheHandler;
23 18
    }
24
25 14
    public function __invoke(RequestInterface $request): RequestInterface
26
    {
27 14
        $token = $this->cacheHandler->getTokenByProvider($this->provider, $this->config);
28 14
        if (false === $token) {
29 12
            $accessToken = $this->getAccessToken();
30 8
            $token = $accessToken->getToken();
31 8
            $this->cacheHandler->saveTokenByProvider($accessToken, $this->provider, $this->config);
32
        }
33
34 10
        foreach ($this->provider->getHeaders($token) as $name => $value) {
35 10
            $request = $request->withHeader($name, $value);
36
        }
37
38 10
        return $request;
39
    }
40
41 12
    private function getAccessToken(): AccessToken
42
    {
43 12
        $options = $this->getOptions();
44 12
        $grantType = $this->getGrantType();
45 10
        return $this->provider->getAccessToken($grantType, $options);
46
    }
47
48 12
    private function getGrantType(): string
49
    {
50 12
        if (empty($this->config['grant_type'])) {
51 2
            throw new InvalidArgumentException('Config value `grant_type` needs to be specified.');
52
        }
53 10
        return $this->config['grant_type'];
54
    }
55
56 12
    private function getOptions(): array
57
    {
58 12
        $options = [];
59 12
        if (!empty($this->config['scope'])) {
60 8
            $options['scope'] = $this->config['scope'];
61
        }
62
      
63 12
        if (!empty($this->config['token_options'])) {
64 4
            $tokenOptions = $this->config['token_options'];
65 4
            foreach ($tokenOptions as $key => $value) {
66 4
                $options[$key] = $value;
67
            }
68
        }
69
70 12
        return $options;
71
    }
72
}
73