PluginProbe
404 Solution / 4.3.0
404 Solution v4.3.0
4.3.5 4.3.4 4.3.3 4.3.2 4.3.1 4.3.0 4.2.0 4.1.19 4.1.18 4.1.17 4.1.16 4.1.15 4.1.13 4.1.12 4.1.11 4.1.10 4.1.9 4.1.8 4.1.7 4.1.6 4.1.5 4.1.4 4.1.3 trunk 2.30.0 All 109 releases
404-solution / includes / stats / StatsRefreshLock.php

StatsRefreshLock.php in 404 Solution 4.3.0, at includes/stats/StatsRefreshLock.php

66 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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