Created
February 15, 2026 23:47
-
-
Save thekid/73ef0fbc0aea76031453cf6ec11528c5 to your computer and use it in GitHub Desktop.
Create mimetypes for XP Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php namespace tools; | |
| use util\cmd\Console; | |
| use peer\http\HttpConnection from 'xp-framework/http'; | |
| use text\json\StreamInput from 'xp-forge/json'; | |
| $c= new HttpConnection('https://cdn.jsdelivr.net/gh/jshttp/mime-db@latest/db.json'); | |
| $r= $c->get(); | |
| if (200 !== $r->statusCode()) { | |
| Console::$err->writeLine($r); | |
| return 1; | |
| } | |
| $out= Console::$out; | |
| $out->writeLine('<?php namespace util;'); | |
| $out->writeLine(); | |
| $out->writeLine(<<<'DECLARATION' | |
| /** | |
| * MIME Types | |
| * | |
| * @see https://cdn.jsdelivr.net/gh/jshttp/mime-db@latest/db.json | |
| * @test util.unittest.MimeTypeTest | |
| */ | |
| abstract class MimeType { | |
| DECLARATION); | |
| // Generate lookup map | |
| $in= new StreamInput($r->in()); | |
| $extensions= []; | |
| foreach ($in->pairs() as $type => $value) { | |
| foreach ($value['extensions'] ?? [] as $extension) { | |
| if ('application/octet-stream' === $type) { | |
| $score= 0.1; | |
| } else if (str_starts_with($type, 'application/x-')) { | |
| $score= 0.7; | |
| } else if (strstr($type, '/vnd.')) { | |
| $score= 0.8; | |
| } else if (str_starts_with($type, 'application/')) { | |
| $score= 0.9; | |
| } else { | |
| $score= 1.0; | |
| } | |
| $extensions[$extension]??= []; | |
| $extensions[$extension][$type]= $score; | |
| } | |
| } | |
| $in->close(); | |
| $out->writeLine(' private static $map= ['); | |
| foreach ($extensions as $extension => $types) { | |
| arsort($types); | |
| $out->writeLine(' \'.', $extension, '\' => \'', key($types), '\','); | |
| } | |
| $out->writeLine(' ];'); | |
| $out->writeLine(); | |
| // Generate accessor method | |
| $out->writeLine(<<<'METHOD' | |
| /** | |
| * Get mime type by filename | |
| * | |
| * @param string $name | |
| * @param string $default | |
| * @return string | |
| */ | |
| public static function getByFilename($name, $default= 'application/octet-stream') { | |
| $p= strrpos($name, '.'); | |
| return false === $p ? $default : self::$map[strtolower(substr($name, $p))] ?? $default; | |
| } | |
| METHOD); | |
| $out->writeLine('}'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment