|
| 1 | +.. index:: |
| 2 | + single: MIME |
| 3 | + single: Components; MIME |
| 4 | + |
| 5 | +The MIME Component |
| 6 | +================== |
| 7 | + |
| 8 | + The MIME component allows manipulating MIME types. |
| 9 | + |
| 10 | +Installation |
| 11 | +------------ |
| 12 | + |
| 13 | +.. code-block:: terminal |
| 14 | +
|
| 15 | + $ composer require symfony/mime |
| 16 | +
|
| 17 | +Alternatively, you can clone the `<https://github.com/symfony/mime>`_ repository. |
| 18 | + |
| 19 | +.. include:: /components/require_autoload.rst.inc |
| 20 | + |
| 21 | +MIME Types |
| 22 | +---------- |
| 23 | + |
| 24 | +The :class:`Symfony\\Component\\Mime\\MimeTypes` class manipulates the |
| 25 | +relationships between MIME types and file name extensions:: |
| 26 | + |
| 27 | + use Symfony\Component\Mime\MimeTypes; |
| 28 | + |
| 29 | + $mimeTypes = new MimeTypes(); |
| 30 | + $exts = $mimeTypes->getExtensions('application/mbox'); |
| 31 | + // $exts contains an array of extensions: ['mbox'] |
| 32 | + |
| 33 | + $mimeTypes = $mimeTypes->getMimeTypes('mbox'); |
| 34 | + // $mimeTypes contains an array of MIME types: ['application/mbox'] |
| 35 | + |
| 36 | + // guess a mime type for a file |
| 37 | + $mimeType = $mimeTypes->guessMimeType('/some/path/to/image.gif'); |
| 38 | + |
| 39 | +Adding a MIME Type Guesser |
| 40 | +~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 41 | + |
| 42 | +You can register your own MIME type guesser by creating a class that extends |
| 43 | +:class:`Symfony\\Component\\Mime\\MimeTypeGuesserInterface`:: |
| 44 | + |
| 45 | + namespace App; |
| 46 | + |
| 47 | + use Symfony\Component\Mime\MimeTypeGuesserInterface; |
| 48 | + |
| 49 | + class SomeMimeTypeGuesser implements MimeTypeGuesserInterface |
| 50 | + { |
| 51 | + public function isGuesserSupported(): bool |
| 52 | + { |
| 53 | + // return true when the guesser is supported (might depend on the OS for instance) |
| 54 | + return true; |
| 55 | + } |
| 56 | + |
| 57 | + public function guessMimeType(string $path): ?string |
| 58 | + { |
| 59 | + // return a MIME type based on the content of the file stored in $path |
| 60 | + // you MUST not use the filename to determine the MIME type. |
| 61 | + return 'text/plain'; |
| 62 | + } |
| 63 | + } |
0 commit comments