Conversion::bytesToHumans()   B
last analyzed

Complexity

Conditions 10
Paths 6

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 19
ccs 15
cts 15
cp 1
rs 7.6666
cc 10
nc 6
nop 2
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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