Completed
Push — master ( 226b43...36df15 )
by Cedric
59s
created

ShortenNums::readableBillion()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
dl 12
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Stonec0der\ShortenNums;
4
5
/**
6
 *
7
 * ShortenNums Class
8
 *
9
 * Created 14/01/2020
10
 * Author: Cedric Megnie N. (Stonec0der).
11
 * Email: [email protected]
12
 *
13
 * This Class function is to shorten some number and return shorter form
14
 * It convert 1000 to 1k, 10000 to 10K, 1050 to 1k and 10500 to 10.5k
15
 * You can shorten from 1000 up to 1000000000000 => 1B (1 billion).
16
 *
17
 * Licence: MIT
18
 */
19
class ShortenNums
20
{
21
	// TODO:  Add method to use $value / 999 for 999-999999 to return 0.9K instead of rounded it to 1K
22
    /**
23
     * 
24
     * @var array Max supported numbers.
25
     */
26
    private static $tresholds = [
27
        'K' => '999999',
28
        'M' => '999999999',
29
        'B'	=> '999999999999',
30
        'T' => '999899999999930',
31
    ];
32
    /**
33
     * 
34
     * @var array
35
     */
36
    private static $formats = [
37
        'K'	=> 1000,
38
        'M'	=> 1000000,
39
        'B'	=> 1000000000,
40
        'T' => 1000000000000,
41
    ];
42
43
	/**
44
	 * Convert long number to readable Numbers 1000 => 1K
45
	 * 
46
	 * @param int|string $value This should be pass as a string for now.
47
	 * @param int $precision Number of number after decimal point.
48
	 * @return string
49
	 */
50
	public static function readableNumber($value, $precision = 1): string
51
	{
52
		$clean_number = '';
53
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
54
		if (self::isNotValid($value))
55
			return self::notSupported($value);
56
		$suffix = '';
57
		foreach(self::$tresholds as $suffix => $treshold) {
58
			if ($value < $treshold) {
59
				$clean_number = $value / self::$formats[$suffix];
60
				break;
61
			}
62
		}
63
		$formated_number = number_format($clean_number, config('shorten-nums.precision') ?? $precision);
64
65
		return (preg_match('/\d\.0{1,}$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
66
	}
67
68
	/**
69
	 * Convert 1000 => 1K, 10000 => 10K & 1000000 => 100K
70
	 * 
71
	 * @param  int|string $value
72
	 * @param int $precision Number of number after decimal point.
73
	 * @return string 	A string number formated as 1K-1.5K
74
	 */		
75 View Code Duplication
	public static function readableThousand($value, $precision = 1): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
	{
77
		$range = [999, 999999];
78
		$suffix = 'K';
79
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
80
		self::validateRange($value, $range);
81
82
		$clean_number = $value / self::$formats[$suffix];
83
		$formated_number = number_format($clean_number, config('shorten-nums.precision') ?? $precision);
84
85
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
86
	}
87
88
	/**
89
	 * Convert 1,000,000 place to 1M
90
	 * @param  int|string $value
91
	 * @param int $precision Number of number after decimal point.
92
	 */
93 View Code Duplication
	public static function readableMillion($value, $precision = 1): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
	{
95
		$range = [999999, 999999999];
96
		$suffix = 'M';
97
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
98
		self::validateRange($value, $range);
99
100
		$clean_number = $value / self::$formats[$suffix];
101
		$formated_number = number_format($clean_number, config('shorten-nums.precision') ?? $precision);
102
103
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
104
	}
105
106
	/**
107
	 * Convert 1000,000,000 place to 1B
108
	 * @param  int|string $value
109
	 * @param int $precision Number of number after decimal point.
110
	 */
111 View Code Duplication
	public static function readableBillion($value, $precision = 1): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
	{
113
		$range = [999999999, 999999999999];
114
		$suffix = 'B';
115
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
116
		self::validateRange($value, $range);
117
118
		$clean_number = $value / self::$formats[$suffix];
119
		$formated_number = number_format($clean_number, config('shorten-nums.precision') ?? $precision);
120
121
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;  
122
	}
123
124
	/**
125
	 * Convert 1,000,000,000,000 place to 1T
126
	 * @param  int|string $value
127
	 * @param int $precision Number of number after decimal point.
128
	 */
129 View Code Duplication
	public static function readableTrillion($value, $precision = 1): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
	{
131
		$range = [999999999999, 999899999999930];
132
		$suffix = 'T';
133
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
134
		self::validateRange($value, $range);
135
136
		$clean_number = $value / self::$formats[$suffix];
137
		$formated_number = number_format($clean_number, config('shorten-nums.precision') ?? $precision);
138
139
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix; 
140
	}
141
142
143
	/**
144
	 * The Current value is not yet suppoerted, typically it greater than the supported values
145
	 * @param  int|string $value the invalid number
146
	 */
147
	private static function notSupported($value): string
148
	{
149
		if ($value < 999) {
150
			return $value;
151
		}
152
		else{
153
			return '999+T';
154
		}
155
	}
156
157
	/**
158
	 * Validate number
159
	 * @param int|string $value
160
	 */
161
	private static function isNotValid($value)
162
	{
163
		// Accept only integers and string with valid integers.
164
    	if (!is_int((int)$value) || !preg_match('/((?!(0\d))^[\d]+)$/i', (string)$value))
165
    		throw new \Exception("TypeError: $value is not a valid integer", 1);
166
		//  TODO:  Allow negative numbers
167
		if (($value < 999) || ($value >= 999899999999930)) {
168
			return true;
169
		}
170
		return false;
171
	}
172
173
	/**
174
	 * @param int|string $value
175
	 * @param array $range
176
	 */
177
	private static function validateRange($value, $range)
178
	{
179
		// Accept only integers and string with valid integers.
180
		if (!is_int((int)$value))
181
			throw new \Exception("TypeError: $value is not a valid integer", 1);
182
		// Should not start with 0. Also check the number length
183
		if (!preg_match('/((?!(0\d))^[\d]+)$/i', (string)$value))
184
			throw new \Exception("Error: $value is not valid, value should not start with 0", 1);
185
		if ((int)$value < $range[0] || (int)$value >= $range[1])
186
			throw new \Exception("Error: The provided value \"$value\" is not in the range of \"$range[0]-$range[1]\".");
187
	}
188
}
189