Passed
Branch main (8837c4)
by Sílvio
14:13
created

RedisKeyspace::resolveTTL()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 6
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 13
rs 9.2222
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore\Support;
4
5
use Silviooosilva\CacheerPhp\Helpers\CacheFileHelper;
6
7
/**
8
 * Handles namespacing and TTL resolution for Redis cache keys.
9
 */
10
final class RedisKeyspace
11
{   
12
    /** @var string */
13
    private string $namespace;
14
15
    /** @var int|null */
16
    private ?int $defaultTTL;
17
18
    /**
19
     * @param string $namespace
20
     * @param int|null $defaultTTL
21
     * 
22
     * @return void
23
     */
24
    public function __construct(string $namespace = '', ?int $defaultTTL = null)
25
    {
26
        $this->namespace = $namespace;
27
        $this->defaultTTL = $defaultTTL;
28
    }
29
30
    /**
31
     * @param string $key
32
     * @param string $namespace
33
     * 
34
     * @return string
35
     */
36
    public function build(string $key, string $namespace = ''): string
37
    {
38
        return $this->namespace . ($namespace ? $namespace . ':' : '') . $key;
39
    }
40
41
    /**
42
     * @param string $tag
43
     * 
44
     * @return string
45
     */
46
    public function tagKey(string $tag): string
47
    {
48
        return 'tag:' . $tag;
49
    }
50
51
    /**
52
     * @param string|int|null $ttl
53
     * 
54
     * @return int|null
55
     */
56
    public function resolveTTL(string|int|null $ttl): ?int
57
    {
58
        $ttlToUse = $ttl;
59
60
        if ($this->defaultTTL !== null && ($ttl === null || (int) $ttl === 3600)) {
61
            $ttlToUse = $this->defaultTTL;
62
        }
63
64
        if (is_string($ttlToUse)) {
65
            $ttlToUse = (int) CacheFileHelper::convertExpirationToSeconds($ttlToUse);
66
        }
67
68
        return $ttlToUse === null ? null : (int) $ttlToUse;
69
    }
70
}
71