You are here

public function ExtensionMimeTypeGuesser::guess in Drupal 8

Same name in this branch
  1. 8 core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser::guess()
  2. 8 core/lib/Drupal/Core/ProxyClass/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\ProxyClass\File\MimeType\ExtensionMimeTypeGuesser::guess()
Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser::guess()

File

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

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::service('file_system')
    ->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';
}