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(): MimeType |
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
|
|
|
* @return string |
35
|
|
|
* @throws \LogicException |
36
|
|
|
* @throws FileNotFoundException |
37
|
|
|
* @throws AccessDeniedException |
38
|
|
|
*/ |
39
|
|
|
public function guess(string $path): string |
40
|
|
|
{ |
41
|
|
|
if (!is_file($path)) { |
42
|
|
|
throw new FileNotFoundException($path); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (!is_readable($path)) { |
46
|
|
|
throw new AccessDeniedException($path); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (0 == count($this->guesserList)) { |
50
|
|
|
$msg = 'Unable to guess the mime type as no guessers are available'; |
51
|
|
|
if (!FileInfoMimeType::isSupported()) { |
52
|
|
|
$msg .= ' (Did you enable the php_fileinfo extension?)'; |
53
|
|
|
} |
54
|
|
|
throw new \LogicException($msg); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** @var FileInfoMimeType|BinaryMimeType $guesser */ |
58
|
|
|
foreach ($this->guesserList as $guesser) { |
59
|
|
|
if ('' != $mimeType = $guesser->guess($path)) { |
60
|
|
|
return $mimeType; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return ''; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Registers all natively provided mime type guessers. |
70
|
|
|
*/ |
71
|
|
|
private function __construct() |
72
|
|
|
{ |
73
|
|
|
$this->guesserList = []; |
74
|
|
|
|
75
|
|
|
if (FileInfoMimeType::isSupported()) { |
76
|
|
|
$this->guesserList[] = new FileInfoMimeType(); |
77
|
|
|
} |
78
|
|
|
if (BinaryMimeType::isSupported()) { |
79
|
|
|
$this->guesserList[] = new BinaryMimeType(); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @var MimeType |
86
|
|
|
*/ |
87
|
|
|
private static $instance = null; |
88
|
|
|
|
89
|
|
|
private $guesserList; |
90
|
|
|
} |