diff --git a/src/Services/FilesystemService.php b/src/Services/FilesystemService.php index 72c8998..03ef4da 100644 --- a/src/Services/FilesystemService.php +++ b/src/Services/FilesystemService.php @@ -15,7 +15,10 @@ use function dirname; use function fclose; +use function fflush; +use function flock; use function fopen; +use function ftruncate; use function fwrite; use function is_resource; use function microtime; @@ -43,6 +46,8 @@ public function createDraft(string $filename) // @pest-ignore-type // @codeCoverageIgnoreEnd } + $this->lock($resource); + return $resource; // @codeCoverageIgnoreStart } catch (Throwable $e) { @@ -70,6 +75,7 @@ public function release($resource, string $path): void // @pest-ignore-type { $temp = $this->getMetaPath($resource); + $this->unlock($resource); $this->close($resource); if ($this->file->exists($path)) { @@ -132,4 +138,27 @@ protected function getMetaPath($file): string return $meta['uri'] ?? throw new ResourceMetaException; } + + /** + * @param resource $resource + */ + protected function lock($resource): void // @pest-ignore-type + { + if (! flock($resource, LOCK_EX)) { + // @codeCoverageIgnoreStart + throw new RuntimeException('Resource lock error. The resource may be in use by another process.'); + // @codeCoverageIgnoreEnd + } + + ftruncate($resource, 0); + } + + /** + * @param resource $resource + */ + protected function unlock($resource): void // @pest-ignore-type + { + fflush($resource); + flock($resource, LOCK_UN); + } }