W3cubDocs

/Drupal 8

public function ExtensionMimeTypeGuesser::guess

public ExtensionMimeTypeGuesser::guess($path)

Guesses the mime type of the file with the given path.

Parameters

string $path The path to the file:

Return value

string The mime type or NULL, if none could be guessed

Throws

FileNotFoundException If the file does not exist

AccessDeniedException If the file could not be read

Overrides MimeTypeGuesserInterface::guess

File

core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php, line 889

Class

ExtensionMimeTypeGuesser
Makes possible to guess the MIME type of a file using its extension.

Namespace

Drupal\Core\File\MimeType

Code

public function guess($path) {
  if ($this->mapping === NULL) {
    $mapping = $this->defaultMapping;
    // Allow modules to alter the default mapping.
    $this->moduleHandler->alter('file_mimetype_mapping', $mapping);
    $this->mapping = $mapping;
  }

  $extension = '';
  $file_parts = explode('.', drupal_basename($path));

  // Remove the first part: a full filename should not match an extension.
  array_shift($file_parts);

  // Iterate over the file parts, trying to find a match.
  // For my.awesome.image.jpeg, we try:
  //   - jpeg
  //   - image.jpeg, and
  //   - awesome.image.jpeg
  while ($additional_part = array_pop($file_parts)) {
    $extension = strtolower($additional_part . ($extension ? '.' . $extension : ''));
    if (isset($this->mapping['extensions'][$extension])) {
      return $this->mapping['mimetypes'][$this->mapping['extensions'][$extension]];
    }
  }

  return 'application/octet-stream';
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!File!MimeType!ExtensionMimeTypeGuesser.php/function/ExtensionMimeTypeGuesser::guess/8.1.x