Passed
Push — master ( 33913d...25fb9a )
by Bjørn
01:59
created

GuessFromExtension   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 58
rs 10
c 0
b 0
f 0
wmc 16

1 Method

Rating   Name   Duplication   Size   Complexity  
C guess() 0 32 16
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 GuessFromExtension
13
{
14
15
16
    /**
17
     *  Make a wild guess based on file extension.
18
     *
19
     *  - and I mean wild!
20
     *
21
     *  Only most popular image types are recognized.
22
     *  Many are not. See this list: https://www.iana.org/assignments/media-types/media-types.xhtml
23
     *                - and the constants here: https://secure.php.net/manual/en/function.exif-imagetype.php
24
     *
25
     *  If no mapping found, nothing is returned
26
     *
27
     *  TODO: jp2, jpx, ...
28
     * Returns:
29
     * - mimetype (if file extension could be mapped to an image type),
30
     * - false (if file extension could be mapped to a type known not to be an image type)
31
     * - void (if file extension could not be mapped to any mime type, using our little list)
32
     *
33
     * @param  string  $filePath  The path to the file
34
     * @return string|false|void  mimetype (if file extension could be mapped to an image type),
35
     *    false (if file extension could be mapped to a type known not to be an image type)
36
     *    or void (if file extension could not be mapped to any mime type, using our little list)
37
     */
38
    public static function guess($filePath)
39
    {
40
        $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
41
        $fileExtension = strtolower($fileExtension);
42
43
        switch ($fileExtension) {
44
            case 'bmp':
45
            case 'gif':
46
            case 'jpeg':
47
            case 'png':
48
            case 'tiff':
49
            case 'webp':
50
                return 'image/' . $fileExtension;
51
52
            case 'ico':
53
                return 'image/vnd.microsoft.icon';      // or perhaps 'x-icon' ?
54
55
            case 'jpg':
56
                return 'image/jpeg';
57
58
            case 'svg':
59
                return 'image/svg+xml';
60
61
            case 'tif':
62
                return 'image/tiff';
63
64
            case 'txt':
65
            case 'doc':
66
            case 'exe':
67
            case 'zip':
68
            case 'gz':
69
                return false;
70
71
        }
72
    }
73
}
74