Completed
Pull Request — master (#1)
by Cedric
02:53 queued 01:24
created

ShortenNums   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 188
Duplicated Lines 35.11 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 0
dl 66
loc 188
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A formatThousand() 18 18 2
A formatNumber() 0 22 4
A formatMillion() 16 16 2
A formatBillion() 16 16 2
A formatTrillion() 16 16 2
A notSupported() 0 4 1
A validateNumber() 0 13 4
A validateRange() 0 5 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
	//private static $thousand_format;
22
	//private static $million_format;
23
	//private static $billion_format;
24
	//private static $trillion_format;
25
	// TODO:  Add method to use $value / 999 for 999-999999 to return 0.9K instead of rounded it to 1K
26
    /**
27
     * 
28
     * @var array Max supported numbers.
29
     */
30
    private static $tresholds = [
31
        'K' => '999999',
32
        'M' => '999999999',
33
        'B'	=> '999999999999',
34
        'T' => '999999999999000',
35
    ];
36
    /**
37
     * 
38
     * @var array
39
     */
40
    private static $formats = [
41
        'K'	=> 1000,
42
        'M'	=> 1000000,
43
        'B'	=> 1000000000,
44
        'T' => 1000000000000,
45
    ];
46
47
	/**
48
	 * Convert long number to readable Numbers 1000 => 1K
49
	 * 
50
	 * @param string $value This should be pass as a string for now.
51
	 * @param int $precision Number of number after decimal point.
52
	 * @return string
53
	 */
54
	public static function formatNumber($value, $precision): string
55
	{
56
		// $treshold2 = 999; // If you want 0.9k for 999
57
		$suffix = '';
58
		$clean_number = '';
59
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
60
		self::validateNumber($value);
61
		self::validateRange($value, $range);
0 ignored issues
show
Bug introduced by
The variable $range does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
62
		foreach(self::$tresholds as $suffix => $treshold) {
63
			if ($value < $treshold) {
64
				//if (isset(self::$thousand_format))
65
				//	$clean_number = $value / self::$thousand_format;
66
				$clean_number = $value / self::$formats[$suffix];
67
				// Round and format number
68
				//die(var_dump($clean_number, $formats[$suffix]));
69
				break;
70
			}
71
		}
72
		$formated_number = number_format($clean_number,$precision);
73
74
		return (preg_match('/\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
75
	}
76
77
	/**
78
	 * Convert 1000 => 1K, 10000 => 10K & 1000000 => 100K
79
	 * 
80
	 * @param  string $value
81
	 * @param int $precision Number of number after decimal point.
82
	 * @return string 	A string number formated as 1K-1.5K
83
	 */		
84 View Code Duplication
	public static function formatThousand($value, $precision): 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...
85
	{
86
		//$format = 1000; // If you dont wnat 0.9k but straight 1k for 999
87
		// $treshold2 = 999; // If you want 0.9k for 999
88
		$range = [999, 999999];
89
		$suffix = 'K';
90
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
91
		self::validateNumber($value);
92
		self::validateRange($value, $range);
93
94
		//if (isset(self::$thousand_format))
95
		//	$clean_number = $value / self::$thousand_format;
96
		$clean_number = $value / self::$format[$suffix];
97
		// Round and format number
98
		$formated_number = number_format($clean_number,$precision);
99
100
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
101
	}
102
103
	/**
104
	 * Convert 1,000,000 place to 1M
105
	 * @param  string $value
106
	 * @param int $precision Number of number after decimal point.
107
	 * @return string 	A string number formated as 1M-1.5M
108
	 */
109 View Code Duplication
	public static function formatMillion($value, $precision): 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...
110
	{
111
		$range = [999999, 999999999];
112
		$suffix = 'M';
113
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
114
		self::validateNumber($value);
115
		self::validateRange($value, $range);
116
117
		//if (isset(self::$million_format))
118
		//	$clean_number = $value / self::$million_format;
119
		$clean_number = $value / self::$formats[$suffix];
120
		// Round and format number
121
		$formated_number = number_format($clean_number,$precision);
122
123
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
124
	}
125
126
	/**
127
	 * Convert 1000,000,000 place to 1B
128
	 * @param  string $value
129
	 * @param int $precision Number of number after decimal point.
130
	 * @return string 	A string number formated as 1B-1.5B
131
	 */
132 View Code Duplication
	public static function formatBillion($value, $precision): 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...
133
	{
134
		$range = [999999999, 999999999999];
135
		$suffix = 'B';
136
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
137
		self::validateNumber($value);
138
		self::validateRange($value, $range);
139
140
		//if (isset(self::$billion_format))
141
		//	$clean_number = $value / self::$billion_format;
142
		$clean_number = $value / self::$formats[$suffix];
143
		// Round and format number
144
		$formated_number = number_format($clean_number,$precision);
145
146
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;  
147
	}
148
149
	/**
150
	 * Convert 1,000,000,000,000 place to 1T
151
	 * @param  string $value
152
	 * @param int $precision Number of number after decimal point.
153
	 * @return string 	A string number formated as 1B-1.5B
154
	 */
155 View Code Duplication
	public static function formatTrillion($value, $precision): 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...
156
	{
157
		$range = [999999999999, 999999999999000];
158
		$suffix = 'T';
159
		// Check if value is a valid integer and does not start with 0, and force user to pass value as string
160
		self::validateNumber($value);
161
		self::validateRange($value, $range);
162
163
		//if (isset(self::$trillion_format))
164
		//	$clean_number = $value / self::$trillion_format;
165
		$clean_number = $value / self::$formats[$suffix];
166
		// Round and format number
167
		$formated_number = number_format($clean_number,$precision);
168
169
		return (preg_match('/\\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix; 
170
	}
171
172
173
	/**
174
	 * The Current value is not yet suppoerted, typically it greater than the supported values
175
	 * @param  string $value the invalid number
176
	 * @return string
177
	 */
178
	private static function notSupported($value): string
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
179
	{
180
	    return 'Sorry ' . $value . ' is not Supported!';
181
	}
182
183
	/**
184
	 * Validate number
185
	 * @param string $value
186
	 */
187
	private static function validateNumber($value)
188
	{
189
		// Tis temporary enforce that the pass value should be pass as string of an integer instead non quoted integer example: '1000' is valid, 1000 is not.
190
		if (!is_string($value))
191
			throw new \Exception("TypeError: $value should be pass as quoted string to avoid unespected result.", 1);
192
		// Accept only integers and string with valid integers.
193
    	if (!is_int((int)$value))
194
    		throw new \Exception("TypeError: $value is not a valid integer", 1);
195
    	// Should not start with 0. Also check the number length
196
    	if (!preg_match('/((?!(0))^[\d]+)$/i', (string)$value))
197
    		throw new \Exception("Error: $value is not valid, value should not start with 0", 1);
198
    	// Invalid number TODO:  Allow negative numbers
199
	}
200
201
	private static function validateRange($value, $range)
202
	{
203
		if ((int)$value < $range[0] || (int)$value > $range[1])
204
			throw new \Exception("Error: The provided value \"$value\" is not in the range of \"$range[0]-$range[1]\".");
205
	}
206
}
207