ManagesLocksAndShardsTrait::acquireLock()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 4
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Padosoft\SuperCache\Traits;
4
5
trait ManagesLocksAndShardsTrait
6
{
7
    /**
8
     * Acquisisce un lock ottimistico su una chiave.
9
     */
10
    protected function acquireLock(string $key, ?string $connection_name = null): bool
11
    {
12
        $lockKey = 'lock:' . $key;
0 ignored issues
show
Unused Code introduced by
The assignment to $lockKey is dead and can be removed.
Loading history...
13
        // Tenta di acquisire il lock con un timeout di 10 secondi
14
        //return $this->redis->getRedisConnection($connection_name)->set($lockKey, '1', 'NX', 'EX', 10);
15
        return $this->redis->getRedisConnection($connection_name)->set($key, 1, 'EX', 10, 'NX');
16
    }
17
18
    /**
19
     * Rilascia un lock ottimistico su una chiave.
20
     */
21
    protected function releaseLock(string $key, ?string $connection_name = null): void
22
    {
23
        $lockKey = 'lock:' . $key;
24
        $this->redis->getRedisConnection($connection_name)->del($lockKey);
25
    }
26
27
    /**
28
     * Ricava il nome dello shard per una chiave e un tag.
29
     */
30
    protected function getShardNameForTag(string $tag, string $key): string
31
    {
32
        // Usa lo stesso algoritmo di sharding della cache manager
33
        $hash = crc32($key);
34
        $numShards = (int) config('supercache.num_shards');
35
        $shardIndex = $hash % $numShards;
36
37
        return config('supercache.prefix') . 'tag:' . $tag . ':shard:' . $shardIndex;
38
    }
39
}
40