Added the Search API Synonym module to deal specifically with licence and license...
[yaffs-website] / vendor / symfony / http-foundation / File / MimeType / FileBinaryMimeTypeGuesser.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\HttpFoundation\File\MimeType;
13
14 use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
15 use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
16
17 /**
18  * Guesses the mime type with the binary "file" (only available on *nix).
19  *
20  * @author Bernhard Schussek <bschussek@gmail.com>
21  */
22 class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface
23 {
24     private $cmd;
25
26     /**
27      * The $cmd pattern must contain a "%s" string that will be replaced
28      * with the file name to guess.
29      *
30      * The command output must start with the mime type of the file.
31      *
32      * @param string $cmd The command to run to get the mime type of a file
33      */
34     public function __construct($cmd = 'file -b --mime %s 2>/dev/null')
35     {
36         $this->cmd = $cmd;
37     }
38
39     /**
40      * Returns whether this guesser is supported on the current OS.
41      *
42      * @return bool
43      */
44     public static function isSupported()
45     {
46         static $supported = null;
47
48         if (null !== $supported) {
49             return $supported;
50         }
51
52         if ('\\' === \DIRECTORY_SEPARATOR || !\function_exists('passthru') || !\function_exists('escapeshellarg')) {
53             return $supported = false;
54         }
55
56         ob_start();
57         passthru('command -v file', $exitStatus);
58         $binPath = trim(ob_get_clean());
59
60         return $supported = 0 === $exitStatus && '' !== $binPath;
61     }
62
63     /**
64      * {@inheritdoc}
65      */
66     public function guess($path)
67     {
68         if (!is_file($path)) {
69             throw new FileNotFoundException($path);
70         }
71
72         if (!is_readable($path)) {
73             throw new AccessDeniedException($path);
74         }
75
76         if (!self::isSupported()) {
77             return;
78         }
79
80         ob_start();
81
82         // need to use --mime instead of -i. see #6641
83         passthru(sprintf($this->cmd, escapeshellarg($path)), $return);
84         if ($return > 0) {
85             ob_end_clean();
86
87             return;
88         }
89
90         $type = trim(ob_get_clean());
91
92         if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
93             // it's not a type, but an error message
94             return;
95         }
96
97         return $match[1];
98     }
99 }