CluPilotCloud/app/Support/Bytes.php

27 lines
701 B
PHP

<?php
namespace App\Support;
/**
* Byte counts for humans. WireGuard reports raw octets, and an operator
* scanning a table needs "1,4 GB", not 1503238553.
*/
final class Bytes
{
public static function human(int $bytes, int $decimals = 1): string
{
if ($bytes < 1024) {
return $bytes.' B';
}
$units = ['kB', 'MB', 'GB', 'TB', 'PB'];
$power = min((int) floor(log($bytes, 1024)), count($units));
$value = $bytes / (1024 ** $power);
// Whole numbers read better without a trailing ",0".
$decimals = $value >= 100 ? 0 : $decimals;
return number_format($value, $decimals, ',', '.').' '.$units[$power - 1];
}
}