Skip to content

Commit

Permalink
Move exception building to NumberFormatException
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastienDug authored and BenMorel committed Nov 29, 2023
1 parent 57a1758 commit 6380a77
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
17 changes: 3 additions & 14 deletions src/BigNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private static function _of(BigNumber|int|float|string $value) : BigNumber
if (str_contains($value, '/')) {
// Rational number
if (\preg_match(self::PARSE_REGEXP_RATIONAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
self::throwException($value);
throw NumberFormatException::invalidFormat($value);
}

$sign = $matches['sign'];
Expand All @@ -114,7 +114,7 @@ private static function _of(BigNumber|int|float|string $value) : BigNumber
} else {
// Integer or decimal number
if (\preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
self::throwException($value);
throw NumberFormatException::invalidFormat($value);
}

$sign = $matches['sign'];
Expand All @@ -124,7 +124,7 @@ private static function _of(BigNumber|int|float|string $value) : BigNumber
$exponent = $matches['exponent'];

if ($integral === null && $fractional === null) {
self::throwException($value);
throw NumberFormatException::invalidFormat($value);
}

if ($integral === null) {
Expand Down Expand Up @@ -159,17 +159,6 @@ private static function _of(BigNumber|int|float|string $value) : BigNumber
}
}

/**
* Throws a NumberFormatException for the given value.
* @psalm-pure
*/
private static function throwException(string $value) : never {
throw new NumberFormatException(\sprintf(
'The given value "%s" does not represent a valid number.',
$value
));
}

/**
* Overridden by subclasses to convert a BigNumber to an instance of the subclass.
*
Expand Down
10 changes: 9 additions & 1 deletion src/Exception/NumberFormatException.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
*/
class NumberFormatException extends MathException
{
public static function invalidFormat(string $value) : self
{
return new self(\sprintf(
'The given value "%s" does not represent a valid number.',
$value,
));
}

/**
* @param string $char The failing character.
*
Expand All @@ -28,6 +36,6 @@ public static function charNotInAlphabet(string $char) : self
$char = '"' . $char . '"';
}

return new self(sprintf('Char %s is not a valid character in the given alphabet.', $char));
return new self(\sprintf('Char %s is not a valid character in the given alphabet.', $char));
}
}

0 comments on commit 6380a77

Please sign in to comment.