<?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
     *
     * @param string $ext
     * @return string|null
     */
    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.
     *
     * @param string $filename
     * @return string|null
     */
    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
     * @param File $file
     * @return bool
     */
    public function isImage(File $file): bool
    {
        $mimetype = $file->getMimeType() ?: $this->guessMimeTypeFromFilename($file->getName());
        return boolval(preg_match('#^image#', $mimetype));
    }
}