Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| MimeMap | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
10 | |
100.00% |
1 / 1 |
| filenameToMime | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| extToMime | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
8 | |||
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * ImageMimeTypeGuesser - Detect / guess mime type of an image |
| 5 | * |
| 6 | * @link https://github.com/rosell-dk/image-mime-type-guesser |
| 7 | * @license MIT |
| 8 | */ |
| 9 | |
| 10 | namespace ImageMimeTypeGuesser; |
| 11 | |
| 12 | class MimeMap |
| 13 | { |
| 14 | |
| 15 | /** |
| 16 | * Map image file extension to mime type |
| 17 | * |
| 18 | * |
| 19 | * @param string $filePath The filename (or path), ie "image.jpg" |
| 20 | * @return string|false|null mimetype (if file extension could be mapped to an image type), |
| 21 | * false (if file extension could be mapped to a type known not to be an image type) |
| 22 | * or null (if file extension could not be mapped to any mime type, using our little list) |
| 23 | */ |
| 24 | public static function filenameToMime($filePath) |
| 25 | { |
| 26 | $result = preg_match('#\\.([^.]*)$#', $filePath, $matches); |
| 27 | if ($result !== 1) { |
| 28 | return null; |
| 29 | } |
| 30 | $fileExtension = $matches[1]; |
| 31 | return self::extToMime($fileExtension); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Map image file extension to mime type |
| 36 | * |
| 37 | * |
| 38 | * @param string $fileExtension The file extension (ie "jpg") |
| 39 | * @return string|false|null mimetype (if file extension could be mapped to an image type), |
| 40 | * false (if file extension could be mapped to a type known not to be an image type) |
| 41 | * or null (if file extension could not be mapped to any mime type, using our little list) |
| 42 | */ |
| 43 | public static function extToMime($fileExtension) |
| 44 | { |
| 45 | |
| 46 | $fileExtension = strtolower($fileExtension); |
| 47 | |
| 48 | // Trivial image mime types |
| 49 | if (in_array($fileExtension, ['apng', 'avif', 'bmp', 'gif', 'jpeg', 'png', 'tiff', 'webp'])) { |
| 50 | return 'image/' . $fileExtension; |
| 51 | } |
| 52 | |
| 53 | // Common extensions that are definitely not images |
| 54 | if (in_array($fileExtension, ['txt', 'doc', 'zip', 'gz', 'exe'])) { |
| 55 | return false; |
| 56 | } |
| 57 | |
| 58 | // Non-trivial image mime types |
| 59 | switch ($fileExtension) { |
| 60 | case 'ico': |
| 61 | case 'cur': |
| 62 | return 'image/x-icon'; // or perhaps 'vnd.microsoft.icon' ? |
| 63 | |
| 64 | case 'jpg': |
| 65 | return 'image/jpeg'; |
| 66 | |
| 67 | case 'svg': |
| 68 | return 'image/svg+xml'; |
| 69 | |
| 70 | case 'tif': |
| 71 | return 'image/tiff'; |
| 72 | } |
| 73 | |
| 74 | // We do not know this extension, return null |
| 75 | return null; |
| 76 | } |
| 77 | } |