Skip to content

Commit 9cc7dfa

Browse files
Merge pull request #158 from neo4j-php/flock
improved handling of file
2 parents fc13df0 + dedc144 commit 9cc7dfa

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/protocol/AProtocol.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,10 +170,19 @@ public function __destruct()
170170
{
171171
if (!getenv('BOLT_ANALYTICS_OPTOUT') && is_writable(sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php-bolt-analytics' . DIRECTORY_SEPARATOR)) {
172172
$file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php-bolt-analytics' . DIRECTORY_SEPARATOR . 'analytics.' . strtotime('today') . '.json';
173-
$data = file_exists($file) ? (array)json_decode((string)file_get_contents($file), true) : [];
174-
$data['queries'] = ($data['queries'] ?? 0) + $this->writeCalls;
175-
$data['sessions'] = ($data['sessions'] ?? 0) + 1;
176-
file_put_contents($file, json_encode($data));
173+
174+
$fp = fopen($file, 'c+');
175+
if (flock($fp, LOCK_EX)) {
176+
$data = json_decode(fread($fp, length: 8192), true) ?? [];
177+
$data['queries'] = ($data['queries'] ?? 0) + $this->writeCalls;
178+
$data['sessions'] = ($data['sessions'] ?? 0) + 1;
179+
180+
ftruncate($fp, 0);
181+
rewind($fp);
182+
fwrite($fp, json_encode($data));
183+
flock($fp, LOCK_UN);
184+
}
185+
fclose($fp);
177186
}
178187
}
179188
}

0 commit comments

Comments
 (0)