Skip to content

Commit 3490842

Browse files
committed
✨ mime type getters
1 parent 137faed commit 3490842

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/message_helpers.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
use Psr\Http\Message\{MessageInterface, RequestInterface, ResponseInterface, UriInterface};
1313

1414
use function array_filter, array_map, explode, extension_loaded, function_exists, gzdecode, gzinflate, gzuncompress, implode,
15-
is_array, is_scalar, json_decode, json_encode, parse_url, preg_match, preg_replace_callback, rawurldecode,
15+
is_array, is_scalar, json_decode, json_encode, parse_url, pathinfo, preg_match, preg_replace_callback, rawurldecode,
1616
rawurlencode, simplexml_load_string, strtolower, trim, urlencode;
1717

18+
use const PATHINFO_EXTENSION;
19+
1820
const CHILLERLAN_PSR7_UTIL_INCLUDES = true;
1921

2022
/**
@@ -123,6 +125,20 @@
123125
'zip' => 'application/zip',
124126
];
125127

128+
/**
129+
* Get the mime type for the given file extension
130+
*/
131+
function getMimetypeFromExtension(string $extension):?string{
132+
return MIMETYPES[strtolower($extension)] ?? null;
133+
}
134+
135+
/**
136+
* Get the mime type from a file name
137+
*/
138+
function getMimetypeFromFilename(string $filename):?string{
139+
return getMimetypeFromExtension(pathinfo($filename, PATHINFO_EXTENSION));
140+
}
141+
126142
/**
127143
* @param string|string[] $data
128144
*

tests/MessageHelpersTest.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
use RuntimeException, TypeError;
1414

1515
use function chillerlan\HTTP\Utils\{
16-
decompress_content, get_json, get_xml, message_to_string, parseUrl, r_rawurlencode,
17-
uriIsAbsolute, uriIsAbsolutePathReference, uriIsDefaultPort, uriIsNetworkPathReference,
16+
decompress_content, get_json, get_xml, getMimetypeFromExtension, getMimetypeFromFilename, message_to_string,
17+
parseUrl, r_rawurlencode, uriIsAbsolute, uriIsAbsolutePathReference, uriIsDefaultPort, uriIsNetworkPathReference,
1818
uriIsRelativePathReference, uriWithoutQueryValue, uriWithQueryValue
1919
};
2020

@@ -286,4 +286,10 @@ public function testParseUrl($url, $expected):void{
286286
$this::assertSame($expected, parseUrl($url));
287287
}
288288

289+
public function testGetMimetype():void{
290+
$this::assertSame('application/json', getMimetypeFromExtension('json'));
291+
$this::assertSame('application/json', getMimetypeFromFilename('/path/to/some/file.json'));
292+
$this::assertNull(getMimetypeFromExtension('whatever'));
293+
}
294+
289295
}

0 commit comments

Comments
 (0)