Completed
Push — master ( 80d642...269232 )
by Cedric
01:52 queued 11s
created

ShortenNums::isNotValid()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4888
c 0
b 0
f 0
cc 5
nc 4
nop 1
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' => '999999999999000',
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 formatNumber($value, $precision): 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
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,$precision);
64
65
		return (preg_match('/\d\.0$/', $formated_number)) ? rtrim(rtrim($formated_number,'0'), '.').$suffix : $formated_number.$suffix;
0 ignored issues
show
Bug introduced by
The variable $suffix seems to be defined by a foreach iteration on line 57. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
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 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...
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,$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 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...
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,$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 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...
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,$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 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...
130
	{
131
		$range = [999999999999, 999999999999000];
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,$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))
165
    		throw new \Exception("TypeError: $value is not a valid integer", 1);
166
    	// Should not start with 0. Also check the number length
167
    	if (!preg_match('/((?!(0))^[\d]+)$/i', (string)$value))
168
    		throw new \Exception("Error: $value is not valid, value should not start with 0", 1);
169
		//  TODO:  Allow negative numbers
170
		if (($value < 999) || ($value > 999999999999000)) {
171
			return true;
172
		}
173
		return false;
174
	}
175
176
	/**
177
	 * @param int|string $value
178
	 * @param mixed $range
179
	 */
180
	private static function validateRange($value, $range)
181
	{
182
		// Accept only integers and string with valid integers.
183
		if (!is_int((int)$value))
184
			throw new \Exception("TypeError: $value is not a valid integer", 1);
185
		// Should not start with 0. Also check the number length
186
		if (!preg_match('/((?!(0))^[\d]+)$/i', (string)$value))
187
			throw new \Exception("Error: $value is not valid, value should not start with 0", 1);
188
		if ((int)$value < $range[0] || (int)$value > $range[1])
189
			throw new \Exception("Error: The provided value \"$value\" is not in the range of \"$range[0]-$range[1]\".");
190
	}
191
}
192