forked from alexjustesen/speedtest-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber.php
More file actions
82 lines (67 loc) · 2.31 KB
/
Number.php
File metadata and controls
82 lines (67 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace App\Helpers;
use Illuminate\Support\Number as SupportNumber;
class Number extends SupportNumber
{
/**
* Cast the given value to the type specified.
*/
public static function castToType(mixed $value, string $type): mixed
{
if (is_null($value)) {
return null;
}
settype($value, $type);
return $value;
}
/**
* Convert the given number to a specific bit order of magnitude.
*/
public static function bitsToMagnitude(int|float $bits, int $precision = 0, string $magnitude = 'kbit'): float
{
$value = match ($magnitude) {
'kbit' => $bits * 1000,
'mbit' => $bits * pow(1000, -2),
'gbit' => $bits * pow(1000, -3),
'tbit' => $bits * pow(1000, -4),
'pbit' => $bits * pow(1000, -5),
'ebit' => $bits * pow(1000, -6),
'zbit' => $bits * pow(1000, -7),
'ybit' => $bits * pow(1000, -8),
default => $bits,
};
return round(num: $value, precision: $precision);
}
/**
* Convert the given number to its largest bit order of magnitude.
*
* Reference: https://en.wikipedia.org/wiki/Bit
*/
public static function bitsToHuman(int|float $bits, int $precision = 0, ?int $maxPrecision = null): string
{
$units = ['B', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'];
if ($bits === 0) {
return '0 B';
}
for ($i = 0; ($bits / 1000) > 0.99 && ($i < count($units) - 1); $i++) {
$bits /= 1000;
}
return sprintf('%s %s', static::format($bits, $precision, $maxPrecision), $units[$i]);
}
/**
* Convert the given number to its largest bit rate order of magnitude.
*
* Reference: https://en.wikipedia.org/wiki/Bit_rate
*/
public static function toBitRate(int|float $bits, int $precision = 0, ?int $maxPrecision = null): string
{
$units = ['Bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps'];
if ($bits === 0) {
return '0 B';
}
for ($i = 0; ($bits / 1000) > 0.99 && ($i < count($units) - 1); $i++) {
$bits /= 1000;
}
return sprintf('%s %s', static::format($bits, $precision, $maxPrecision), $units[$i]);
}
}