Jake Vanderwerf
7 days ago 46d681c6b825d21b3f698d793c4e630c687d90ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
namespace JVBase\managers\queue;
 
if (!defined('ABSPATH')) {
    exit;
}
class Locker
{
    private string $lockKey;
    private int $timeout;
    private ?string $token = null;
 
    public function __construct(string $key = 'queue', int $timeout = 60)
    {
        $this->lockKey = BASE . $key . '_lock';
        $this->timeout = $timeout;
    }
 
    public function withLock(callable $callback): void
    {
        if (!$this->acquire()) return;
 
        try {
            $callback();
        } finally {
            $this->unlock();
        }
    }
 
    private function acquire(): bool
    {
        $this->token = bin2hex(random_bytes(8));
        return (bool) wp_cache_add($this->lockKey, $this->token, 'locks', $this->timeout);
    }
 
    public function unlock(): void
    {
        $current = wp_cache_get($this->lockKey, 'locks');
        if ($current === $this->token) {
            wp_cache_delete($this->lockKey, 'locks');
        }
        $this->token = null;
    }
}