<?php

namespace AutoAdmin\Bundle\Core\Upload;

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\MimeTypes;

class FileVerifier
{
    public function verify($file): void
    {
        if ($file instanceof File) {
            $extension = $this->getFilenameExtension($file);
            $mimeExtensions = MimeTypes::getDefault()->getExtensions($file->getMimeType()) ?? [];

            if (
                // linux file ?
                empty($extension)
                // forbid php
                || trim($extension) === 'php'
                // mime coherence
                || !in_array(strtolower($extension), $mimeExtensions)
            ) {
                throw new \RuntimeException('Improper file.');
            }
        }
    }

    protected function getFilenameExtension(File $file): string
    {
        if ($file instanceof UploadedFile) {
            $filename = $file->getClientOriginalName();
        } else {
            $filename = $file->getFilename();
        }

        $splFile = new \SplFileInfo($filename);
        return $splFile->getExtension();
    }
}
