misuzu/utility.php

72 lines
2.1 KiB
PHP
Raw Normal View History

2022-09-13 13:14:49 +00:00
<?php
use Index\Colour\Colour;
2022-09-13 13:14:49 +00:00
function byte_symbol(int $bytes, bool $decimal = false, array $symbols = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']): string {
if($bytes < 1)
return '0 B';
$divider = $decimal ? 1000 : 1024;
$exp = floor(log($bytes) / log($divider));
$bytes = $bytes / pow($divider, $exp);
$symbol = $symbols[$exp];
return sprintf("%.2f %s%sB", $bytes, $symbol, $symbol !== '' && !$decimal ? 'i' : '');
}
function get_country_name(string $code, string $locale = 'en'): string {
$code = strtolower($code);
switch($code) {
case 'xx':
return 'Unknown';
case 'a1':
return 'Anonymous Proxy';
case 'a2':
return 'Satellite Provider';
case 'cn':
return 'West Taiwan';
case 'xm':
return 'The Moon';
default:
return \Locale::getDisplayRegion("-{$code}", $locale);
}
}
// render_error, render_info and render_info_or_json should be redone a bit better
// following a uniform format so there can be a global handler for em
function render_error(int $code, string $template = 'errors.%d'): string {
return render_info(null, $code, $template);
}
function render_info(?string $message, int $httpCode, string $template = 'errors.%d'): string {
http_response_code($httpCode);
\Misuzu\Template::set('http_code', $httpCode);
if(!empty($message))
\Misuzu\Template::set('message', $message);
$template = sprintf($template, $httpCode);
return \Misuzu\Template::renderRaw(sprintf($template, $httpCode));
}
function html_colour(int|null|Colour $colour, $attribs = '--user-colour'): string {
$colour = (string)($colour instanceof Colour ? $colour : Colour::fromMisuzu($colour ?? 0x40000000));
2022-09-13 13:14:49 +00:00
if(is_string($attribs))
$attribs = [ $attribs => '%s' ];
2022-09-13 13:14:49 +00:00
if(!$attribs)
2022-09-13 13:14:49 +00:00
$attribs = [
'color' => '%s',
'--user-colour' => '%s',
];
$css = '';
foreach($attribs as $name => $format)
$css .= $name . ':' . sprintf($format, $colour) . ';';
2022-09-13 13:14:49 +00:00
return $css;
}