Skip to content

Commit d84fa17

Browse files
committed
PHPLIB-1313 Ensure the GridFS stream is saved when the script ends
1 parent 9f8eac1 commit d84fa17

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

src/GridFS/StreamWrapper.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,11 @@ class StreamWrapper
5353

5454
public function __destruct()
5555
{
56-
/* This destructor is a workaround for PHP trying to use the stream well
57-
* after all objects have been destructed. This can cause autoloading
58-
* issues and possibly segmentation faults during PHP shutdown. */
59-
$this->stream = null;
56+
/* Ensure the stream is closed so the last chunk is written. This is
57+
* necessary because PHP would close the stream after all objects have
58+
* been destructed. This can cause autoloading issues and possibly
59+
* segmentation faults during PHP shutdown. */
60+
$this->stream_close();
6061
}
6162

6263
/**

tests/GridFS/StreamWrapperFunctionalTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@
55
use MongoDB\BSON\Binary;
66
use MongoDB\BSON\UTCDateTime;
77

8+
use function escapeshellarg;
9+
use function exec;
810
use function fclose;
911
use function feof;
1012
use function fread;
1113
use function fseek;
1214
use function fstat;
1315
use function fwrite;
1416

17+
use const PHP_BINARY;
1518
use const SEEK_CUR;
1619
use const SEEK_END;
1720
use const SEEK_SET;
@@ -204,4 +207,18 @@ public function testWritableStreamWrite(): void
204207

205208
$this->assertSame(6, fwrite($stream, 'foobar'));
206209
}
210+
211+
public function testAutocloseOnScriptEnd(): void
212+
{
213+
$command = PHP_BINARY . ' ' . escapeshellarg(__DIR__ . '/scripts/stream-autoclose.php');
214+
exec($command, $output, $exitCode);
215+
216+
$this->assertSame([], $output);
217+
$this->assertSame(0, $exitCode);
218+
219+
$fileDocument = $this->filesCollection->findOne(['filename' => 'hello.txt']);
220+
221+
$this->assertNotNull($fileDocument);
222+
$this->assertSame(14, $fileDocument->length);
223+
}
207224
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
use MongoDB\Client;
4+
5+
require __DIR__ . '/../../../vendor/autoload.php';
6+
7+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100');
8+
$database = $client->selectDatabase(getenv('MONGODB_DATABASE') ?: 'phplib_test');
9+
$gridfs = $database->selectGridFSBucket();
10+
$stream = $gridfs->openUploadStream('hello.txt');
11+
fwrite($stream, 'Hello MongoDB!');
12+
13+
// The WriteStream must be closed and the file inserted automatically

0 commit comments

Comments
 (0)