Skip to content

Commit 2922936

Browse files
committed
refactor: make 2 separate methods for read/write file with lock operation;
1 parent 346d9a2 commit 2922936

File tree

1 file changed

+22
-27
lines changed

1 file changed

+22
-27
lines changed

src/Drivers/BaseDriver.php

+22-27
Original file line numberDiff line numberDiff line change
@@ -32,29 +32,13 @@ public function getTmpData(): ?array
3232

3333
public function saveSharedTmpData(callable $callback): void
3434
{
35-
$this->handleFileWithLock(
36-
filePath: $this->sharedTempFilePath,
37-
mode: 'c+',
38-
operation: LOCK_EX | LOCK_NB,
39-
callback: function ($handle) use ($callback) {
40-
$data = $callback($this->readJsonFromStream($handle));
41-
42-
$this->writeJsonToStream($handle, $data);
43-
},
44-
);
35+
$this->writeFileWithLock($this->sharedTempFilePath, $callback);
4536
}
4637

4738
public function getSharedTmpData(): ?array
4839
{
4940
if (file_exists($this->sharedTempFilePath)) {
50-
return $this->handleFileWithLock(
51-
filePath: $this->sharedTempFilePath,
52-
mode: 'r',
53-
operation: LOCK_SH,
54-
callback: function ($handle) {
55-
return $this->readJsonFromStream($handle);
56-
},
57-
);
41+
return $this->readFileWithLock($this->sharedTempFilePath);
5842
}
5943

6044
return null;
@@ -83,19 +67,30 @@ protected function getJsonFromFile(string $filePath): ?array
8367
return null;
8468
}
8569

86-
protected function handleFileWithLock(
87-
string $filePath,
88-
string $mode,
89-
int $operation,
90-
callable $callback,
91-
): mixed
70+
protected function readFileWithLock(string $filePath): array
71+
{
72+
$handle = fopen($filePath, 'r');
73+
74+
try {
75+
$this->acquireLock($handle, LOCK_SH);
76+
77+
return $this->readJsonFromStream($handle);
78+
} finally {
79+
flock($handle, LOCK_UN);
80+
fclose($handle);
81+
}
82+
}
83+
84+
protected function writeFileWithLock(string $filePath, callable $callback): void
9285
{
93-
$handle = fopen($filePath, $mode);
86+
$handle = fopen($filePath, 'c+');
9487

9588
try {
96-
$this->acquireLock($handle, $operation);
89+
$this->acquireLock($handle, LOCK_EX | LOCK_NB);
90+
91+
$data = $callback($this->readJsonFromStream($handle));
9792

98-
return $callback($handle);
93+
$this->writeJsonToStream($handle, $data);
9994
} finally {
10095
flock($handle, LOCK_UN);
10196
fclose($handle);

0 commit comments

Comments
 (0)