FileUtils.php 1.7 KB

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