Cache::save()   A
last analyzed

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
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/*
3
 * This file is part of the Concurrency Limit package.
4
 *
5
 * (c) Bogdan Koval' <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types = 1);
12
13
namespace Bogkov\ConcurrencyLimit\Provider;
14
15
use Doctrine\Common\Cache\CacheProvider;
16
17
/**
18
 * Class Cache
19
 *
20
 * @package Bogkov\ConcurrencyLimit\Provider
21
 */
22
class Cache implements ProviderInterface
23
{
24
    const DEFAULT_LIFETIME = 30;
25
26
    /**
27
     * @var CacheProvider
28
     */
29
    protected $cache;
30
31
    /**
32
     * @var int
33
     */
34
    protected $lifetime;
35
36
    /**
37
     * Cache constructor.
38
     *
39
     * @param CacheProvider $cache    cache
40
     * @param int           $lifetime lifetime
41
     */
42
    public function __construct(CacheProvider $cache, int $lifetime = self::DEFAULT_LIFETIME)
43
    {
44
        $this->cache = $cache;
45
        $this->lifetime = $lifetime;
46
    }
47
48
    /**
49
     * @param string $key key
50
     *
51
     * @return int|null
52
     */
53
    public function fetch(string $key)/*: ?int*/
54
    {
55
        return false !== ($result = $this->cache->fetch(static::prepareKey($key))) ? $result : null;
56
    }
57
58
    /**
59
     * @param string $key   key
60
     * @param int    $value value
61
     *
62
     * @return bool
63
     */
64
    public function save(string $key, int $value): bool
65
    {
66
        return $this->cache->save(static::prepareKey($key), $value, $this->lifetime);
67
    }
68
69
    /**
70
     * @param string $key key
71
     *
72
     * @return string
73
     */
74
    protected static function prepareKey(string $key): string
75
    {
76
        return sha1(strtolower(__CLASS__ . $key));
77
    }
78
}