Completed
Pull Request — master (#1)
by Peter
02:16
created

ClientWithCache::getPlayer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
namespace PtrTn\Battlerite;
4
5
use Doctrine\Common\Cache\Cache;
6
use Doctrine\Common\Cache\FilesystemCache;
7
use GuzzleHttp\Client as GuzzleClient;
8
use PtrTn\Battlerite\Dto\Match\DetailedMatch;
9
use PtrTn\Battlerite\Dto\Player\DetailedPlayer;
10
11
class ClientWithCache
12
{
13
    private const CACHE_DIR = '/tmp/battlerite';
14
15
    private const CACHE_PREFIX = 'battlerite-';
16
17
    private const CACHE_LIFETIME = 300;
18
19
    /**
20
     * @var Client
21
     */
22
    private $client;
23
    /**
24
     * @var Cache
25
     */
26
    private $cache;
27
28 2
    public function __construct(Client $client, Cache $cache)
29
    {
30 2
        $this->client = $client;
31 2
        $this->cache = $cache;
32 2
    }
33
34
    /**
35
     * Create default API client setup with a filesystem caching layer
36
     */
37
    public static function create(string $apiKey): self
38
    {
39
        return new self(
40
            new Client(
41
                new ApiClient(
42
                    $apiKey,
43
                    new GuzzleClient()
44
                )
45
            ),
46
            new FilesystemCache(self::CACHE_DIR, '.cache')
47
        );
48
    }
49
50
    /**
51
     * Create default API client setup with a custom caching layer
52
     */
53
    public static function createWithCache(string $apiKey, Cache $cache): self
54
    {
55
        return new self(
56
            new Client(
57
                new ApiClient(
58
                    $apiKey,
59
                    new GuzzleClient()
60
                )
61
            ),
62
            $cache
63
        );
64
    }
65
66 1
    public function getPlayer(string $playerId): DetailedPlayer
67
    {
68 1
        $cacheKey = self::CACHE_PREFIX . '-player-' . $playerId;
69 1
        if ($this->cache->contains($cacheKey)) {
70 1
            return $this->cache->fetch($cacheKey);
71
        }
72 1
        $data = $this->client->getPlayer($playerId);
73 1
        $this->cache->save($cacheKey, $data, self::CACHE_LIFETIME);
74 1
        return $data;
75
    }
76
77 1
    public function getMatch(string $matchId): DetailedMatch
78
    {
79 1
        $cacheKey = self::CACHE_PREFIX . '-match-' . $matchId;
80 1
        if ($this->cache->contains($cacheKey)) {
81 1
            return $this->cache->fetch($cacheKey);
82
        }
83 1
        $data = $this->client->getMatch($matchId);
84 1
        $this->cache->save($cacheKey, $data, self::CACHE_LIFETIME);
85 1
        return $data;
86
    }
87
}
88