| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
/** |
| 8 |
* Coordinates stats refresh work through WordPress option locks. |
| 9 |
*/ |
| 10 |
class ABJ_404_Solution_StatsRefreshLock { |
| 11 |
|
| 12 |
/** @var int Cooldown for distributed refresh locks. */ |
| 13 |
const REFRESH_LOCK_COOLDOWN_SECONDS = 30; |
| 14 |
|
| 15 |
/** @var ABJ_404_Solution_DatabaseCoreInterface */ |
| 16 |
private $dbCore; |
| 17 |
|
| 18 |
/** @param ABJ_404_Solution_DatabaseCoreInterface $dbCore */ |
| 19 |
public function __construct(ABJ_404_Solution_DatabaseCoreInterface $dbCore) { |
| 20 |
$this->dbCore = $dbCore; |
| 21 |
} |
| 22 |
|
| 23 |
/** @param string $cacheKey @return bool */ |
| 24 |
public function acquire(string $cacheKey): bool { |
| 25 |
if (!function_exists('add_option')) { |
| 26 |
return true; |
| 27 |
} |
| 28 |
|
| 29 |
$lockKey = $this->getOptionName($cacheKey); |
| 30 |
if (add_option($lockKey, abj_clock()->now(), '', false)) { |
| 31 |
return true; |
| 32 |
} |
| 33 |
|
| 34 |
if (!function_exists('get_option')) { |
| 35 |
return false; |
| 36 |
} |
| 37 |
|
| 38 |
$lockValue = get_option($lockKey, false); |
| 39 |
if ($lockValue === false || $lockValue === '' || $lockValue === null) { |
| 40 |
return (bool)add_option($lockKey, abj_clock()->now(), '', false); |
| 41 |
} |
| 42 |
|
| 43 |
$lockTs = is_numeric($lockValue) ? (int)$lockValue : 0; |
| 44 |
if ($lockTs > 0 && (abj_clock()->now() - $lockTs) > self::REFRESH_LOCK_COOLDOWN_SECONDS) { |
| 45 |
if (function_exists('delete_option')) { |
| 46 |
delete_option($lockKey); |
| 47 |
} |
| 48 |
return (bool)add_option($lockKey, abj_clock()->now(), '', false); |
| 49 |
} |
| 50 |
|
| 51 |
return false; |
| 52 |
} |
| 53 |
|
| 54 |
/** @param string $cacheKey @return void */ |
| 55 |
public function release(string $cacheKey): void { |
| 56 |
if (function_exists('delete_option')) { |
| 57 |
delete_option($this->getOptionName($cacheKey)); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
/** @param string $cacheKey @return string */ |
| 62 |
private function getOptionName(string $cacheKey): string { |
| 63 |
return $this->dbCore->tableNameResolver()->getLowercasePrefix() . 'abj404_view_cache_lock_' . md5((string)$cacheKey); |
| 64 |
} |
| 65 |
} |
| 66 |
|