Passed
Push — master ( 78880b...ac7e2f )
by Jens
20:00 queued 13s
created

OAuth2Handler::cache()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 8
ccs 4
cts 7
cp 0.5714
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3.7085
1
<?php
2
3
namespace Commercetools\Core\Client\OAuth;
4
5
use Commercetools\Core\Cache\CacheAdapterFactory;
6
use Commercetools\Core\Error\InvalidArgumentException;
7
use Psr\Cache\CacheItemPoolInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\SimpleCache\CacheInterface;
10
11
class OAuth2Handler
12
{
13
    /**
14
     * @var TokenProvider
15
     */
16
    private $provider;
17
18
    /**
19
     * OAuth2Handler constructor.
20
     * @param TokenProvider $provider
21
     * @param CacheItemPoolInterface|CacheInterface $cache
22
     * @param CacheAdapterFactory|null $factory
23
     * @param string $cacheKey
24
     */
25 19
    public function __construct(
26
        TokenProvider $provider
27
    ) {
28 19
        $this->provider = $provider;
29 19
    }
30
31
    /**
32
     * @param RequestInterface $request
33
     * @param array $options
34
     * @return RequestInterface
35
     */
36 17
    public function __invoke(RequestInterface $request, array $options = [])
37
    {
38 17
        if ($request->hasHeader('Authorization')) {
39
            return $request;
40
        }
41 17
        return $request->withHeader('Authorization', $this->getAuthorizationHeader());
42
    }
43
44
    /**
45
     * @return string
46
     */
47 17
    public function getAuthorizationHeader()
48
    {
49 17
        return 'Bearer ' . $this->getBearerToken()->getToken();
50
    }
51
52 1
    public function refreshToken()
53
    {
54 1
        if ($this->provider instanceof RefreshTokenProvider) {
55 1
            return $this->provider->refreshToken();
56
        }
57
        throw new InvalidArgumentException();
58
    }
59
60
    /**
61
     * @return Token
62
     */
63 17
    private function getBearerToken()
64
    {
65 17
        return $this->provider->getToken();
66
    }
67
68
    /**
69
     * @return bool
70
     */
71 19
    public function refreshable()
72
    {
73 19
        return ($this->provider instanceof RefreshTokenProvider);
74
    }
75
}
76