Failed Conditions
Push — ng ( 9b5389...3a0de5 )
by Florent
03:43
created

RefreshTokenRepository::getFromEvents()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Bundle\Tests\TestBundle\Entity;
15
16
use OAuth2Framework\Component\RefreshTokenGrant\RefreshToken;
17
use OAuth2Framework\Component\RefreshTokenGrant\RefreshTokenId;
18
use OAuth2Framework\Component\RefreshTokenGrant\RefreshTokenRepository as RefreshTokenRepositoryInterface;
19
use Symfony\Component\Cache\Adapter\AdapterInterface;
20
21
class RefreshTokenRepository implements RefreshTokenRepositoryInterface
22
{
23
    /**
24
     * @var AdapterInterface
25
     */
26
    private $cache;
27
28
    /**
29
     * RefreshTokenRepository constructor.
30
     *
31
     * @param AdapterInterface $cache
32
     */
33
    public function __construct(AdapterInterface $cache)
34
    {
35
        $this->cache = $cache;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function find(RefreshTokenId $refreshTokenId)
42
    {
43
        $refreshToken = $this->getFromCache($refreshTokenId);
44
45
        return $refreshToken;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function save(RefreshToken $refreshToken)
52
    {
53
        $refreshToken->eraseMessages();
54
        $this->cacheObject($refreshToken);
55
    }
56
57
    /**
58
     * @param RefreshTokenId $refreshTokenId
59
     *
60
     * @return RefreshToken|null
61
     */
62
    private function getFromCache(RefreshTokenId $refreshTokenId): ? RefreshToken
63
    {
64
        $itemKey = sprintf('oauth2-refresh_token-%s', $refreshTokenId->getValue());
65
        $item = $this->cache->getItem($itemKey);
66
        if ($item->isHit()) {
67
            return $item->get();
68
        }
69
70
        return null;
71
    }
72
73
    /**
74
     * @param RefreshToken $refreshToken
75
     */
76
    private function cacheObject(RefreshToken $refreshToken)
77
    {
78
        $itemKey = sprintf('oauth2-refresh_token-%s', $refreshToken->getTokenId()->getValue());
79
        $item = $this->cache->getItem($itemKey);
80
        $item->set($refreshToken);
81
        $item->tag(['oauth2_server', 'refresh_token', $itemKey]);
82
        $this->cache->save($item);
83
    }
84
}
85