[HttpFoundation] use atomic writes in MockFileSessionStorage

This commit is contained in:
Nicolas Grekas 2021-01-13 14:01:18 +01:00
parent d23b74ebce
commit 5290e978bd

View File

@ -103,7 +103,10 @@ class MockFileSessionStorage extends MockArraySessionStorage
try {
if ($data) {
file_put_contents($this->getFilePath(), serialize($data));
$path = $this->getFilePath();
$tmp = $path.bin2hex(random_bytes(6));
file_put_contents($tmp, serialize($data));
rename($tmp, $path);
} else {
$this->destroy();
}
@ -123,8 +126,11 @@ class MockFileSessionStorage extends MockArraySessionStorage
*/
private function destroy(): void
{
if (is_file($this->getFilePath())) {
set_error_handler(static function () {});
try {
unlink($this->getFilePath());
} finally {
restore_error_handler();
}
}
@ -141,8 +147,14 @@ class MockFileSessionStorage extends MockArraySessionStorage
*/
private function read(): void
{
$filePath = $this->getFilePath();
$this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : [];
set_error_handler(static function () {});
try {
$data = file_get_contents($this->getFilePath());
} finally {
restore_error_handler();
}
$this->data = $data ? unserialize($data) : [];
$this->loadSession();
}