| 1 |
<?php |
| 2 |
|
| 3 |
declare (strict_types=1); |
| 4 |
namespace WindPress\WindPress\Core\Scanner; |
| 5 |
|
| 6 |
class ScanLock |
| 7 |
{ |
| 8 |
private const LEASE_SECONDS = 300; |
| 9 |
public static function acquire(string $resource): ?string |
| 10 |
{ |
| 11 |
global $wpdb; |
| 12 |
$option = self::option_name($resource); |
| 13 |
$previous = get_option($option, \false); |
| 14 |
if (is_array($previous) && ($previous['expires'] ?? 0) <= time()) { |
| 15 |
// Compare the entire observed lease so another request's replacement survives. |
| 16 |
$wpdb->delete($wpdb->options, ['option_name' => $option, 'option_value' => maybe_serialize($previous)]); |
| 17 |
wp_cache_delete($option, 'options'); |
| 18 |
} |
| 19 |
$token = wp_generate_uuid4(); |
| 20 |
$acquired = add_option($option, ['token' => $token, 'expires' => time() + self::LEASE_SECONDS], '', \false); |
| 21 |
return $acquired ? $token : null; |
| 22 |
} |
| 23 |
public static function is_owner(string $resource, string $token): bool |
| 24 |
{ |
| 25 |
$option = self::option_name($resource); |
| 26 |
wp_cache_delete($option, 'options'); |
| 27 |
$lease = get_option($option, \false); |
| 28 |
return is_array($lease) && ($lease['token'] ?? null) === $token && ($lease['expires'] ?? 0) > time(); |
| 29 |
} |
| 30 |
public static function release(string $resource, string $token): void |
| 31 |
{ |
| 32 |
global $wpdb; |
| 33 |
$option = self::option_name($resource); |
| 34 |
wp_cache_delete($option, 'options'); |
| 35 |
$lease = get_option($option, \false); |
| 36 |
if (is_array($lease) && ($lease['token'] ?? null) === $token) { |
| 37 |
$wpdb->delete($wpdb->options, ['option_name' => $option, 'option_value' => maybe_serialize($lease)]); |
| 38 |
wp_cache_delete($option, 'options'); |
| 39 |
} |
| 40 |
} |
| 41 |
private static function option_name(string $resource): string |
| 42 |
{ |
| 43 |
return 'windpress_scan_lock_' . hash('sha256', $resource); |
| 44 |
} |
| 45 |
} |
| 46 |
|