Completed
Push — master ( d9f7fe...0d6725 )
by Igor
02:53
created

BinaryMimeType   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 2
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isSupported() 0 4 3
B guess() 0 29 6
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()
20
    {
21
        return '\\' !== DIRECTORY_SEPARATOR && function_exists('passthru') && function_exists('escapeshellarg');
22
    }
23
24
    /**
25
     * @param $path
26
     *
27
     * @return string|null
28
     *
29
     * @throws FileNotFoundException
30
     * @throws AccessDeniedException
31
     */
32
    public function guess($path)
33
    {
34
        if (!is_file($path)) {
35
            throw new FileNotFoundException($path);
36
        }
37
38
        if (!is_readable($path)) {
39
            throw new AccessDeniedException($path);
40
        }
41
42
        if (!self::isSupported()) {
43
            return null;
44
        }
45
46
        $return = 1;
47
        ob_start();
48
        passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return);
49
        if ($return > 0) {
50
            ob_end_clean();
51
            return null;
52
        }
53
54
        $type = trim(ob_get_clean());
55
        if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
56
            return null;
57
        }
58
59
        return $match[1];
60
    }
61
}