4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation\File\MimeType;
14 use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
15 use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
18 * Guesses the mime type with the binary "file" (only available on *nix).
20 * @author Bernhard Schussek <bschussek@gmail.com>
22 class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
27 * The $cmd pattern must contain a "%s" string that will be replaced
28 * with the file name to guess.
30 * The command output must start with the mime type of the file.
32 * @param string $cmd The command to run to get the mime type of a file
34 public function __construct($cmd = 'file -b --mime %s 2>/dev/null')
40 * Returns whether this guesser is supported on the current OS.
44 public static function isSupported()
46 static $supported = null;
48 if (null !== $supported) {
52 if ('\\' === DIRECTORY_SEPARATOR || !function_exists('passthru') || !function_exists('escapeshellarg')) {
53 return $supported = false;
57 passthru('command -v file', $exitStatus);
58 $binPath = trim(ob_get_clean());
60 return $supported = 0 === $exitStatus && '' !== $binPath;
66 public function guess($path)
68 if (!is_file($path)) {
69 throw new FileNotFoundException($path);
72 if (!is_readable($path)) {
73 throw new AccessDeniedException($path);
76 if (!self::isSupported()) {
82 // need to use --mime instead of -i. see #6641
83 passthru(sprintf($this->cmd, escapeshellarg($path)), $return);
90 $type = trim(ob_get_clean());
92 if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
93 // it's not a type, but an error message