Skip to content

Instantly share code, notes, and snippets.

@renebakx
Created May 15, 2025 11:38
Show Gist options
  • Save renebakx/f45ac2b206af4444d122cf3c66a9f9cd to your computer and use it in GitHub Desktop.
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.
<?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