AccessTokenCacheHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 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