ldc-cocotte/infra/Adapters/Locks/LaravelCacheLock.php

53 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Infrastructure\Adapters\Locks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\LockTimeoutException as LaravelLockTimeoutException;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
final readonly class LaravelCacheLock implements Lock
{
public function __construct(
private CacheRepository $cache,
) {
}
/**
* @template T
*
* @param callable(): T $callback
* @return T
*
* @throws \Shared\Concurrency\LockTimeoutException
*/
#[\Override]
public function synchronize(
string $key,
callable $callback,
int $ttlSeconds = 30,
int $waitSeconds = 10,
): mixed {
$store = $this->cache->getStore();
if (! $store instanceof LockProvider) {
throw new \UnexpectedValueException('Cache store does not implement LockProvider.');
}
$lock = $store->lock($key, $ttlSeconds);
try {
return $lock->block($waitSeconds, $callback);
} catch (LaravelLockTimeoutException $e) {
throw new LockTimeoutException(
message: $e->getMessage(),
code: (int) $e->getCode(),
previous: $e,
);
}
}
}