| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- <?php
- declare(strict_types=1);
- namespace App\Service\Utils;
- use App\Entity\Core\File;
- use Exception;
- use Mimey\MimeTypes;
- use RuntimeException;
- class FileUtils
- {
- public function __construct()
- {
- }
- /**
- * Return the mimetype corresponding to the givent file extension.
- */
- public function getMimeTypeFromExt(string $ext): ?string
- {
- return (new MimeTypes())->getMimeType(ltrim($ext, '.'));
- }
- /**
- * Try to guess the mimetype from the filename.
- *
- * Return null if it did not manage to guess it.
- */
- public function guessMimeTypeFromFilename(string $filename): ?string
- {
- $ext = pathinfo($filename, PATHINFO_EXTENSION);
- if (empty($ext)) {
- return null;
- }
- return self::getMimeTypeFromExt($ext);
- }
- /**
- * Test si le fichier passé en paramètre est une image.
- */
- public function isImage(File $file): bool
- {
- $mimetype = $file->getMimeType() ?: $this->guessMimeTypeFromFilename($file->getName());
- return boolval(preg_match('#^image#', $mimetype));
- }
- /**
- * Génère un nom de fichier temporaire situé dans le répertoire var/tmp,
- * avec l'extension et le préfixe donnés.
- *
- * @param string $ext
- * @param string $prefix
- * @return string
- * @throws RuntimeException
- */
- public function getTempFilename(string $ext = 'tmp', string $prefix = ''): string
- {
- if (empty($ext)) {
- throw new RuntimeException('Extension can not be empty');
- }
- $tempDir = Path::getProjectDir() . '/var/tmp';
- if (!is_dir($tempDir)) {
- mkdir($tempDir);
- }
- return $tempDir . '/' . $prefix . uniqid() . '.' . $ext;
- }
- }
|