3 namespace Drupal\imagemagick;
5 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
8 * Maps MIME types to file extensions.
10 class ImagemagickMimeTypeMapper {
13 * The extension MIME type guesser.
15 * @var \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser
17 protected $mimeTypeGuesser;
20 * The MIME types mapping array after going through the module handler.
22 * Copied via Reflection from
23 * \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser.
30 * Constructs an ImagemagickMimeTypeMapper object.
32 * @param \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $extension_mimetype_guesser
33 * The extension MIME type guesser.
35 public function __construct(MimeTypeGuesserInterface $extension_mimetype_guesser) {
36 $this->mimeTypeGuesser = $extension_mimetype_guesser;
40 * Returns the MIME types mapping array from ExtensionMimeTypeGuesser.
42 * Copied via Reflection from
43 * \Drupal\Core\File\MimeType\ExtensionMimeTypeGuesser.
46 * The MIME types mapping array.
48 protected function getMapping() {
49 if (!$this->mapping) {
50 // Guess a fake file name just to ensure the guesser loads any mapping
51 // alteration through the hooks.
52 $this->mimeTypeGuesser->guess('fake.png');
53 // Use Reflection to get a copy of the protected $mapping property in the
54 // guesser class. Get the proxied service first, then the actual mapping.
55 $reflection = new \ReflectionObject($this->mimeTypeGuesser);
56 $proxied_service = $reflection->getProperty('service');
57 $proxied_service->setAccessible(TRUE);
58 $service = $proxied_service->getValue(clone $this->mimeTypeGuesser);
59 $reflection = new \ReflectionObject($service);
60 $reflection_mapping = $reflection->getProperty('mapping');
61 $reflection_mapping->setAccessible(TRUE);
62 $this->mapping = $reflection_mapping->getValue(clone $service);
64 return $this->mapping;
68 * Returns the appropriate extensions for a given MIME type.
70 * @param string $mimetype
74 * An array of file extensions matching the MIME type, without leading dot.
76 public function getExtensionsForMimeType($mimetype) {
77 $mapping = $this->getMapping();
78 if (!in_array($mimetype, $mapping['mimetypes'])) {
81 $key = array_search($mimetype, $mapping['mimetypes']);
82 $extensions = array_keys($mapping['extensions'], $key, TRUE);
88 * Returns known MIME types.
91 * An array of MIME types.
93 public function getMimeTypes() {
94 return array_values($this->getMapping()['mimetypes']);