misuzu/utility.php

72 lines
2.1 KiB
PHP
Raw Normal View History

<?php
use Index\Colour\Colour;
function byte_symbol(int $bytes, bool $decimal = false, array $symbols = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']): string {
2020-05-18 21:27:34 +00:00
if($bytes < 1)
return '0 B';
$divider = $decimal ? 1000 : 1024;
$exp = floor(log($bytes) / log($divider));
2020-05-18 21:27:34 +00:00
$bytes = $bytes / pow($divider, $exp);
$symbol = $symbols[$exp];
return sprintf("%.2f %s%sB", $bytes, $symbol, $symbol !== '' && !$decimal ? 'i' : '');
}
2020-10-06 22:07:47 +02:00
function get_country_name(string $code, string $locale = 'en'): string {
$code = strtolower($code);
switch($code) {
2018-03-22 02:56:41 +00:00
case 'xx':
return 'Unknown';
case 'a1':
return 'Anonymous Proxy';
case 'a2':
return 'Satellite Provider';
2020-10-06 22:07:47 +02:00
case 'cn':
return 'West Taiwan';
case 'xm':
return 'The Moon';
2018-03-22 02:56:41 +00:00
default:
2020-10-06 22:07:47 +02:00
return \Locale::getDisplayRegion("-{$code}", $locale);
2018-03-22 02:56:41 +00:00
}
}
// 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
2019-06-10 19:04:53 +02:00
function render_error(int $code, string $template = 'errors.%d'): string {
2018-08-07 00:19:35 +02:00
return render_info(null, $code, $template);
}
2019-06-10 19:04:53 +02:00
function render_info(?string $message, int $httpCode, string $template = 'errors.%d'): string {
2018-08-07 00:19:35 +02:00
http_response_code($httpCode);
2022-08-11 23:28:45 +00:00
\Misuzu\Template::set('http_code', $httpCode);
2018-08-07 00:19:35 +02:00
2022-08-11 23:28:45 +00:00
if(!empty($message))
\Misuzu\Template::set('message', $message);
2018-08-07 00:19:35 +02:00
2022-08-11 23:28:45 +00:00
$template = sprintf($template, $httpCode);
2018-08-07 00:19:35 +02:00
2022-08-11 23:28:45 +00:00
return \Misuzu\Template::renderRaw(sprintf($template, $httpCode));
}
2018-07-06 03:28:06 +02:00
function html_colour(int|null|Colour $colour, $attribs = '--user-colour'): string {
$colour = (string)($colour instanceof Colour ? $colour : Colour::fromMisuzu($colour ?? 0x40000000));
2018-07-23 15:31:36 +02:00
if(is_string($attribs))
$attribs = [ $attribs => '%s' ];
2018-09-23 16:42:15 +02:00
if(!$attribs)
2018-09-23 16:42:15 +02:00
$attribs = [
'color' => '%s',
'--user-colour' => '%s',
];
2018-07-06 03:28:06 +02:00
$css = '';
foreach($attribs as $name => $format)
$css .= $name . ':' . sprintf($format, $colour) . ';';
2018-07-06 03:28:06 +02:00
return $css;
}