1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ElegantMedia\PHPToolkit; |
4
|
|
|
|
5
|
|
|
class Conversion |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Convert bytes to a human readable format. |
9
|
|
|
* |
10
|
|
|
* @see http://codeaid.net/php/convert-size-in-bytes-to-a-human-readable-format-(php) |
11
|
|
|
* |
12
|
|
|
* @param int $bytes |
13
|
|
|
* @param int $precision |
14
|
|
|
* |
15
|
|
|
* @return string |
16
|
|
|
*/ |
17
|
|
|
public static function bytesToHumans(int $bytes, $precision = 2): ?string |
18
|
|
|
{ |
19
|
6 |
|
$kilobyte = 1024; |
20
|
|
|
$megabyte = 1048576; // $kilobyte * 1024; |
21
|
6 |
|
$gigabyte = 1073741824; // $megabyte * 1024; |
22
|
6 |
|
$terabyte = 1099511627776; // $gigabyte * 1024; |
23
|
6 |
|
|
24
|
6 |
|
if (($bytes >= 0) && ($bytes < $kilobyte)) { |
25
|
|
|
return $bytes . ' B'; |
26
|
6 |
|
} elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) { |
27
|
6 |
|
return round($bytes / $kilobyte, $precision) . ' KB'; |
28
|
6 |
|
} elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) { |
29
|
3 |
|
return round($bytes / $megabyte, $precision) . ' MB'; |
30
|
6 |
|
} elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) { |
31
|
6 |
|
return round($bytes / $gigabyte, $precision) . ' GB'; |
32
|
6 |
|
} elseif ($bytes >= $terabyte) { |
33
|
6 |
|
return round($bytes / $terabyte, $precision) . ' TB'; |
34
|
6 |
|
} else { |
35
|
6 |
|
return $bytes . ' B'; |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Converts a string with numbers to a full number. |
41
|
|
|
* |
42
|
|
|
* @param $string |
43
|
|
|
* |
44
|
|
|
* @return int |
45
|
|
|
*/ |
46
|
|
|
public static function stringToInt($string): int |
47
|
|
|
{ |
48
|
|
|
return (int) round(floatval(preg_replace('/[^0-9.]/', '', $string))); |
49
|
3 |
|
} |
50
|
|
|
|
51
|
3 |
|
/** |
52
|
|
|
* Convert a string numeric to a float |
53
|
|
|
* Eg: 1,232.12 -> becomes -> (float) 1232.12. |
54
|
|
|
* |
55
|
|
|
* @param $value |
56
|
|
|
* |
57
|
|
|
* @return float |
58
|
|
|
*/ |
59
|
|
|
public static function stringToFloat($value): float |
60
|
|
|
{ |
61
|
|
|
return (float) (filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|