master

laravel/framework

Last updated at: 29/12/2023 09:24

MimeType.php

TLDR

This file provides a class called MimeType which allows you to get the MIME type of a file based on its extension or search for the extension of a given MIME type.

Methods

getMimeTypes

This method retrieves the instance of the MimeTypes class from the Symfony MimeTypes library.

from

This method takes a filename as a parameter and returns the MIME type of the corresponding file based on its extension.

get

This method takes an extension as a parameter and returns the MIME type associated with the extension. If the extension is not found, it returns the default MIME type 'application/octet-stream'.

search

This method takes a MIME type as a parameter and searches for the extension associated with the given MIME type. It returns the first extension found or null if no extension is found.

<?php

namespace Illuminate\Http\Testing;

use Illuminate\Support\Arr;
use Symfony\Component\Mime\MimeTypes;

class MimeType
{
    /**
     * The mime types instance.
     *
     * @var \Symfony\Component\Mime\MimeTypes|null
     */
    private static $mime;

    /**
     * Get the mime types instance.
     *
     * @return \Symfony\Component\Mime\MimeTypesInterface
     */
    public static function getMimeTypes()
    {
        if (self::$mime === null) {
            self::$mime = new MimeTypes;
        }

        return self::$mime;
    }

    /**
     * Get the MIME type for a file based on the file's extension.
     *
     * @param  string  $filename
     * @return string
     */
    public static function from($filename)
    {
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        return self::get($extension);
    }

    /**
     * Get the MIME type for a given extension or return all mimes.
     *
     * @param  string  $extension
     * @return string
     */
    public static function get($extension)
    {
        return Arr::first(self::getMimeTypes()->getMimeTypes($extension)) ?? 'application/octet-stream';
    }

    /**
     * Search for the extension of a given MIME type.
     *
     * @param  string  $mimeType
     * @return string|null
     */
    public static function search($mimeType)
    {
        return Arr::first(self::getMimeTypes()->getExtensions($mimeType));
    }
}