AccessTokenCacheHandler   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 56
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getTokenByProvider() 0 9 2
A saveTokenByProvider() 0 14 1
A deleteItemByProvider() 0 4 1
A getCacheKey() 0 6 1
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 18
    public function __construct(CacheItemPoolInterface $cache)
17
    {
18 18
        $this->cache = $cache;
19 18
    }
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 4
    public function getTokenByProvider(OAuth2Provider $provider, array $options)
30
    {
31 4
        $cacheKey = $this->getCacheKey($provider, $options);
32 4
        $cacheItem = $this->cache->getItem($cacheKey);
33 4
        if ($cacheItem->isHit()) {
34 2
            return $cacheItem->get();
35
        }
36 2
        return false;
37
    }
38
39 2
    public function saveTokenByProvider(AccessToken $accessToken, OAuth2Provider $provider, array $options): bool
40
    {
41 2
        $cacheKey = $this->getCacheKey($provider, $options);
42 2
        $cacheItem = $this->cache->getItem($cacheKey);
43 2
        $cacheItem->set(
44 2
            $accessToken->getToken()
45
        );
46 2
        $expiration = new \DateTime();
47 2
        $expiration->setTimestamp($accessToken->getExpires());
48 2
        $cacheItem->expiresAt(
49 2
            $expiration
50
        );
51 2
        return $this->cache->save($cacheItem);
52
    }
53
54 2
    public function deleteItemByProvider(OAuth2Provider $provider, array $options): bool
55
    {
56 2
        return $this->cache->deleteItem($this->getCacheKey($provider, $options));
57
    }
58
59 14
    public function getCacheKey(OAuth2Provider $provider, array $options): string
60
    {
61 14
        parse_str(parse_url($provider->getAuthorizationUrl(), PHP_URL_QUERY), $query);
62 14
        return static::CACHE_KEY_PREFIX
63 14
            . md5($provider->getBaseAuthorizationUrl() . ($query['client_id'] ?? '') . serialize($options));
64
    }
65
}
66