FinfoMimeTypeDetector::detectMimeType()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 6
nc 4
nop 2
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\MimeTypeDetection;
6
7
use finfo;
8
9
use const FILEINFO_MIME_TYPE;
10
use const PATHINFO_EXTENSION;
11
12
class FinfoMimeTypeDetector implements MimeTypeDetector
13
{
14
    private const INCONCLUSIVE_MIME_TYPES = ['application/x-empty', 'text/plain', 'text/x-asm'];
15
16
    /**
17
     * @var finfo
18
     */
19
    private $finfo;
20
21
    /**
22
     * @var ExtensionToMimeTypeMap
23
     */
24
    private $extensionMap;
25
26 36
    public function __construct(string $magicFile = '', ExtensionToMimeTypeMap $extensionMap = null)
27
    {
28 36
        $this->finfo = new finfo(FILEINFO_MIME_TYPE, $magicFile);
29 36
        $this->extensionMap = $extensionMap ?: new GeneratedExtensionToMimeTypeMap();
30 36
    }
31
32 18
    public function detectMimeType(string $path, $contents): ?string
33
    {
34 18
        $mimeType = is_string($contents)
35 12
            ? (@$this->finfo->buffer($contents) ?: null)
36 18
            : null;
37
38 18
        if ($mimeType !== null && ! in_array($mimeType, self::INCONCLUSIVE_MIME_TYPES)) {
39 6
            return $mimeType;
40
        }
41
42 12
        return $this->detectMimeTypeFromPath($path);
43
    }
44
45 18
    public function detectMimeTypeFromPath(string $path): ?string
46
    {
47 18
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
48
49 18
        return $this->extensionMap->lookupMimeType($extension);
50
    }
51
52 6
    public function detectMimeTypeFromFile(string $path): ?string
53
    {
54 6
        return @$this->finfo->file($path) ?: null;
55
    }
56
57 6
    public function detectMimeTypeFromBuffer(string $contents): ?string
58
    {
59 6
        return @$this->finfo->buffer($contents) ?: null;
60
    }
61
}
62
63