1
0
mirror of https://github.com/danog/file.git synced 2024-12-02 09:17:57 +01:00

Add Filesystem arg to FileMutex

This commit is contained in:
Aaron Piotrowski 2024-03-09 10:05:11 -06:00
parent 8e063788e8
commit 0bc3e2d251
No known key found for this signature in database
GPG Key ID: 5B456E6AABA44A63

View File

@ -11,11 +11,14 @@ final class FileMutex implements Mutex
{ {
private const LATENCY_TIMEOUT = 0.01; private const LATENCY_TIMEOUT = 0.01;
private readonly Filesystem $filesystem;
/** /**
* @param string $fileName Name of temporary file to use as a mutex. * @param string $fileName Name of temporary file to use as a mutex.
*/ */
public function __construct(private readonly string $fileName) public function __construct(private readonly string $fileName, ?Filesystem $filesystem = null)
{ {
$this->filesystem = $filesystem ?? filesystem();
} }
public function acquire(): Lock public function acquire(): Lock
@ -24,7 +27,7 @@ final class FileMutex implements Mutex
// has the lock, so set an asynchronous timer and try again. // has the lock, so set an asynchronous timer and try again.
while (true) { while (true) {
try { try {
$file = openFile($this->fileName, 'x'); $file = $this->filesystem->openFile($this->fileName, 'x');
// Return a lock object that can be used to release the lock on the mutex. // Return a lock object that can be used to release the lock on the mutex.
$lock = new Lock($this->release(...)); $lock = new Lock($this->release(...));
@ -46,12 +49,11 @@ final class FileMutex implements Mutex
private function release(): void private function release(): void
{ {
try { try {
deleteFile($this->fileName); $this->filesystem->deleteFile($this->fileName);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
throw new SyncException( throw new SyncException(
'Failed to unlock the mutex file: ' . $this->fileName, 'Failed to unlock the mutex file: ' . $this->fileName,
0, previous: $exception,
$exception
); );
} }
} }