Add type-safe drop-in replacement for mime_content_type()

This commit is contained in:
Joshua Ramon Enslin 2020-11-08 18:54:40 +01:00 committed by Stefan Rohde-Enslin
parent cb8c786284
commit 50d3a20b01
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

View File

@ -378,6 +378,27 @@ final class MD_STD {
}
/**
* Wrapper around the finfo functions to get the mime content type of a file.
*
* @param string $filepath Expected file path.
*
* @return string
*/
public static function mime_content_type(string $filepath):string {
if (!($finfo = \finfo_open(FILEINFO_MIME_TYPE))) {
throw new Exception("Cannot open finfo context");
}
if (!($mime_type = finfo_file($finfo, $filepath))) {
throw new MDWrongFileType("Cannot get mime type of file: " . basename($filepath));
}
\finfo_close($finfo);
return $mime_type;
}
/**
* Checks if a file exists, with one of the expected mime types.
*
@ -397,13 +418,7 @@ final class MD_STD {
return;
}
if (!($finfo = \finfo_open(FILEINFO_MIME_TYPE))) {
throw new Exception("Cannot open finfo context");
}
if (!($mime_type = finfo_file($finfo, $filepath))) {
throw new MDWrongFileType("Cannot get mime type of file: " . basename($filepath));
}
\finfo_close($finfo);
$mime_type = self::mime_content_type($filepath);
if (!\in_array($mime_type, $accepted_mimetype, true)) {
throw new MDWrongFileType("Incorrect mime type of file " . \basename($filepath) . ". Mime type is " . \mime_content_type($filepath) . ", accepted any of ['" . \implode("', '", $accepted_mimetype) . "']");