| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Jobs; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
|
| 7 |
class LockManager |
| 8 |
{ |
| 9 |
public function acquire(string $jobType, int $timeout = 0): bool |
| 10 |
{ |
| 11 |
return $this->acquireNamedLock('sync_basalam_job_' . $jobType, $timeout); |
| 12 |
} |
| 13 |
|
| 14 |
public function release(string $jobType): bool |
| 15 |
{ |
| 16 |
return $this->releaseNamedLock('sync_basalam_job_' . $jobType); |
| 17 |
} |
| 18 |
|
| 19 |
public function acquireGlobalJobsLock(int $timeout = 0): bool |
| 20 |
{ |
| 21 |
return $this->acquireNamedLock('sync_basalam_jobs_runner', $timeout); |
| 22 |
} |
| 23 |
|
| 24 |
public function releaseGlobalJobsLock(): bool |
| 25 |
{ |
| 26 |
return $this->releaseNamedLock('sync_basalam_jobs_runner'); |
| 27 |
} |
| 28 |
|
| 29 |
private function acquireNamedLock(string $lockName, int $timeout = 0): bool |
| 30 |
{ |
| 31 |
global $wpdb; |
| 32 |
|
| 33 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Named MySQL advisory lock; no object cache applicable. |
| 34 |
$result = $wpdb->get_var($wpdb->prepare("SELECT GET_LOCK(%s, %d)", $lockName, $timeout)); |
| 35 |
|
| 36 |
return $result === '1'; |
| 37 |
} |
| 38 |
|
| 39 |
private function releaseNamedLock(string $lockName): bool |
| 40 |
{ |
| 41 |
global $wpdb; |
| 42 |
|
| 43 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Named MySQL advisory lock; no object cache applicable. |
| 44 |
$result = $wpdb->get_var($wpdb->prepare("SELECT RELEASE_LOCK(%s)", $lockName)); |
| 45 |
|
| 46 |
return $result === '1'; |
| 47 |
} |
| 48 |
} |
| 49 |
|