summaryrefslogtreecommitdiff
path: root/src/application/mystic/forum/utils/FileUtils.php
blob: 1910f0cfde00b03f359d1cf72239c9b03142dd2a (plain)
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
<?php
declare(strict_types=1);

namespace mystic\forum\utils;

final class FileUtils {
    use StaticClass;

    private const MIME_FILE = __DIR__ . "/../../../assets/mimetypes";
    public const DEFAULT_MIME_TYPE = "application/octet-stream";

    private static ?array $extToMime = null;

    private static function ensureMimeMapping(): void {
        if (self::$extToMime !== null)
            return;

        self::$extToMime = [];
        
        $hFile = fopen(self::MIME_FILE, "r");
        while (($ln = fgets($hFile)) !== false) {
            [$mime, $extensions] = preg_split('/\t+/', $ln, 2);
            $extensions = explode(" ", strtolower($extensions));
            foreach ($extensions as $ext)
                self::$extToMime[$ext] = $mime;
        }
    }

    public static function getMimeTypeForExtension(string $extension, string $defaultMimeType = self::DEFAULT_MIME_TYPE): string {
        self::ensureMimeMapping();
        return self::$extToMime[strtolower($extension)] ?? $defaultMimeType;
    }
}