BinaryMimeType::guess()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.8337
c 0
b 0
f 0
cc 6
nc 6
nop 1
1
<?php
2
/**
3
 * @license MIT
4
 */
5
namespace Pivasic\Bundle\Common\File\MimeType;
6
7
use Pivasic\Bundle\Common\File\Exception\FileNotFoundException;
8
use Pivasic\Bundle\Common\File\Exception\AccessDeniedException;
9
10
/**
11
 * Class BinaryMimeType
12
 * @package Pivasic\Bundle\Common\File\MimeType
13
 */
14
class BinaryMimeType
15
{
16
    /**
17
     * @return bool
18
     */
19
    public static function isSupported(): bool
20
    {
21
        return '\\' !== DIRECTORY_SEPARATOR && function_exists('passthru') && function_exists('escapeshellarg');
22
    }
23
24
    /**
25
     * @param $path
26
     * @return string
27
     * @throws FileNotFoundException
28
     * @throws AccessDeniedException
29
     */
30
    public function guess(string $path): string
31
    {
32
        if (!is_file($path)) {
33
            throw new FileNotFoundException($path);
34
        }
35
36
        if (!is_readable($path)) {
37
            throw new AccessDeniedException($path);
38
        }
39
40
        if (!self::isSupported()) {
41
            return '';
42
        }
43
44
        $return = 1;
45
        ob_start();
46
        passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return);
47
        if ($return > 0) {
48
            ob_end_clean();
49
            return '';
50
        }
51
52
        $type = trim(ob_get_clean());
53
        if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
54
            return '';
55
        }
56
57
        return $match[1];
58
    }
59
}