MimeTypeGuesser.php 2.28 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
<?php

/**
 * @file
 * Contains \Drupal\Core\File\MimeType\MimeTypeGuesser.
 */

namespace Drupal\Core\File\MimeType;

use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;

/**
 * Defines a MIME type guesser that also supports stream wrapper paths.
 */
class MimeTypeGuesser implements MimeTypeGuesserInterface {

  /**
   * An array of arrays of registered guessers keyed by priority.
   *
   * @var array
   */
  protected $guessers = array();

  /**
   * Holds the array of guessers sorted by priority.
   *
   * If this is NULL a rebuild will be triggered.
   *
   * @var \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface[]
   *
   * @see \Drupal\Core\File\MimeType\MimeTypeGuesser::addGuesser()
   * @see \Drupal\Core\File\MimeType\MimeTypeGuesser::sortGuessers()
   */
  protected $sortedGuessers = NULL;

  /**
   * {@inheritdoc}
   */
  public function guess($path) {
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($path)) {
      // Get the real path from the stream wrapper.
      $path = $wrapper->realpath();
    }

    if ($this->sortedGuessers === NULL) {
46
      // Sort is not triggered yet.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      $this->sortedGuessers = $this->sortGuessers();
    }

    foreach ($this->sortedGuessers as $guesser) {
      $mime_type = $guesser->guess($path);
      if ($mime_type !== NULL) {
        return $mime_type;
      }
    }
  }

  /**
   * Appends a MIME type guesser to the guessers chain.
   *
   * @param \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $guesser
   *   The guesser to be appended.
   * @param int $priority
   *   The priority of the guesser being added.
   *
66
   * @return $this
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
   */
  public function addGuesser(MimeTypeGuesserInterface $guesser, $priority = 0) {
    $this->guessers[$priority][] = $guesser;
    // Mark sorted guessers for rebuild.
    $this->sortedGuessers = NULL;
    return $this;
  }

  /**
   * Sorts guessers according to priority.
   *
   * @return \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface[]
   *   A sorted array of MIME type guesser objects.
   */
  protected function sortGuessers() {
    $sorted = array();
    krsort($this->guessers);

    foreach ($this->guessers as $guesser) {
      $sorted = array_merge($sorted, $guesser);
    }
    return $sorted;
  }

}