Skip to content

Instantly share code, notes, and snippets.

@meniam
Last active May 15, 2021 13:24
Show Gist options
  • Save meniam/12f8c9c788969daa5c8fdfad97d9a9cc to your computer and use it in GitHub Desktop.
Save meniam/12f8c9c788969daa5c8fdfad97d9a9cc to your computer and use it in GitHub Desktop.
Convert /etc/mime.types to nginx MIME types Format
<?php
$shortopts = "m:";
$shortopts .= "o::";
$shortopts .= "i::";
$shortopts .= "f::";
$options = getopt($shortopts);
if (!$options) {
echo "Usage:\n\n";
echo "php $0 -m=<source mime file> -o=<nginx mime>\n\n";
exit;
}
$isFilterWithoutExt = isset($options['f']);
if (!$lines = array_filter(array_map('trim',file($options['m'])))) {
echo "Source File Does Not Contain Mime Types";
}
$ignoredMime = [];
$ignoredMimeBase = [];
$ignored = [];
if (isset($options['i']) && ($ignored = array_filter(array_map('trim', explode(',', $options['i']))))) {
foreach ($ignored as $ignore) {
if (substr($ignore, -1) == '/') {
$ignoredMimeBase[$ignore] = true;
} else {
$ignoredMime[$ignore] = true;
}
}
}
$result = [];
foreach ($lines as $line) {
if ($line[0] == '#') {
continue;
}
$lineParts = explode(' ', trim(preg_replace('#\s+#', ' ', $line)));
$mime = $lineParts[0];
$mimeBase = explode('/', $mime, 2)[0].'/';
if (isset($ignoredMimeBase[$mimeBase])) {
continue;
}
if (isset($ignoredMime[$mime])) {
continue;
}
if (count($lineParts) == 1) {
if (!$isFilterWithoutExt) {
$result[] = sprintf(" %s;", $mime);
}
} else {
$exts = array_filter(array_slice($lineParts, 1));
$result[] = sprintf(" %s %s;", $mime, implode(' ', $exts));
}
}
$output = '';
if (!empty($result)) {
$template =
"#############################################################################
# Generated By MIME.types to nginx MIME converter
# https://gist.github.com/meniam/12f8c9c788969daa5c8fdfad97d9a9cc
#############################################################################
types {
%s
}
";
$output = sprintf($template, implode("\n", $result));
} else {
echo "Result Is Empty\n";
die;
}
if (!isset($options['o'])) {
echo $output;
} else {
file_put_contents($options['o'], $output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment