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

Commit 37b1c6c

Browse files
committed
Decreased Decimal::fromString complexity
1 parent 6dfe303 commit 37b1c6c

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

src/Decimal.php

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

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

193-
$dec_scale = $scale !== null ?
194-
$scale :
195-
(isset($captures[4]) ? max(0, strlen($captures[4])-1) : 0);
192+
$min_scale = isset($captures[4]) ?
193+
max(0, strlen($captures[4])-1) :
194+
0;
196195

197196
} elseif (preg_match('/([+\-]?)0*([0-9](\.[0-9]+)?)[eE]([+\-]?)([1-9][0-9]*)/', $strValue, $captures) === 1) {
198197

199-
// Now it's time to "unroll" the exponential notation to basic positional notation
200-
$sign = self::normalizeSign($captures[1]);
201-
$mantissa = $captures[2];
202-
203198
$mantissa_scale = max(strlen($captures[3])-1, 0);
204199

205200
$exp_val = (int)$captures[5];
@@ -212,20 +207,31 @@ public static function fromString($strValue, $scale = null)
212207
$tmp_multiplier = bcpow(10, -$exp_val, $exp_val);
213208
}
214209

215-
$value = $sign . bcmul($mantissa, $tmp_multiplier, max($min_scale, $scale !== null ? $scale : 0));
216-
$dec_scale = $scale !== null ? $scale : $min_scale;
210+
$value = self::normalizeSign($captures[1]) . bcmul(
211+
$captures[2],
212+
$tmp_multiplier,
213+
max(
214+
$min_scale,
215+
$scale !== null ? $scale : 0
216+
)
217+
);
217218

218219
} else {
219220
throw new \InvalidArgumentException(
220221
'$strValue must be a string that represents uniquely a float point number.'
221222
);
222223
}
223224

224-
if ($scale !== null) {
225-
$value = self::innerRound($value, $scale);
225+
if ($scale!==null) {
226+
$dec_scale = $scale;
227+
} else {
228+
$dec_scale = $min_scale;
226229
}
227230

228-
return new Decimal($value, $dec_scale);
231+
return new Decimal(
232+
self::innerRound($value, $dec_scale),
233+
$dec_scale
234+
);
229235
}
230236

231237
/**

0 commit comments

Comments
 (0)