| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- declare(strict_types=1);
- namespace App\Service\Utils;
- use App\Entity\Core\File;
- use Mimey\MimeTypes;
- 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.
- *
- * @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;
- }
- public function unlinkIfExist(string $path): void
- {
- if (file_exists($path)) {
- unlink($path);
- }
- }
- public function getFileContent(string $path): string
- {
- return file_get_contents($path);
- }
- /**
- * Recursively remove a directory
- *
- * @param string $path
- * @return void
- */
- public static function rrmDir(string $path): void
- {
- if (!is_dir($path)) {
- throw new \RuntimeException(sprintf('Path %s is not a directory', $path));
- }
- $files = glob($path.'/*');
- foreach ($files as $file) {
- is_dir($file) ? self::rrmDir($file) : unlink($file);
- }
- rmdir($path);
- }
- }
|