-
Notifications
You must be signed in to change notification settings - Fork 12
/
GridFSAdapter.php
446 lines (380 loc) · 15.3 KB
/
GridFSAdapter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<?php
declare(strict_types=1);
namespace League\Flysystem\GridFS;
use League\Flysystem\Config;
use League\Flysystem\DirectoryAttributes;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\PathPrefixer;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToCreateDirectory;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\UnableToWriteFile;
use League\MimeTypeDetection\FinfoMimeTypeDetector;
use League\MimeTypeDetection\MimeTypeDetector;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Driver\Exception\Exception;
use MongoDB\GridFS\Bucket;
use MongoDB\GridFS\Exception\FileNotFoundException;
/**
* @phpstan-type GridFile array{_id:ObjectId, length:int, chunkSize:int, uploadDate:UTCDateTime, filename:string, metadata?:array{contentType?:string, flysystem_visibility?:string}}
*/
class GridFSAdapter implements FilesystemAdapter
{
private const METADATA_DIRECTORY = 'flysystem_directory';
private const METADATA_VISIBILITY = 'flysystem_visibility';
private const METADATA_MIMETYPE = 'contentType';
private const TYPEMAP_ARRAY = [
'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'],
'codec' => null,
];
private Bucket $bucket;
private PathPrefixer $prefixer;
private MimeTypeDetector $mimeTypeDetector;
public function __construct(
Bucket $bucket,
string $prefix = '',
?MimeTypeDetector $mimeTypeDetector = null,
) {
$this->bucket = $bucket;
$this->prefixer = new PathPrefixer($prefix);
$this->mimeTypeDetector = $mimeTypeDetector ?? new FinfoMimeTypeDetector();
}
public function fileExists(string $path): bool
{
$file = $this->findFile($path);
return $file !== null;
}
public function directoryExists(string $path): bool
{
// A directory exists if at least one file exists with a path starting with the directory name
$files = $this->listContents($path, true);
foreach ($files as $file) {
return true;
}
return false;
}
public function write(string $path, string $contents, Config $config): void
{
if (str_ends_with($path, '/')) {
throw UnableToWriteFile::atLocation($path, 'file path cannot end with a slash');
}
$filename = $this->prefixer->prefixPath($path);
$options = [
'metadata' => $config->get('metadata', []),
];
if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
$options['metadata'][self::METADATA_VISIBILITY] = $visibility;
}
if (($mimeType = $config->get('mimetype')) || ($mimeType = $this->mimeTypeDetector->detectMimeType($path, $contents))) {
$options['metadata'][self::METADATA_MIMETYPE] = $mimeType;
}
try {
$stream = $this->bucket->openUploadStream($filename, $options);
fwrite($stream, $contents);
fclose($stream);
} catch (Exception $exception) {
throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception);
}
}
public function writeStream(string $path, $contents, Config $config): void
{
if (str_ends_with($path, '/')) {
throw UnableToWriteFile::atLocation($path, 'file path cannot end with a slash');
}
$filename = $this->prefixer->prefixPath($path);
$options = [];
if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
$options['metadata'][self::METADATA_VISIBILITY] = $visibility;
}
if (($mimetype = $config->get('mimetype')) || ($mimetype = $this->mimeTypeDetector->detectMimeTypeFromPath($path))) {
$options['metadata'][self::METADATA_MIMETYPE] = $mimetype;
}
try {
$this->bucket->uploadFromStream($filename, $contents, $options);
} catch (Exception $exception) {
throw UnableToWriteFile::atLocation($path, $exception->getMessage(), $exception);
}
}
public function read(string $path): string
{
$stream = $this->readStream($path);
try {
return stream_get_contents($stream);
} finally {
fclose($stream);
}
}
public function readStream(string $path)
{
if (str_ends_with($path, '/')) {
throw UnableToReadFile::fromLocation($path, 'file path cannot end with a slash');
}
try {
$filename = $this->prefixer->prefixPath($path);
return $this->bucket->openDownloadStreamByName($filename);
} catch (FileNotFoundException $exception) {
throw UnableToReadFile::fromLocation($path, 'file does not exist', $exception);
} catch (Exception $exception) {
throw UnableToReadFile::fromLocation($path, $exception->getMessage(), $exception);
}
}
/**
* Delete all revisions of the file name, starting with the oldest,
* no-op if the file does not exist.
*
* @throws UnableToDeleteFile
*/
public function delete(string $path): void
{
if (str_ends_with($path, '/')) {
throw UnableToDeleteFile::atLocation($path, 'file path cannot end with a slash');
}
$filename = $this->prefixer->prefixPath($path);
try {
$this->findAndDelete(['filename' => $filename]);
} catch (Exception $exception) {
throw UnableToDeleteFile::atLocation($path, $exception->getMessage(), $exception);
}
}
public function deleteDirectory(string $path): void
{
$prefixedPath = $this->prefixer->prefixDirectoryPath($path);
try {
$this->findAndDelete(['filename' => new Regex('^' . preg_quote($prefixedPath))]);
} catch (Exception $exception) {
throw UnableToDeleteDirectory::atLocation($path, $exception->getMessage(), $exception);
}
}
public function createDirectory(string $path, Config $config): void
{
$dirname = $this->prefixer->prefixDirectoryPath($path);
$options = [
'metadata' => $config->get('metadata', []) + [self::METADATA_DIRECTORY => true],
];
if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
$options['metadata'][self::METADATA_VISIBILITY] = $visibility;
}
try {
$stream = $this->bucket->openUploadStream($dirname, $options);
fwrite($stream, '');
fclose($stream);
} catch (Exception $exception) {
throw UnableToCreateDirectory::atLocation($path, $exception->getMessage(), $exception);
}
}
public function setVisibility(string $path, string $visibility): void
{
$file = $this->findFile($path);
if ($file === null) {
throw UnableToSetVisibility::atLocation($path, 'file does not exist');
}
try {
$this->bucket->getFilesCollection()->updateOne(
['_id' => $file['_id']],
['$set' => ['metadata.' . self::METADATA_VISIBILITY => $visibility]],
);
} catch (Exception $exception) {
throw UnableToSetVisibility::atLocation($path, $exception->getMessage(), $exception);
}
}
public function visibility(string $path): FileAttributes
{
$file = $this->findFile($path);
if ($file === null) {
throw UnableToRetrieveMetadata::mimeType($path, 'file does not exist');
}
return $this->mapFileAttributes($file);
}
public function fileSize(string $path): FileAttributes
{
if (str_ends_with($path, '/')) {
throw UnableToRetrieveMetadata::fileSize($path, 'file path cannot end with a slash');
}
$file = $this->findFile($path);
if ($file === null) {
throw UnableToRetrieveMetadata::fileSize($path, 'file does not exist');
}
return $this->mapFileAttributes($file);
}
public function mimeType(string $path): FileAttributes
{
if (str_ends_with($path, '/')) {
throw UnableToRetrieveMetadata::mimeType($path, 'file path cannot end with a slash');
}
$file = $this->findFile($path);
if ($file === null) {
throw UnableToRetrieveMetadata::mimeType($path, 'file does not exist');
}
$attributes = $this->mapFileAttributes($file);
if ($attributes->mimeType() === null) {
throw UnableToRetrieveMetadata::mimeType($path, 'unknown');
}
return $attributes;
}
public function lastModified(string $path): FileAttributes
{
if (str_ends_with($path, '/')) {
throw UnableToRetrieveMetadata::lastModified($path, 'file path cannot end with a slash');
}
$file = $this->findFile($path);
if ($file === null) {
throw UnableToRetrieveMetadata::lastModified($path, 'file does not exist');
}
return $this->mapFileAttributes($file);
}
public function listContents(string $path, bool $deep): iterable
{
$path = $this->prefixer->prefixDirectoryPath($path);
$pathdeep = 0;
// Get the last revision of each file, using the index on the files collection
$pipeline = [['$sort' => ['filename' => 1, 'uploadDate' => 1]]];
if ($path !== '') {
$pathdeep = substr_count($path, '/');
// Exclude files that do not start with the expected path
$pipeline[] = ['$match' => ['filename' => new Regex('^' . preg_quote($path))]];
}
if ($deep === false) {
$pipeline[] = ['$addFields' => ['splitpath' => ['$split' => ['$filename', '/']]]];
$pipeline[] = ['$group' => [
// The same name could be used as a filename and as part of the path of other files
'_id' => [
'basename' => ['$arrayElemAt' => ['$splitpath', $pathdeep]],
'isDir' => ['$ne' => [['$size' => '$splitpath'], $pathdeep + 1]],
],
// Get the metadata of the last revision of each file
'file' => ['$last' => '$$ROOT'],
// The "lastModified" date is the date of the last uploaded file in the directory
'uploadDate' => ['$max' => '$uploadDate'],
]];
$files = $this->bucket->getFilesCollection()->aggregate($pipeline, self::TYPEMAP_ARRAY);
foreach ($files as $file) {
if ($file['_id']['isDir']) {
yield new DirectoryAttributes(
$this->prefixer->stripDirectoryPrefix($path . $file['_id']['basename']),
null,
$file['uploadDate']->toDateTime()->getTimestamp(),
);
} else {
yield $this->mapFileAttributes($file['file']);
}
}
} else {
// Get the metadata of the last revision of each file
$pipeline[] = ['$group' => [
'_id' => '$filename',
'file' => ['$first' => '$$ROOT'],
]];
$files = $this->bucket->getFilesCollection()->aggregate($pipeline, self::TYPEMAP_ARRAY);
foreach ($files as $file) {
$file = $file['file'];
if (str_ends_with($file['filename'], '/')) {
// Empty files with a trailing slash are markers for directories, only for Flysystem
yield new DirectoryAttributes(
$this->prefixer->stripDirectoryPrefix($file['filename']),
$file['metadata'][self::METADATA_VISIBILITY] ?? null,
$file['uploadDate']->toDateTime()->getTimestamp(),
$file,
);
} else {
yield $this->mapFileAttributes($file);
}
}
}
}
public function move(string $source, string $destination, Config $config): void
{
if ($source === $destination) {
return;
}
if ($this->fileExists($destination)) {
$this->delete($destination);
}
try {
$result = $this->bucket->getFilesCollection()->updateMany(
['filename' => $this->prefixer->prefixPath($source)],
['$set' => ['filename' => $this->prefixer->prefixPath($destination)]],
);
if ($result->getModifiedCount() === 0) {
throw UnableToMoveFile::because('file does not exist', $source, $destination);
}
} catch (Exception $exception) {
throw UnableToMoveFile::fromLocationTo($source, $destination, $exception);
}
}
public function copy(string $source, string $destination, Config $config): void
{
$file = $this->findFile($source);
if ($file === null) {
throw UnableToCopyFile::fromLocationTo(
$source,
$destination,
);
}
$options = [];
if (($visibility = $config->get(Config::OPTION_VISIBILITY)) || $visibility = $file['metadata'][self::METADATA_VISIBILITY] ?? null) {
$options['metadata'][self::METADATA_VISIBILITY] = $visibility;
}
if (($mimetype = $config->get('mimetype')) || $mimetype = $file['metadata'][self::METADATA_MIMETYPE] ?? null) {
$options['metadata'][self::METADATA_MIMETYPE] = $mimetype;
}
try {
$stream = $this->bucket->openDownloadStream($file['_id']);
$this->bucket->uploadFromStream($this->prefixer->prefixPath($destination), $stream, $options);
} catch (Exception $exception) {
throw UnableToCopyFile::fromLocationTo($source, $destination, $exception);
}
}
/**
* Get the last revision of the file name.
*
* @return GridFile|null
*/
private function findFile(string $path): ?array
{
$filename = $this->prefixer->prefixPath($path);
$files = $this->bucket->find(
['filename' => $filename],
['sort' => ['uploadDate' => -1], 'limit' => 1] + self::TYPEMAP_ARRAY,
);
return $files->toArray()[0] ?? null;
}
/**
* @param GridFile $file
*/
private function mapFileAttributes(array $file): FileAttributes
{
return new FileAttributes(
$this->prefixer->stripPrefix($file['filename']),
$file['length'],
$file['metadata'][self::METADATA_VISIBILITY] ?? null,
$file['uploadDate']->toDateTime()->getTimestamp(),
$file['metadata'][self::METADATA_MIMETYPE] ?? null,
$file,
);
}
/**
* @throws Exception
*/
private function findAndDelete(array $filter): void
{
$files = $this->bucket->find(
$filter,
['sort' => ['uploadDate' => 1], 'projection' => ['_id' => 1]] + self::TYPEMAP_ARRAY,
);
foreach ($files as $file) {
try {
$this->bucket->delete($file['_id']);
} catch (FileNotFoundException) {
// Ignore error due to race condition
}
}
}
}