Add a function to ensure a file exists, optionally checking the mime

type
This commit is contained in:
Joshua Ramon Enslin 2020-11-08 00:12:02 +01:00 committed by Stefan Rohde-Enslin
parent 2f68acdfc1
commit 1c86051997
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

View File

@ -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) . "']");
}
}
} }