Completed
Pull Request — master (#12)
by Andrea De
06:45 queued 01:44
created

AccessTokenCacheHandler::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
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\Cache\CacheItemPoolInterface;
8
use Psr\Cache\InvalidArgumentException;
9
10
class AccessTokenCacheHandler
11
{
12
    const CACHE_KEY_PREFIX = 'oauth2-token-';
13
14
    private $cache;
15
16 4
    public function __construct(CacheItemPoolInterface $cache)
17
    {
18 4
        $this->cache = $cache;
19 4
    }
20
21
    /**
22
     * @param OAuth2Provider $provider
23
     * @param array          $options
24
     *
25
     * @throws InvalidArgumentException
26
     *
27
     * @return string|bool False if no token can be found in cache, the token's value otherwise.
28
     */
29
    public function getTokenByProvider(OAuth2Provider $provider, array $options)
30
    {
31
        $cacheKey = $this->getCacheKey($provider, $options);
32
        $cacheItem = $this->cache->getItem($cacheKey);
33
        if ($cacheItem->isHit()) {
34
            return $cacheItem->get();
35
        }
36
        return false;
37
    }
38
39
    public function saveTokenByProvider(AccessToken $accessToken, OAuth2Provider $provider, array $options): bool
40
    {
41
        $cacheKey = $this->getCacheKey($provider, $options);
42
        $cacheItem = $this->cache->getItem($cacheKey);
43
        $cacheItem->set(
44
            $accessToken->getToken()
45
        );
46
        $expiration = new \DateTime();
47
        $expiration->setTimestamp($accessToken->getExpires());
48
        $cacheItem->expiresAt(
49
            $expiration
50
        );
51
        return $this->cache->save($cacheItem);
52
    }
53
54
    public function deleteItemByProvider(OAuth2Provider $provider, array $options): bool
55
    {
56
        return $this->cache->deleteItem($this->getCacheKey($provider, $options));
57
    }
58
59
    public function getCacheKey(OAuth2Provider $provider, array $options): string
60
    {
61
        $query = [];
62
        parse_str(parse_url($provider->getAuthorizationUrl(), PHP_URL_QUERY), $query);
63
        return static::CACHE_KEY_PREFIX
64
            . md5($provider->getBaseAuthorizationUrl() . $query['client_id'] . serialize($options));
65
    }
66
}
67