diff --git a/MD_STD.php b/MD_STD.php index 262721c..73ef091 100644 --- a/MD_STD.php +++ b/MD_STD.php @@ -378,4 +378,35 @@ final class MD_STD { } + /** + * Checks if a file exists, with one of the expected mime types. + * + * @param string $filepath File path of the file that needs to exist. + * @param string[] $accepted_mimetype Mime type the file should have. + * + * @return void + */ + public static function ensure_file(string $filepath, array $accepted_mimetype = []) { + + if (!\file_exists($filepath)) { + throw new MDFileDoesNotExist("File " . basename($filepath) . " does not exist"); + } + + // Check for mime type follows. If no check is to be done, ignore this. + if (empty($accepted_mimetype)) { + return; + } + + $finfo = \finfo_open(FILEINFO_MIME_TYPE); + if (!($mime_type = finfo_file($finfo, $filepath))) { + throw new MDWrongFileType("Cannot get mime type of file: " . basename($filepath)); + } + \finfo_close($finfo); + + if (!\in_array($mime_type, $accepted_mimetype)) { + throw new MDWrongFileType("Incorrect mime type of file " . \basename($filepath) . ". Mime type is " . \mime_content_type($filepath) . ", accepted any of ['" . \implode("', '", $accepted_mimetype) . "']"); + } + + } + }