SymfonyCache::get()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Marek\OpenWeatherMap\Core\Cache;
6
7
use Marek\OpenWeatherMap\API\Cache\HandlerInterface;
8
use Symfony\Component\Cache\Adapter\AdapterInterface;
9
10
class SymfonyCache implements HandlerInterface
11
{
12
    /**
13
     * @var \Symfony\Component\Cache\Adapter\AdapterInterface
14
     */
15
    protected $cache;
16
17
    /**
18
     * @var int
19
     */
20
    protected $timeToLive;
21
22
    /**
23
     * SymfonyCache constructor.
24
     *
25
     * @param \Symfony\Component\Cache\Adapter\AdapterInterface $cache
26
     * @param int $timeToLive
27
     */
28
    public function __construct(AdapterInterface $cache, int $timeToLive = 3600)
29
    {
30
        $this->cache = $cache;
31
        $this->timeToLive = $timeToLive;
32
    }
33
34
    public function has(string $cacheKey): bool
35
    {
36
        $key = $this->computeKey($cacheKey);
37
38
        $item = $this->cache->getItem($key);
39
40
        return $item->isHit();
41
    }
42
43
    public function get(string $cacheKey): array
44
    {
45
        $key = $this->computeKey($cacheKey);
46
47
        $item = $this->cache->getItem($key);
48
49
        return $item->get();
50
    }
51
52
    public function set(string $cacheKey, array $data): void
53
    {
54
        $key = $this->computeKey($cacheKey);
55
56
        $item = $this->cache->getItem($key);
57
        $item->expiresAfter($this->timeToLive);
58
59
        $item->set($data);
60
        $this->cache->save($item);
61
    }
62
63
    protected function computeKey(string $cacheKey): string
64
    {
65
        return md5(self::CACHE_KEY_PREFIX . $cacheKey);
66
    }
67
}
68