FileUtils.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Utils;
  4. use App\Entity\Core\File;
  5. use Mimey\MimeTypes;
  6. class FileUtils
  7. {
  8. public function __construct()
  9. {
  10. }
  11. /**
  12. * Return the mimetype corresponding to the givent file extension.
  13. */
  14. public function getMimeTypeFromExt(string $ext): ?string
  15. {
  16. return (new MimeTypes())->getMimeType(ltrim($ext, '.'));
  17. }
  18. /**
  19. * Try to guess the mimetype from the filename.
  20. *
  21. * Return null if it did not manage to guess it.
  22. */
  23. public function guessMimeTypeFromFilename(string $filename): ?string
  24. {
  25. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  26. if (empty($ext)) {
  27. return null;
  28. }
  29. return self::getMimeTypeFromExt($ext);
  30. }
  31. /**
  32. * Test si le fichier passé en paramètre est une image.
  33. */
  34. public function isImage(File $file): bool
  35. {
  36. $mimetype = $file->getMimeType() ?: $this->guessMimeTypeFromFilename($file->getName());
  37. return boolval(preg_match('#^image#', $mimetype));
  38. }
  39. /**
  40. * Génère un nom de fichier temporaire situé dans le répertoire var/tmp,
  41. * avec l'extension et le préfixe donnés.
  42. *
  43. * @throws \RuntimeException
  44. */
  45. public function getTempFilename(string $ext = 'tmp', string $prefix = ''): string
  46. {
  47. if (empty($ext)) {
  48. throw new \RuntimeException('Extension can not be empty');
  49. }
  50. $tempDir = Path::getProjectDir().'/var/tmp';
  51. if (!is_dir($tempDir)) {
  52. mkdir($tempDir);
  53. }
  54. return $tempDir.'/'.$prefix.uniqid().'.'.$ext;
  55. }
  56. public function unlinkIfExist(string $path): void
  57. {
  58. if (file_exists($path)) {
  59. unlink($path);
  60. }
  61. }
  62. public function getFileContent(string $path): string
  63. {
  64. return file_get_contents($path);
  65. }
  66. /**
  67. * Recursively remove a directory
  68. *
  69. * @param string $path
  70. * @return void
  71. */
  72. public static function rrmDir(string $path): void
  73. {
  74. if (!is_dir($path)) {
  75. throw new \RuntimeException(sprintf('Path %s is not a directory', $path));
  76. }
  77. $files = glob($path.'/*');
  78. foreach ($files as $file) {
  79. is_dir($file) ? self::rrmDir($file) : unlink($file);
  80. }
  81. rmdir($path);
  82. }
  83. }