-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileManager.php
757 lines (664 loc) · 24.8 KB
/
FileManager.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<?php
namespace Oro\Bundle\GaufretteBundle;
use Gaufrette\Adapter\MetadataSupporter;
use Gaufrette\Exception;
use Gaufrette\Exception\FileNotFound;
use Gaufrette\File;
use Gaufrette\Filesystem;
use Gaufrette\Stream;
use Gaufrette\Stream\Local as LocalStream;
use Gaufrette\StreamMode;
use Knp\Bundle\GaufretteBundle\FilesystemMap;
use Oro\Bundle\GaufretteBundle\Adapter\LocalAdapter;
use Oro\Bundle\GaufretteBundle\Exception\FlushFailedException;
use Oro\Bundle\GaufretteBundle\Exception\ProtocolConfigurationException;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\HttpFoundation\File\File as ComponentFile;
/**
* This manager can be used to simplify retrieving and storing files
* via Gaufrette filesystem abstraction layer.
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class FileManager
{
/** The number of bytes to be read from a source stream at a time */
protected const READ_BATCH_SIZE = 100000;
private const DIRECTORY_SEPARATOR = '/';
/** @var array */
private $tmpFiles = [];
/** @var bool */
private $clearTempFilesCallbackRegistered = false;
/** @var Filesystem */
private $filesystem;
/** @var string */
private $filesystemName;
/** @var string|null */
private $subDirectory;
/** @var bool */
private $useSubDirectory = false;
/** @var string */
private $protocol;
/** @var string */
private $readonlyProtocol;
/**
* @param string $filesystemName The name of Gaufrette filesystem this manager works with
* @param string|null $subDirectory The name of a sub-directory if it is different than the filesystem name
*/
public function __construct(string $filesystemName, string $subDirectory = null)
{
if (!$filesystemName) {
throw new \InvalidArgumentException('The filesystem name must not be empty.');
}
$this->filesystemName = $filesystemName;
if ($subDirectory) {
$this->subDirectory = $subDirectory;
$this->useSubDirectory = true;
}
}
public function __destruct()
{
$this->clearTempFiles();
}
public function clearTempFiles()
{
foreach (array_keys($this->tmpFiles) as $tmpFile) {
@unlink($tmpFile);
}
$this->tmpFiles = [];
}
private function rememberTempFile(string $file)
{
if (!$this->clearTempFilesCallbackRegistered) {
// In case of unexpected exit(); call or maximum execution time reaching temp files should be removed
register_shutdown_function([$this, 'clearTempFiles']);
$this->clearTempFilesCallbackRegistered = true;
}
$this->tmpFiles[$file] = true;
}
/**
* Sets a flag indicates whether files should be stored in a sub-directory.
*/
public function useSubDirectory(bool $useSubDirectory): void
{
if (!$useSubDirectory && $this->subDirectory) {
throw new \LogicException('The Gaufrette file manager must be configured without a sub-directory.');
}
$this->useSubDirectory = $useSubDirectory;
}
/**
* Sets an object contains references to all declared Gaufrette filesystems.
*/
public function setFilesystemMap(FilesystemMap $filesystemMap): void
{
$this->filesystem = $filesystemMap->get($this->filesystemName);
}
/**
* Sets the name of the protocol mapped to the Gaufrette stream wrapper.
*/
public function setProtocol(string $protocol): void
{
$this->protocol = $protocol;
}
/**
* Sets the name of the read-only protocol mapped to the Gaufrette stream wrapper.
*/
public function setReadonlyProtocol(string $protocol): void
{
$this->readonlyProtocol = $protocol;
}
/**
* Gets the name of the protocol mapped to the Gaufrette stream wrapper.
*/
public function getProtocol(): string
{
return $this->protocol;
}
/**
* Gets the name of the read-only protocol mapped to the Gaufrette stream wrapper.
*/
public function getReadonlyProtocol(): string
{
return $this->readonlyProtocol;
}
public function getSubDirectory(): ?string
{
if (!$this->useSubDirectory) {
return null;
}
return $this->subDirectory ?? $this->filesystemName;
}
/**
* Gets the full path to a file in the Gaufrette file system.
* This path can be used in the native file functions like "copy", "unlink", etc.
*
* @throws ProtocolConfigurationException if the Gaufrette protocol is not configured
*/
public function getFilePath(string $fileName): string
{
if (!$this->protocol) {
throw new ProtocolConfigurationException();
}
return $this->protocol . '://' . $this->getFilePathWithoutProtocol($fileName);
}
/**
* Gets the full path to a file in the read-only Gaufrette file system.
* This path can be used in the native file functions that need a read-only access to a file.
*
* @throws ProtocolConfigurationException if the Gaufrette protocol is not configured
*/
public function getReadonlyFilePath(string $fileName): string
{
if (!$this->readonlyProtocol) {
throw new ProtocolConfigurationException();
}
return $this->readonlyProtocol . '://' . $this->getFilePathWithoutProtocol($fileName);
}
/**
* Gets the full path to a file in the Gaufrette file system but without the protocol part.
* For example, if a full path is "gaufrette://my_filesystem/file.txt",
* the full full path the protocol part is "my_filesystem/file.txt".
*/
public function getFilePathWithoutProtocol(string $fileName): string
{
return
$this->filesystemName
. self::DIRECTORY_SEPARATOR
. $this->getFileNameWithSubDirectory($fileName);
}
/**
* Returns a human readable representation of a Gaufrette adapter used by this file manager:
* * for Local adapter the full path to the directory will be returned.
* * for other adapters the name of the adapter will be returned.
*/
public function getAdapterDescription(): string
{
$directory = $this->getLocalPath();
if (null !== $directory) {
return $directory;
}
$adapter = $this->filesystem->getAdapter();
$className = \get_class($adapter);
$lastSeparatorPos = strrpos($className, '\\');
if (false !== $lastSeparatorPos) {
$className = substr($className, $lastSeparatorPos + 1);
}
return $className;
}
/**
* Returns the full path to the directory for Local adapter.
*/
public function getLocalPath(): ?string
{
$adapter = $this->filesystem->getAdapter();
if (!$adapter instanceof LocalAdapter) {
return null;
}
$directory = $adapter->getDirectory();
$subDirectory = $this->getSubDirectory();
if ($subDirectory) {
$directory .= DIRECTORY_SEPARATOR . $subDirectory;
}
return $directory;
}
/**
* Gets the MIME type of a file in the Gaufrette file system.
*
* @param string $fileName
*
* @return string|null The MIME type or NULL if the Gaufrette file system does not support MIME types
* or cannot recognize MIME type
*
* @throws FileNotFound if the file does not exist
*/
public function getFileMimeType(string $fileName): ?string
{
if (!$fileName) {
return null;
}
try {
return $this->filesystem->mimeType($this->getFileNameWithSubDirectory($fileName)) ?: null;
} catch (\LogicException $e) {
// the Gaufrette filesystem adapter does support MIME types
return null;
}
}
/**
* Finds files that name beginning with the given prefix.
*
* @param string $prefix
*
* @return string[] The names of the found files
*/
public function findFiles(string $prefix = ''): array
{
$fileNames = $this->listKeys($this->getFileNameWithSubDirectory($prefix))['keys'];
if ($fileNames && $this->getSubDirectory()) {
$fileNamesWithoutSubDirectory = [];
foreach ($fileNames as $fileName) {
$fileNamesWithoutSubDirectory[] = $this->getFileNameWithoutSubDirectory($fileName);
}
$fileNames = $fileNamesWithoutSubDirectory;
}
return $fileNames;
}
/**
* Checks if the given file exists in the Gaufrette file system.
*/
public function hasFile(string $fileName): bool
{
if (!$fileName) {
return false;
}
return $this->filesystem->has($this->getFileNameWithSubDirectory($fileName));
}
/**
* Returns a File object for the file stored in the Gaufrette file system.
*
* @param string $fileName
* @param bool $throwException Whether to throw an exception in case the file does not exists
* in the Gaufrette file system
*
* @return File|null
*
* @throws FileNotFound if the file does not exist and throw exception is requested
*/
public function getFile(string $fileName, bool $throwException = true): ?File
{
if (!$fileName) {
return null;
}
$file = null;
$fileName = $this->getFileNameWithSubDirectory($fileName);
if ($throwException || $this->filesystem->has($fileName)) {
$file = $this->filesystem->get($fileName);
$file->setName($this->getFileNameWithoutSubDirectory($file->getName()));
}
return $file;
}
/**
* Returns a File stream for the file stored in the Gaufrette file system.
*
* @param string $fileName The file name
* @param bool $throwException Whether to throw an exception in case the file does not exists
*
* @return Stream|null
*
* @throws FileNotFound if the file does not exist and throw exception is requested
*/
public function getStream(string $fileName, bool $throwException = true): ?Stream
{
if (!$fileName) {
return null;
}
$fileName = $this->getFileNameWithSubDirectory($fileName);
$hasFile = $this->filesystem->has($fileName);
if (!$hasFile && $throwException) {
throw new Exception\FileNotFound($fileName);
}
return $hasFile
? $this->filesystem->createStream($fileName)
: null;
}
/**
* Returns the content of a file stored in the Gaufrette file system.
*
* @param string $fileName
* @param bool $throwException Whether to throw exception in case the file does not exist
* in the Gaufrette file system
*
* @return string|null
*
* @throws FileNotFound if the file does not exist and throw exception is requested
* @throws \RuntimeException if the file cannot be read
*/
public function getFileContent(string $fileName, bool $throwException = true): ?string
{
$content = null;
$file = $this->getFile($fileName, $throwException);
if (null !== $file) {
$content = $file->getContent();
}
return $content;
}
/**
* Deletes the given file from the Gaufrette file system if it exists.
*
* @throws \RuntimeException if the file cannot be deleted
*/
public function deleteFile(string $fileName): void
{
if (!$fileName) {
return;
}
// delete temp file created by file manager
if (\in_array($fileName, $this->tmpFiles, true)) {
unset($this->tmpFiles[$fileName]);
@unlink($fileName);
return;
}
$realFileName = $this->getFileNameWithSubDirectory($fileName);
if ($this->filesystem->has($realFileName) && !$this->filesystem->isDirectory($realFileName)) {
$this->filesystem->delete($realFileName);
// delete all parent directories that do not contain any files or sub-directories
$dirName = $this->getDirectoryName($fileName);
while ($dirName) {
$realDirName = $this->getFileNameWithSubDirectory($dirName);
if ($this->filesystem->isDirectory($realDirName) && $this->isDirectoryEmpty($realDirName)) {
$this->deleteDirectory($realDirName);
$dirName = $this->getDirectoryName($dirName);
} else {
break;
}
}
}
}
/**
* Deletes all files that name beginning with the given prefix from the Gaufrette file system.
*
* @throws \RuntimeException if any file cannot be deleted
*/
public function deleteAllFiles(string $prefix = ''): void
{
$hasTailingDirectorySeparator = self::endsWithDirectorySeparator($prefix);
if ($hasTailingDirectorySeparator) {
$prefix = rtrim($prefix, self::DIRECTORY_SEPARATOR) . self::DIRECTORY_SEPARATOR;
}
$realDirName = $this->getFileNameWithSubDirectory($prefix);
$listResult = $this->listKeys($realDirName);
if (empty($listResult['keys']) && empty($listResult['dirs'])) {
return;
}
foreach ($listResult['keys'] as $fileName) {
$this->filesystem->delete($fileName);
}
foreach ($listResult['dirs'] as $dirName) {
$this->deleteDirectory($dirName);
}
if ($hasTailingDirectorySeparator) {
$dirName = substr($prefix, 0, -\strlen(self::DIRECTORY_SEPARATOR));
if ($dirName) {
$dirName = $this->getFileNameWithSubDirectory($dirName);
if ($this->filesystem->isDirectory($dirName)) {
$this->deleteDirectory($dirName);
}
}
}
}
/**
* Writes the specified data to the Gaufrette file system.
*
* @throws FlushFailedException if an error occurred during the flushing data to the destination stream
* @throws \RuntimeException if the destination stream cannot be opened
* @throws \LogicException if the source stream does not allow read or the destination stream does not allow write
* @throws \InvalidArgumentException if the file name is empty string
*/
public function writeToStorage(string $content, string $fileName): void
{
if (!$fileName) {
throw new \InvalidArgumentException('The file name must not be empty.');
}
$fileName = $this->getFileNameWithSubDirectory($fileName);
$dstStream = $this->filesystem->createStream($fileName);
$dstStream->open(new StreamMode('wb+'));
try {
$dstStream->write($content);
} finally {
$this->filesystem->removeFromRegister($fileName);
$this->flushAndClose($dstStream, $fileName);
}
}
/**
* Copies a file from local filesystem to the Gaufrette file system.
*
* @throws FlushFailedException if an error occurred during the flushing data to the destination stream
* @throws \RuntimeException if the destination stream cannot be opened
* @throws \LogicException if the source stream does not allow read or the destination stream does not allow write
* @throws \InvalidArgumentException if the local file path or the file name are empty string
*/
public function writeFileToStorage(string $localFilePath, string $fileName): void
{
if (!$localFilePath) {
throw new \InvalidArgumentException('The local path must not be empty.');
}
if (!$fileName) {
throw new \InvalidArgumentException('The file name must not be empty.');
}
$this->writeStreamToStorage(new LocalStream($localFilePath), $fileName);
}
/**
* Writes a stream to the Gaufrette file system.
*
* @param Stream $srcStream
* @param string $fileName
* @param bool $avoidWriteEmptyStream
*
* @return bool returns false in case if $avoidWriteEmptyStream = true and input stream is empty.
*
* @throws FlushFailedException if an error occurred during the flushing data to the destination stream
* @throws \RuntimeException if the destination stream cannot be opened
* @throws \LogicException if the source stream does not allow read or the destination stream does not allow write
* @throws \InvalidArgumentException if the local file path of the file name is empty string
*/
public function writeStreamToStorage(Stream $srcStream, string $fileName, bool $avoidWriteEmptyStream = false): bool
{
if (!$fileName) {
throw new \InvalidArgumentException('The file name must not be empty.');
}
$fileName = $this->getFileNameWithSubDirectory($fileName);
$srcStream->open(new StreamMode('rb'));
$nonEmptyStream = true;
$firstChunk = '';
try {
if ($avoidWriteEmptyStream) {
// check if input stream is empty
$firstChunk = $srcStream->read(static::READ_BATCH_SIZE);
if ($firstChunk === '' && $srcStream->eof()) {
$nonEmptyStream = false;
}
}
if ($nonEmptyStream) {
$dstStream = $this->filesystem->createStream($fileName);
$dstStream->open(new StreamMode('wb+'));
try {
// save the chunk that was used to check if input stream is empty
if ($firstChunk) {
$dstStream->write($firstChunk);
$firstChunk = null;
}
while (!$srcStream->eof()) {
$dstStream->write($srcStream->read(static::READ_BATCH_SIZE));
}
} finally {
$this->filesystem->removeFromRegister($fileName);
$this->flushAndClose($dstStream, $fileName);
}
}
} finally {
$srcStream->close();
}
return $nonEmptyStream;
}
/**
* Creates a file in a temporary directory and writes the given content to it.
*
* @param string $content
* @param string|null $originalFileName
*
* @return ComponentFile The created temporary file
*
* @throws IOException if a temporary file cannot be created
*/
public function writeToTemporaryFile(string $content, string $originalFileName = null): ComponentFile
{
$tmpFileName = $this->getTemporaryFileName($originalFileName);
if (false === @file_put_contents($tmpFileName, $content)) {
throw new IOException(sprintf('Failed to write file "%s".', $tmpFileName), 0, null, $tmpFileName);
}
$this->rememberTempFile($tmpFileName);
return new ComponentFile($tmpFileName, false);
}
/**
* Creates a file in a temporary directory and writes the given stream to it.
*
* @param Stream $srcStream
* @param string|null $originalFileName
*
* @return ComponentFile The created temporary file
*
* @throws FlushFailedException if an error occurred during the flushing data to the destination stream
* @throws \RuntimeException if the destination stream cannot be opened
* @throws \LogicException if the source stream does not allow read or the destination stream does not allow write
*/
public function writeStreamToTemporaryFile(Stream $srcStream, string $originalFileName = null): ComponentFile
{
$tmpFileName = $this->getTemporaryFileName($originalFileName);
$srcStream->open(new StreamMode('rb'));
try {
$dstStream = new LocalStream($tmpFileName);
$dstStream->open(new StreamMode('wb+'));
try {
while (!$srcStream->eof()) {
$dstStream->write($srcStream->read(static::READ_BATCH_SIZE));
}
} finally {
$this->flushAndClose($dstStream, $tmpFileName);
}
} finally {
$srcStream->close();
}
$this->rememberTempFile($tmpFileName);
return new ComponentFile($tmpFileName, false);
}
/**
* Returns the full path to a new file in a temporary directory.
*
* @param string|null $suggestedFileName
*
* @return string The full path to a temporary file
*/
public function getTemporaryFileName(string $suggestedFileName = null): string
{
$tmpDir = ini_get('upload_tmp_dir');
if (!$tmpDir || !is_dir($tmpDir) || !is_writable($tmpDir)) {
$tmpDir = sys_get_temp_dir();
}
$tmpDir = realpath($tmpDir);
if (DIRECTORY_SEPARATOR !== substr($tmpDir, -\strlen(DIRECTORY_SEPARATOR))) {
$tmpDir .= DIRECTORY_SEPARATOR;
}
$extension = null;
if ($suggestedFileName) {
$extension = pathinfo($suggestedFileName, PATHINFO_EXTENSION);
}
$tmpFile = $tmpDir . ($suggestedFileName ?: $this->generateFileName($extension));
while (file_exists($tmpFile)) {
$tmpFile = $tmpDir . $this->generateFileName($extension);
}
return $tmpFile;
}
/**
* Generates unique file name with the given extension.
*/
protected function generateFileName(string $extension = null): string
{
$fileName = str_replace('.', '', uniqid('', true));
if ($extension) {
$fileName .= '.' . $extension;
}
return $fileName;
}
/**
* @throws FlushFailedException if an error occurred during the flushing data to the stream
*/
protected function flushAndClose(Stream $stream, string $fileName): void
{
$success = $stream->flush();
$stream->close();
if (!$success) {
throw new FlushFailedException(sprintf(
'Failed to flush data to the "%s" file.',
$fileName
));
}
}
/**
* Sets a metadata for a file is stored in the Gaufrette file system.
*/
protected function setFileMetadata(string $fileName, array $content): void
{
$adapter = $this->filesystem->getAdapter();
if ($adapter instanceof MetadataSupporter) {
$adapter->setMetadata($this->getFileNameWithSubDirectory($fileName), $content);
}
}
/**
* @param string $prefix
*
* @return array ['keys' => [file key, ...], 'dirs' => [dir key, ...]]
*/
private function listKeys(string $prefix): array
{
$result = $this->filesystem->listKeys($prefix);
$hasDirs = \array_key_exists('dirs', $result);
if (\array_key_exists('keys', $result)) {
if (!$hasDirs) {
$result['dirs'] = [];
}
} elseif ($hasDirs) {
$result['keys'] = [];
} else {
$result = ['keys' => $result, 'dirs' => []];
}
return $result;
}
/**
* Checks if the given directory does not contain any files and sub-directories.
*/
private function isDirectoryEmpty(string $realDirName): bool
{
$listResult = $this->listKeys($realDirName . self::DIRECTORY_SEPARATOR);
return empty($listResult['keys']) && empty($listResult['dirs']);
}
/**
* Deletes a directory from the Gaufrette file system.
*/
private function deleteDirectory(string $realDirName): void
{
// use the adapter due to Filesystem::delete() is able to delete files only
$this->filesystem->getAdapter()->delete($realDirName);
}
/**
* Gets a directory where the given file is located.
*/
private function getDirectoryName(string $fileName): string
{
$normalizedFileName = ltrim($fileName, self::DIRECTORY_SEPARATOR);
$lastPos = strrpos($normalizedFileName, self::DIRECTORY_SEPARATOR);
return false !== $lastPos
? substr($normalizedFileName, 0, $lastPos)
: '';
}
private function getFileNameWithSubDirectory(string $fileName): string
{
$result = ltrim($fileName, self::DIRECTORY_SEPARATOR);
$subDirectory = $this->getSubDirectory();
if ($subDirectory) {
$result = $subDirectory . self::DIRECTORY_SEPARATOR . $result;
}
return $result;
}
private function getFileNameWithoutSubDirectory(string $fileName): string
{
$subDirectory = $this->getSubDirectory();
if ($subDirectory) {
return substr($fileName, \strlen($subDirectory) + 1);
}
return $fileName;
}
private static function endsWithDirectorySeparator(string $path): bool
{
return substr($path, -\strlen(self::DIRECTORY_SEPARATOR)) === self::DIRECTORY_SEPARATOR;
}
}