xp-framework / core

The XP Framework is an all-purpose, object oriented PHP framework.
Other
19 stars 6 forks source link

Support image/x-icon #264

Closed thekid closed 3 years ago

thekid commented 3 years ago

image

See https://github.com/xp-framework/core/blob/master/src/main/php/util/MimeType.class.php

thekid commented 3 years ago

We could generate the util.MimeType class from https://cdn.jsdelivr.net/gh/jshttp/mime-db@latest/db.json, which is what PHP does for its sapi/cli/mime_type_map.h

thekid commented 3 years ago

We could generate the util.MimeType class

<?php namespace tools;

use peer\http\HttpConnection from 'xp-framework/http';
use text\json\StreamInput from 'xp-forge/json';

use util\cmd\Console;

$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  xp://net.xp_framework.unittest.util.MimeTypeTest
 */
abstract class MimeType {
DECLARATION);

// Generate lookup map
$out->writeLine('  private static $map= [');
$in= new StreamInput($r->in());
foreach ($in->pairs() as $type => $value) {
  if (!isset($value['extensions'])) continue;

  foreach ($value['extensions'] as $extension) {
    $out->writeLIne('    \'.', $extension, '\' => \'', $type, '\',');
  }
}
$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('}');
thekid commented 3 years ago
$ xp -w '\util\MimeType::getByFilename("favicon.ico")'
image/x-icon
thekid commented 3 years ago

Released in https://github.com/xp-framework/core/releases/tag/v10.9.0