Skip to content
This repository was archived by the owner on Dec 27, 2023. It is now read-only.

Commit 1aee926

Browse files
committed
Decreased Decimal::fromString complexity
1 parent 2e74981 commit 1aee926

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/Decimal.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public static function fromString($strValue, $scale = null)
186186
if (preg_match('/^([+\-]?)0*(([1-9][0-9]*|[0-9])(\.[0-9]+)?)$/', $strValue, $captures) === 1) {
187187

188188
// Now it's time to strip leading zeros in order to normalize inner values
189-
$sign = $captures[1];
189+
$sign = self::normalizeSign($captures[1]);
190190
$value = $sign . $captures[2];
191191

192192
$dec_scale = $scale !== null ?
@@ -196,15 +196,14 @@ public static function fromString($strValue, $scale = null)
196196
} elseif (preg_match('/([+\-]?)([0-9](\.[0-9]+)?)[eE]([+\-]?)([1-9][0-9]*)/', $strValue, $captures) === 1) {
197197

198198
// Now it's time to "unroll" the exponential notation to basic positional notation
199-
$sign = $captures[1];
199+
$sign = self::normalizeSign($captures[1]);
200200
$mantissa = $captures[2];
201201

202202
$mantissa_scale = strlen($captures[3]) > 0 ? strlen($captures[3])-1 : 0;
203203

204-
$exp_sign = ($captures[4]==='') ? '+' : $captures[4];
205204
$exp_val = (int)$captures[5];
206205

207-
if ($exp_sign === '+') {
206+
if (self::normalizeSign($captures[4]) === '') {
208207
$min_scale = ($mantissa_scale-$exp_val > 0) ? $mantissa_scale-$exp_val : 0;
209208
$tmp_multiplier = bcpow(10, $exp_val);
210209
} else {
@@ -804,6 +803,15 @@ private static function paramsValidation($value, $scale)
804803
}
805804
}
806805

806+
private static function normalizeSign($sign)
807+
{
808+
if ($sign==='+') {
809+
return '';
810+
}
811+
812+
return $sign;
813+
}
814+
807815
/**
808816
* @return string
809817
*/

tests/Decimal/DecimalFromStringTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,17 @@ public function testExponentialNotationString_With_NegativeExponent_And_Negative
6767
);
6868
}
6969

70+
public function testSimpleNotation_With_Positive_Sign()
71+
{
72+
$this->assertTrue(
73+
Decimal::fromString('+34')->equals(Decimal::fromString('34'))
74+
);
75+
76+
$this->assertTrue(
77+
Decimal::fromString('+00034')->equals(Decimal::fromString('34'))
78+
);
79+
}
80+
7081
/**
7182
* @expectedException Litipk\Exceptions\InvalidArgumentTypeException
7283
* @expectedExceptionMessage $strVlue must be of type string.

0 commit comments

Comments
 (0)