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

ClientRepository::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\Core\Client\Client;
17
use OAuth2Framework\Component\Core\Client\ClientId;
18
use Symfony\Component\Cache\Adapter\AdapterInterface;
19
20
class ClientRepository implements \OAuth2Framework\Component\Core\Client\ClientRepository
21
{
22
    /**
23
     * @var AdapterInterface
24
     */
25
    private $cache;
26
27
    /**
28
     * ClientRepository constructor.
29
     *
30
     * @param AdapterInterface $cache
31
     */
32
    public function __construct(AdapterInterface $cache)
33
    {
34
        $this->cache = $cache;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function find(ClientId $clientId): ? Client
41
    {
42
        $client = $this->getFromCache($clientId);
43
44
        return $client;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function save(Client $client)
51
    {
52
        $client->eraseMessages();
53
        $this->cacheObject($client);
54
    }
55
56
    /**
57
     * @param ClientId $clientId
58
     *
59
     * @return Client|null
60
     */
61
    private function getFromCache(ClientId $clientId): ? Client
62
    {
63
        $itemKey = sprintf('oauth2-client-%s', $clientId->getValue());
64
        $item = $this->cache->getItem($itemKey);
65
        if ($item->isHit()) {
66
            return $item->get();
67
        }
68
69
        return null;
70
    }
71
72
    /**
73
     * @param Client $client
74
     */
75
    private function cacheObject(Client $client)
76
    {
77
        $itemKey = sprintf('oauth2-client-%s', $client->getPublicId()->getValue());
78
        $item = $this->cache->getItem($itemKey);
79
        $item->set($client);
80
        $item->tag(['oauth2_server', 'client', $itemKey]);
81
        $this->cache->save($item);
82
    }
83
}
84