|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace WebservicesNl\Utils; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class FormatUtils. |
|
7
|
|
|
*/ |
|
8
|
|
|
class FormatUtils |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var array |
|
12
|
|
|
*/ |
|
13
|
|
|
protected static $formats = [ |
|
14
|
|
|
'decimal' => [ // SI Prefixes (decimal) |
|
15
|
|
|
'mod' => 1000, |
|
16
|
|
|
'units' => ['B', 'kB', 'MB', 'GB', 'TB', 'PB'], |
|
17
|
|
|
], |
|
18
|
|
|
'binary' => [ // IEC prefixes (binary) |
|
19
|
|
|
'mod' => 1024, |
|
20
|
|
|
'units' => ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'], |
|
21
|
|
|
], |
|
22
|
|
|
]; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Return a formatted string (from bytes) in decimal or binary. |
|
26
|
|
|
* |
|
27
|
|
|
* @param int|string|float $size |
|
28
|
|
|
* @param int $precision |
|
29
|
|
|
* @param string $format either binary or decimal |
|
30
|
|
|
* |
|
31
|
|
|
* @throws \InvalidArgumentException |
|
32
|
|
|
* |
|
33
|
|
|
* @return string |
|
34
|
|
|
*/ |
|
35
|
2 |
|
public static function formatBytes($size, $precision = 0, $format = 'decimal') |
|
36
|
|
|
{ |
|
37
|
2 |
|
if (!array_key_exists($format, self::$formats)) { |
|
38
|
1 |
|
throw new \InvalidArgumentException('Not a valid format'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
1 |
|
$format = self::$formats[$format]; |
|
42
|
1 |
|
$precision = (int) $precision; |
|
43
|
|
|
|
|
44
|
|
|
/** @var float $base */ |
|
45
|
1 |
|
$base = log((float) $size, $format['mod']); |
|
46
|
1 |
|
$key = (int) floor($base); |
|
47
|
|
|
|
|
48
|
1 |
|
$value = round(pow($format['mod'], $base - floor($base)), $precision); |
|
49
|
|
|
|
|
50
|
1 |
|
return sprintf('%.' . $precision . 'f %s', $value, $format['units'][$key]); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|