Created
May 15, 2025 11:38
-
-
Save renebakx/f45ac2b206af4444d122cf3c66a9f9cd to your computer and use it in GitHub Desktop.
Very simple TimedLock class for Drupal 10 and 11 using the core state system.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\Datetime\DrupalDateTime; | |
class TimedLock { | |
protected static $lockPrefix = 'time_lock:'; | |
public static function getLock(string $name, int $duration=60):bool { | |
$lockKey = self::$lockPrefix . $name; | |
$lockData = \Drupal::state()->get($lockKey); | |
$currentTime = (new DrupalDateTime())->getTimestamp(); | |
if (!empty($lockData)) { | |
if ($currentTime < $lockData['expires']) { | |
return FALSE; | |
} | |
} | |
$lockData = [ | |
'acquired' => $currentTime, | |
'expires' => $currentTime + $duration, | |
]; | |
\Drupal::state()->set($lockKey, $lockData); | |
return TRUE; | |
} | |
public static function release(string $name) { | |
$lockKey = self::$lockPrefix . $name; | |
\Drupal::state()->delete($lockKey); | |
} | |
public static function isLocked(string $name) { | |
$lockKey = self::$lockPrefix . $name; | |
$lockData = \Drupal::state()->get($lockKey); | |
if ($lockData) { | |
$currentTime = (new DrupalDateTime())->getTimestamp(); | |
return $currentTime < $lockData['expires']; | |
} | |
return FALSE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment