Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
53 lines
1.4 KiB
PHP
53 lines
1.4 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace LIT\MCP\Integrations\Divi\Design;
|
||
|
||
use InvalidArgumentException;
|
||
|
||
defined('ABSPATH') || exit;
|
||
|
||
/**
|
||
* One confirmed change per design area at a time (final review I-5): an option lit_mcp_lock_<area> (never
|
||
* autoloaded) holds the time the lock was taken. add_option() is atomic – it fails while the option exists. A lock
|
||
* older than STALE_AFTER seconds (a request that died) is removed and taken once more.
|
||
*/
|
||
final class DesignLock
|
||
{
|
||
public const STALE_AFTER = 120;
|
||
|
||
private const PREFIX = 'lit_mcp_lock_';
|
||
|
||
/** @throws InvalidArgumentException For an area outside SnapshotStore::AREAS. */
|
||
public static function option(string $area): string
|
||
{
|
||
if (! in_array($area, SnapshotStore::AREAS, true)) {
|
||
throw new InvalidArgumentException(sprintf('Unknown design area "%s".', $area));
|
||
}
|
||
|
||
return self::PREFIX . $area;
|
||
}
|
||
|
||
public function acquire(string $area): bool
|
||
{
|
||
$option = self::option($area);
|
||
if (add_option($option, time(), '', false)) {
|
||
return true;
|
||
}
|
||
|
||
$since = get_option($option, 0);
|
||
if (is_numeric($since) && time() - (int) $since <= self::STALE_AFTER) {
|
||
return false;
|
||
}
|
||
delete_option($option);
|
||
|
||
return add_option($option, time(), '', false);
|
||
}
|
||
|
||
public function release(string $area): void
|
||
{
|
||
delete_option(self::option($area));
|
||
}
|
||
}
|