Completed
Push — master ( 390b51...0e9cfd )
by Mario
11:43
created

SymfonyCache::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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