vendor/symfony/mime/FileinfoMimeTypeGuesser.php line 47

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Mime;
  11. use Symfony\Component\Mime\Exception\InvalidArgumentException;
  12. use Symfony\Component\Mime\Exception\LogicException;
  13. /**
  14.  * Guesses the MIME type using the PECL extension FileInfo.
  15.  *
  16.  * @author Bernhard Schussek <bschussek@gmail.com>
  17.  */
  18. class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface
  19. {
  20.     private $magicFile;
  21.     /**
  22.      * @param string $magicFile A magic file to use with the finfo instance
  23.      *
  24.      * @see http://www.php.net/manual/en/function.finfo-open.php
  25.      */
  26.     public function __construct(string $magicFile null)
  27.     {
  28.         $this->magicFile $magicFile;
  29.     }
  30.     /**
  31.      * {@inheritdoc}
  32.      */
  33.     public function isGuesserSupported(): bool
  34.     {
  35.         return \function_exists('finfo_open');
  36.     }
  37.     /**
  38.      * {@inheritdoc}
  39.      */
  40.     public function guessMimeType(string $path): ?string
  41.     {
  42.         if (!is_file($path) || !is_readable($path)) {
  43.             throw new InvalidArgumentException(sprintf('The "%s" file does not exist or is not readable.'$path));
  44.         }
  45.         if (!$this->isGuesserSupported()) {
  46.             throw new LogicException(sprintf('The "%s" guesser is not supported.'__CLASS__));
  47.         }
  48.         if (false === $finfo = new \finfo(\FILEINFO_MIME_TYPE$this->magicFile)) {
  49.             return null;
  50.         }
  51.         $mimeType $finfo->file($path);
  52.         if ($mimeType && === (\strlen($mimeType) % 2)) {
  53.             $mimeStart substr($mimeType0, \strlen($mimeType) >> 1);
  54.             $mimeType $mimeStart.$mimeStart === $mimeType $mimeStart $mimeType;
  55.         }
  56.         return $mimeType;
  57.     }
  58. }