<?php

namespace AutoAdmin\Bundle\Core\Upload;

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

class FileVerifier
{
    public function verify($file): void
    {
        if ($file instanceof File) {
            $extension = $this->getFilenameExtension($file);
            if (
                // linux file ?
                empty($extension)
                // forbid php
                || trim($extension) === 'php'
                // mime coherence
                || $extension != $file->guessExtension()
            ) {
                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);
        $extension = $splFile->getExtension();

        return $extension;
    }
}
