Completed
Push — master ( 7353e9...0c9da4 )
by BENOIT
01:14
created

PSR6Adapter::hasCounter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace BenTools\GuzzleHttp\Middleware\Storage\Adapter;
4
5
use BenTools\GuzzleHttp\Middleware\Storage\Counter;
6
use BenTools\GuzzleHttp\Middleware\Storage\ThrottleStorageInterface;
7
use Psr\Cache\CacheItemPoolInterface;
8
9
/**
10
 * Class PSR6Adapter
11
 * Needs PSR-6 psr/cache implementation (like symfony/cache)
12
 */
13
class PSR6Adapter implements ThrottleStorageInterface
14
{
15
    /**
16
     * @var CacheItemPoolInterface
17
     */
18
    private $cacheItemPool;
19
20
    /**
21
     * PSR6Adapter constructor.
22
     */
23
    public function __construct(CacheItemPoolInterface $cacheItemPool)
24
    {
25
        $this->cacheItemPool = $cacheItemPool;
26
    }
27
28
    /**
29
     * @inheritDoc
30
     */
31
    public function hasCounter(string $storageKey): bool
32
    {
33
        return $this->cacheItemPool->hasItem($storageKey);
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function getCounter(string $storageKey)
40
    {
41
        $item = $this->cacheItemPool->getItem($storageKey);
42
        if ($item->isHit()) {
43
            $counter = unserialize($item->get());
44
        } else {
45
            $counter = null; // will throw TypeError
46
        }
47
        return $counter;
48
    }
49
50
    /**
51
     * @inheritDoc
52
     */
53
    public function saveCounter(string $storageKey, Counter $counter, float $ttl = null)
54
    {
55
        $item = $this->cacheItemPool->getItem($storageKey);
56
        $item->set(serialize($counter));
57
        if (null !== $ttl) {
58
            $item->expiresAfter((int) ceil($ttl));
59
        }
60
        $this->cacheItemPool->save($item);
61
    }
62
63
    /**
64
     * @inheritDoc
65
     */
66
    public function deleteCounter(string $storageKey)
67
    {
68
        $this->cacheItemPool->deleteItem($storageKey);
69
    }
70
}
71