Completed
Pull Request — master (#15)
by
unknown
02:17
created

AddAuthorizationHeader::getOptions()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.5923

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 6
cts 9
cp 0.6667
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 0
crap 4.5923
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 14
    public function __construct(OAuth2Provider $provider, array $config, AccessTokenCacheHandler $cacheHandler)
19
    {
20 14
        $this->provider = $provider;
21 14
        $this->config = $config;
22 14
        $this->cacheHandler = $cacheHandler;
23 14
    }
24
25 10
    public function __invoke(RequestInterface $request): RequestInterface
26
    {
27 10
        $token = $this->cacheHandler->getTokenByProvider($this->provider, $this->config);
28 10
        if (false === $token) {
29 8
            $accessToken = $this->getAccessToken();
30 4
            $token = $accessToken->getToken();
31 4
            $this->cacheHandler->saveTokenByProvider($accessToken, $this->provider, $this->config);
32
        }
33
34 6
        return $request->withHeader('Authorization', 'Bearer ' . $token);
35
    }
36
37 8
    private function getAccessToken(): AccessToken
38
    {
39 8
        $options = $this->getOptions();
40 8
        $grantType = $this->getGrantType();
41 6
        return $this->provider->getAccessToken($grantType, $options);
42
    }
43
44 8
    private function getGrantType(): string
45
    {
46 8
        if (empty($this->config['grant_type'])) {
47 2
            throw new InvalidArgumentException('Config value `grant_type` needs to be specified.');
48
        }
49 6
        return $this->config['grant_type'];
50
    }
51
52 8
    private function getOptions(): array
53
    {
54 8
        $options = [];
55 8
        if (!empty($this->config['scope'])) {
56 4
            $options['scope'] = $this->config['scope'];
57
        }
58
      
59 8
        if (!empty($this->config['token_options'])) {
60
            $token_options = $this->config['token_options'];
61
            foreach ($token_options as $key => $value) {
62
                $options[$key] = $value;
63
            }
64
        }
65
66 8
        return $options;
67
    }
68
}
69