Skip to content

Commit 8eac242

Browse files
Added lock and unlock methods to FilesystemService for resource handling
1 parent 83ff86b commit 8eac242

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/Services/FilesystemService.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515

1616
use function dirname;
1717
use function fclose;
18+
use function fflush;
19+
use function flock;
1820
use function fopen;
21+
use function ftruncate;
1922
use function fwrite;
2023
use function is_resource;
2124
use function microtime;
@@ -43,6 +46,8 @@ public function createDraft(string $filename) // @pest-ignore-type
4346
// @codeCoverageIgnoreEnd
4447
}
4548

49+
$this->lock($resource);
50+
4651
return $resource;
4752
// @codeCoverageIgnoreStart
4853
} catch (Throwable $e) {
@@ -70,6 +75,7 @@ public function release($resource, string $path): void // @pest-ignore-type
7075
{
7176
$temp = $this->getMetaPath($resource);
7277

78+
$this->unlock($resource);
7379
$this->close($resource);
7480

7581
if ($this->file->exists($path)) {
@@ -132,4 +138,27 @@ protected function getMetaPath($file): string
132138

133139
return $meta['uri'] ?? throw new ResourceMetaException;
134140
}
141+
142+
/**
143+
* @param resource $resource
144+
*/
145+
protected function lock($resource): void // @pest-ignore-type
146+
{
147+
if (! flock($resource, LOCK_EX)) {
148+
// @codeCoverageIgnoreStart
149+
throw new RuntimeException('Resource lock error. The resource may be in use by another process.');
150+
// @codeCoverageIgnoreEnd
151+
}
152+
153+
ftruncate($resource, 0);
154+
}
155+
156+
/**
157+
* @param resource $resource
158+
*/
159+
protected function unlock($resource): void // @pest-ignore-type
160+
{
161+
fflush($resource);
162+
flock($resource, LOCK_UN);
163+
}
135164
}

0 commit comments

Comments
 (0)