function ExtensionMimeTypeGuesser::guessMimeType

Same name in this branch
  1. 9 core/lib/Drupal/Core/ProxyClass/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\ProxyClass\File\MimeType\ExtensionMimeTypeGuesser::guessMimeType()
Same name in other branches
  1. 10 core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser::guessMimeType()
  2. 10 core/lib/Drupal/Core/ProxyClass/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\ProxyClass\File\MimeType\ExtensionMimeTypeGuesser::guessMimeType()
  3. 11.x core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser::guessMimeType()
  4. 11.x core/lib/Drupal/Core/ProxyClass/File/MimeType/ExtensionMimeTypeGuesser.php \Drupal\Core\ProxyClass\File\MimeType\ExtensionMimeTypeGuesser::guessMimeType()
1 call to ExtensionMimeTypeGuesser::guessMimeType()
ExtensionMimeTypeGuesser::guess in core/lib/Drupal/Core/File/MimeType/ExtensionMimeTypeGuesser.php

File

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

Class

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

Namespace

Drupal\Core\File\MimeType

Code

public function guessMimeType($path) : ?string {
    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';
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.