FileinfoMimeTypeGuesser.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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\HttpFoundation\File\MimeType;
  11. use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
  12. use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
  13. /**
  14. * Guesses the mime type using the PECL extension FileInfo
  15. *
  16. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  17. */
  18. class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface
  19. {
  20. /**
  21. * Returns whether this guesser is supported on the current OS/PHP setup
  22. *
  23. * @return Boolean
  24. */
  25. static public function isSupported()
  26. {
  27. return function_exists('finfo_open');
  28. }
  29. /**
  30. * Guesses the mime type of the file with the given path
  31. *
  32. * @see MimeTypeGuesserInterface::guess()
  33. */
  34. public function guess($path)
  35. {
  36. if (!is_file($path)) {
  37. throw new FileNotFoundException($path);
  38. }
  39. if (!is_readable($path)) {
  40. throw new AccessDeniedException($path);
  41. }
  42. if (!self::isSupported()) {
  43. return null;
  44. }
  45. if (!$finfo = new \finfo(FILEINFO_MIME_TYPE)) {
  46. return null;
  47. }
  48. return $finfo->file($path);
  49. }
  50. }