Passed
Push — master ( da0795...78880b )
by Jens
14:45 queued 18s
created

OAuth2Handler::getCacheToken()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 14
ccs 5
cts 10
cp 0.5
rs 9.9666
c 0
b 0
f 0
cc 4
nc 4
nop 0
crap 6
1
<?php
2
3
namespace Commercetools\Core\Client\OAuth;
4
5
use Cache\Adapter\Filesystem\FilesystemCachePool;
6
use Commercetools\Core\Cache\CacheAdapterFactory;
7
use Commercetools\Core\Error\InvalidArgumentException;
8
use Commercetools\Core\Error\Message;
9
use League\Flysystem\Adapter\Local;
10
use League\Flysystem\Filesystem;
11
use Psr\Cache\CacheItemInterface;
12
use Psr\Cache\CacheItemPoolInterface;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\SimpleCache\CacheInterface;
15
16
class OAuth2Handler
17
{
18
    const TOKEN_CACHE_KEY = 'commercetools_io_access_token';
19
20
    /**
21
     * @var TokenProvider
22
     */
23
    private $provider;
24
    /**
25
     * @var CacheItemPoolInterface|CacheInterface
26
     */
27
    private $cache;
28
29
    private $cacheKey;
30
31
    /**
32
     * OAuth2Handler constructor.
33
     * @param TokenProvider $provider
34
     * @param CacheItemPoolInterface|CacheInterface $cache
35
     * @param CacheAdapterFactory|null $factory
36
     * @param string $cacheKey
37
     */
38 5
    public function __construct(
39
        TokenProvider $provider,
40
        $cache = null,
41
        CacheAdapterFactory $factory = null,
42
        $cacheKey = null
43
    ) {
44 5
        $this->provider = $provider;
45
46 5
        if (is_null($factory)) {
47
            $factory = new CacheAdapterFactory(__DIR__ . '/../../../..');
48
        }
49 5
        $cache = $factory->get($cache);
50
51 5
        if (is_null($cache)) {
52
            throw new InvalidArgumentException(Message::INVALID_CACHE_ADAPTER);
53
        }
54
55 5
        $this->cacheKey = self::TOKEN_CACHE_KEY . "_" . (!is_null($cacheKey) ? $cacheKey : sha1('access_token'));
56 5
        $this->cache = $cache;
57 5
    }
58
59
    /**
60
     * @param RequestInterface $request
61
     * @param array $options
62
     * @return RequestInterface
63
     */
64 5
    public function __invoke(RequestInterface $request, array $options = [])
65
    {
66 5
        return $request->withHeader('Authorization', $this->getAuthorizationHeader());
67
    }
68
69
    /**
70
     * @return string
71
     */
72 5
    public function getAuthorizationHeader()
73
    {
74 5
        return 'Bearer ' . $this->getBearerToken();
75
    }
76
77 2
    public function refreshToken()
78
    {
79 2
        $token = $this->provider->getToken();
80
        // ensure token to be invalidated in cache before TTL
81 2
        $ttl = max(1, floor($token->getTtl()/2));
82
83 2
        $this->cache($token, $ttl);
84
85 2
        return $token;
86
    }
87
88
    /**
89
     * @return string
90
     */
91 5
    private function getBearerToken()
92
    {
93 5
        $item = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $item is dead and can be removed.
Loading history...
94
95 5
        $token = $this->getCacheToken();
96 5
        if (!is_null($token)) {
97 4
            return $token;
98
        }
99
100 1
        return $this->refreshToken()->getToken();
101
    }
102
103 5
    private function getCacheToken()
104
    {
105 5
        $cache = $this->cache;
106 5
        if ($cache instanceof CacheInterface) {
107 5
            $var = $cache->get($this->cacheKey, null);
108 5
            return $var;
109
        } elseif ($cache instanceof CacheItemPoolInterface) {
0 ignored issues
show
introduced by
$cache is always a sub-type of Psr\Cache\CacheItemPoolInterface.
Loading history...
110
            $item = $cache->getItem($this->cacheKey);
111
            if ($item->isHit()) {
112
                return $item->get();
113
            }
114
        }
115
116
        return null;
117
    }
118
119 2
    private function cache(Token $token, $ttl)
120
    {
121 2
        $cache = $this->cache;
122 2
        if ($cache instanceof CacheInterface) {
123 2
            $cache->set($this->cacheKey, $token->getToken(), (int)$ttl);
124
        } elseif ($cache instanceof CacheItemPoolInterface) {
0 ignored issues
show
introduced by
$cache is always a sub-type of Psr\Cache\CacheItemPoolInterface.
Loading history...
125
            $item = $cache->getItem($this->cacheKey)->set($token->getToken())->expiresAfter((int)$ttl);
126
            $cache->save($item);
127
        }
128 2
    }
129
}
130