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 MimeTypeGuesser |
12
|
|
|
* @package Pivasic\Bundle\Common\File\MimeType |
13
|
|
|
*/ |
14
|
|
|
class MimeType |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Returns the singleton instance. |
18
|
|
|
* |
19
|
|
|
* @return MimeType |
20
|
|
|
*/ |
21
|
|
|
public static function getInstance() |
22
|
|
|
{ |
23
|
|
|
if (null === self::$instance) { |
24
|
|
|
self::$instance = new self(); |
25
|
|
|
} |
26
|
|
|
return self::$instance; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Get mime type or NULL, if none could be guessed. |
32
|
|
|
* |
33
|
|
|
* @param string $path Path to the file |
34
|
|
|
* |
35
|
|
|
* @return string |
36
|
|
|
* |
37
|
|
|
* @throws \LogicException |
38
|
|
|
* @throws FileNotFoundException |
39
|
|
|
* @throws AccessDeniedException |
40
|
|
|
*/ |
41
|
|
|
public function guess($path) |
42
|
|
|
{ |
43
|
|
|
if (!is_file($path)) { |
44
|
|
|
throw new FileNotFoundException($path); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if (!is_readable($path)) { |
48
|
|
|
throw new AccessDeniedException($path); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (0 == count($this->guesserList)) { |
52
|
|
|
$msg = 'Unable to guess the mime type as no guessers are available'; |
53
|
|
|
if (!FileInfoMimeType::isSupported()) { |
54
|
|
|
$msg .= ' (Did you enable the php_fileinfo extension?)'; |
55
|
|
|
} |
56
|
|
|
throw new \LogicException($msg); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** @var FileInfoMimeType|BinaryMimeType $guesser */ |
60
|
|
|
foreach ($this->guesserList as $guesser) { |
61
|
|
|
if (null !== $mimeType = $guesser->guess($path)) { |
62
|
|
|
return $mimeType; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Registers all natively provided mime type guessers. |
72
|
|
|
*/ |
73
|
|
|
private function __construct() |
74
|
|
|
{ |
75
|
|
|
$this->guesserList = []; |
76
|
|
|
|
77
|
|
|
if (FileInfoMimeType::isSupported()) { |
78
|
|
|
$this->guesserList[] = new FileInfoMimeType(); |
79
|
|
|
} |
80
|
|
|
if (BinaryMimeType::isSupported()) { |
81
|
|
|
$this->guesserList[] = new BinaryMimeType(); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* @var MimeType |
88
|
|
|
*/ |
89
|
|
|
private static $instance = null; |
90
|
|
|
|
91
|
|
|
private $guesserList; |
92
|
|
|
} |
93
|
|
|
|