From 50d3a20b01d3c7d53bfe1e37181e41ad0bd98df3 Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Sun, 8 Nov 2020 18:54:40 +0100 Subject: [PATCH] Add type-safe drop-in replacement for mime_content_type() --- MD_STD.php | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/MD_STD.php b/MD_STD.php index 2438ed8..fe93d44 100644 --- a/MD_STD.php +++ b/MD_STD.php @@ -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) . "']");