@@ -21,6 +21,7 @@ class GridFsUpload
21
21
private $ chunkSize ;
22
22
private $ buffer ;
23
23
private $ file ;
24
+ private $ isClosed = false ;
24
25
/**
25
26
* Constructs a GridFS upload stream
26
27
*
@@ -123,6 +124,9 @@ public function uploadFromStream($source)
123
124
*/
124
125
public function insertChunks ($ toWrite )
125
126
{
127
+ if ($ this ->isClosed ){
128
+ return ;
129
+ }
126
130
$ readBytes = 0 ;
127
131
while ($ readBytes != strlen ($ toWrite )) {
128
132
$ addToBuffer = substr ($ toWrite , $ readBytes , $ this ->chunkSize - $ this ->bufferLength );
@@ -144,6 +148,9 @@ public function insertChunks($toWrite)
144
148
*/
145
149
public function close ()
146
150
{
151
+ if ($ this ->isClosed ){
152
+ return ;
153
+ }
147
154
rewind ($ this ->buffer );
148
155
$ cached = stream_get_contents ($ this ->buffer );
149
156
@@ -152,6 +159,7 @@ public function close()
152
159
}
153
160
fclose ($ this ->buffer );
154
161
$ this ->fileCollectionInsert ();
162
+ $ this ->isClosed = true ;
155
163
}
156
164
public function getSize ()
157
165
{
@@ -175,22 +183,43 @@ public function getFile()
175
183
}
176
184
public function isEOF ()
177
185
{
178
- return false ;
186
+ return $ this ->isClosed ;
187
+ }
188
+ private function abort ()
189
+ {
190
+ $ this ->collectionsWrapper ->getChunksCollection ()->deleteMany (["files_id " => $ this ->file ["_id " ]]);
191
+ $ this ->collectionsWrapper ->getFilesCollection ()->deleteOne (["_id " => $ this ->file ['_id ' ]]);
192
+ $ this ->isClosed = true ;
179
193
}
180
194
private function insertChunk ($ data )
181
195
{
196
+ if ($ this ->isClosed ){
197
+ return ;
198
+ }
182
199
$ toUpload = ["files_id " => $ this ->file ['_id ' ], "n " => $ this ->chunkOffset , "data " => new \MongoDB \BSON \Binary ($ data , \MongoDB \BSON \Binary::TYPE_GENERIC )];
183
200
hash_update ($ this ->ctx , $ data );
184
- $ this ->collectionsWrapper ->chunkInsert ($ toUpload );
201
+ try {
202
+ $ this ->collectionsWrapper ->chunkInsert ($ toUpload );
203
+ } catch (\MongoDB \Exception $ e ){
204
+ $ this ->abort ();
205
+ throw $ e ;
206
+ }
185
207
$ this ->length += strlen ($ data );
186
208
$ this ->chunkOffset ++;
187
209
}
188
-
189
210
private function fileCollectionInsert ()
190
211
{
212
+ if ($ this ->isClosed ){
213
+ return ;
214
+ }
191
215
$ md5 = hash_final ($ this ->ctx );
192
216
$ this ->file = array_merge ($ this ->file , ['length ' => $ this ->length , 'md5 ' => $ md5 ]);
193
- $ this ->collectionsWrapper ->fileInsert ($ this ->file );
217
+ try {
218
+ $ this ->collectionsWrapper ->fileInsert ($ this ->file );
219
+ } catch (\MongoDB \Exception $ e ){
220
+ $ this ->abort ();
221
+ throw $ e ;
222
+ }
194
223
return $ this ->file ['_id ' ];
195
224
}
196
225
//from: http://stackoverflow.com/questions/3656713/how-to-get-current-time-in-milliseconds-in-php
0 commit comments