Passed
Push — master ( 25fb9a...142153 )
by Bjørn
01:49
created

SniffFirstFourBytes   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A doDetect() 0 21 4
1
<?php
2
3
namespace ImageMimeTypeGuesser\Detectors;
4
5
use \ImageMimeTypeGuesser\Detectors\AbstractDetector;
6
7
class SniffFirstFourBytes extends AbstractDetector
8
{
9
10
    /**
11
     * Try to detect mime type by sniffing the first four bytes.
12
     *
13
     * Credits: Based on the code here: http://phil.lavin.me.uk/2011/12/php-accurately-detecting-the-type-of-a-file/
14
     *
15
     * Returns:
16
     * - mime type (string) (if it is in fact an image, and type could be determined)
17
     * - false (if it is not an image type that the server knowns about)
18
     * - null  (if nothing can be determined)
19
     *
20
     * @param  string  $filePath  The path to the file
21
     * @return string|false|null  mimetype (if it is an image, and type could be determined),
22
     *    false (if it is not an image type that the server knowns about)
23
     *    or null (if nothing can be determined)
24
     */
25
    protected function doDetect($filePath)
26
    {
27
    	// PNG, GIF, JFIF JPEG, EXIF JPEF (respectively)
28
        $known = [
29
            '89504E47' => 'image/png',
30
            '47494638' => 'image/gif',
31
            'FFD8FFE0' => 'image/jpeg',  //  JFIF JPEG
32
            'FFD8FFE1' => 'image/jpeg',  //  EXIF JPEG
33
        ];
34
35
    	$handle = @fopen($filePath, 'r');
36
        if ($handle === false) {
37
            return;
38
        }
39
        $firstFour = @fread($handle, 4);
40
        if ($firstFour === false) {
41
            return;
42
        }
43
        $key = strtoupper(bin2hex($firstFour));
44
        if (isset($known[$key])) {
45
            return $known[$key];
46
        }
47
    }
48
}
49