You are here

public function MimeDetectService::getMime in MimeDetect 8

Get the MIME type for a given file.

Parameters

\Drupal\file\FileInterface $file: The file to be analyzed.

Return value

string The detected MIME type for the given file.

Overrides MimeDetectServiceInterface::getMime

File

src/MimeDetectService.php, line 83

Class

MimeDetectService
MimeDetect service.

Namespace

Drupal\mimedetect

Code

public function getMime(FileInterface $file) {
  $file_path = $this->fileSystem
    ->realpath($file
    ->getFileUri());

  // Try any specific MIME detector for the filename extension.
  $mime = $this
    ->getMimeByDetector($file);

  // Try PHP fileinfo.
  if (!$mime && $this->finfo) {
    $mime = $this->finfo
      ->file($file_path);
  }

  // Try the 'file' UNIX command.
  if ((!$mime || $mime == 'application/octet-stream') && $this->unixfilecmd) {
    $mime = trim(exec($this->unixfilecmd . escapeshellarg($file_path)));
  }
  if ($mime) {

    // With text we often get charset like 'text/plain; charset=us-ascii'.
    $mime = explode(';', $mime);
    $mime = trim($mime[0]);
  }
  else {

    // Try file name extension mapping.
    $mime = $this->mimeTypeGuesser
      ->guess($file_path);
  }
  return $mime ?: 'application/octet-stream';
}