Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

1221
vendor/brick/math/src/BigDecimal.php vendored Normal file

File diff suppressed because it is too large Load diff

1497
vendor/brick/math/src/BigInteger.php vendored Normal file

File diff suppressed because it is too large Load diff

911
vendor/brick/math/src/BigNumber.php vendored Normal file
View file

@ -0,0 +1,911 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\IntegerOverflowException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\PlatformException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Math\Internal\Safe;
use JsonSerializable;
use Override;
use Stringable;
use function array_is_list;
use function assert;
use function filter_var;
use function in_array;
use function is_int;
use function ltrim;
use function max;
use function preg_match;
use function str_contains;
use function str_repeat;
use function strlen;
use const FILTER_VALIDATE_INT;
use const PHP_INT_MAX;
use const PREG_UNMATCHED_AS_NULL;
/**
* Base class for arbitrary-precision numbers.
*
* This class is sealed: it is part of the public API but should not be subclassed in userland.
* Protected methods may change in any version.
*
* @phpstan-sealed BigInteger|BigDecimal|BigRational
*/
abstract readonly class BigNumber implements JsonSerializable, Stringable
{
/**
* The regular expression used to parse integer or decimal numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
* The digit quantifiers must be possessive (++): backtracking on malformed input could exhaust
* pcre.backtrack_limit, surfacing as PlatformException instead of NumberFormatException.
*/
private const PARSE_REGEXP_NUMERICAL =
'/^' .
'(?<sign>[\-\+])?' .
'(?<integral>[0-9]++)?' .
'(?<point>\.)?' .
'(?<fractional>[0-9]++)?' .
'(?:[eE](?<exponent>[\-\+]?[0-9]++))?' .
'\z/';
/**
* The regular expression used to parse rational numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
* The digit quantifiers must be possessive (++): backtracking on malformed input could exhaust
* pcre.backtrack_limit, surfacing as PlatformException instead of NumberFormatException.
*/
private const PARSE_REGEXP_RATIONAL =
'/^' .
'(?<sign>[\-\+])?' .
'(?<numerator>[0-9]++)' .
'\/' .
'(?<denominator>[0-9]++)' .
'\z/';
/**
* Creates a BigNumber of the given value.
*
* When of() is called on BigNumber, the concrete return type is dependent on the given value, with the following
* rules:
*
* - BigNumber instances are returned as is
* - integer numbers are returned as BigInteger
* - strings containing a `/` character are returned as BigRational
* - strings containing a `.` character or using an exponential notation are returned as BigDecimal
* - strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger
*
* When of() is called on BigInteger, BigDecimal, or BigRational, the resulting number is converted to an instance
* of the subclass when possible; otherwise a RoundingNecessaryException is thrown.
*
* When parsing untrusted input, use {@see parse()} instead.
*
* @throws NumberFormatException If the input is a string, and the format of the number is not valid.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
*
* @pure
*/
final public static function of(BigNumber|int|string $value): static
{
$value = self::_of($value);
if ($value instanceof static) {
// No conversion needed.
return $value;
}
return static::from($value);
}
/**
* Creates a BigNumber of the given value, or returns null if the input is null.
*
* Behaves like {@see of()} for non-null values.
*
* When parsing untrusted input, use {@see parseNullable()} instead.
*
* @throws NumberFormatException If the input is a string, and the format of the number is not valid.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
*
* @pure
*/
final public static function ofNullable(BigNumber|int|string|null $value): ?static
{
if ($value === null) {
return null;
}
return static::of($value);
}
/**
* Creates a BigNumber of the given string, limiting the allowed syntax and the number of digits.
*
* This method is designed to safely parse untrusted input: huge strings, and exponential notation that allows a
* short string such as `1e1000000000` to expand to gigabytes of memory.
*
* The $allowedSyntax parameter restricts the accepted notations: plain integers such as `123` are always accepted,
* then each NumberSyntax case allows one additional feature: DecimalPoint, Exponent, Fraction. A value is accepted
* only if every feature it uses is allowed. The NumberSyntax enum also provides constants for the most common
* combinations, from NumberSyntax::INTEGER to NumberSyntax::ALL.
*
* The $maxDigits parameter limits the number of digits, counted in each of these forms:
*
* - as written, where every digit of the input counts, including leading zeros and exponent digits: `005` counts
* 3 digits, `01e-3` counts 3, and `010/012` counts 6;
* - in its expanded form, with exponents materialized and leading zeros trimmed: `01e-3` counts 4 (`0.001`);
* - in its converted form, when called on a subclass, as written by toString(): `BigDecimal::parse('1/8', ...)`
* counts 4 digits (`0.125`), although `1/8` counts only 2.
*
* When parse() is called on BigNumber, the concrete return type is determined by the format of the string,
* following the same rules as {@see of()}. When called on a subclass, the value is converted to an instance of
* that subclass when possible.
*
* @param string $value The untrusted value to parse.
* @param list<NumberSyntax> $allowedSyntax The allowed syntax features; plain integers are always accepted.
* @param positive-int $maxDigits The maximum number of digits, as written and in the resulting number.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
* @throws InvalidArgumentException If $allowedSyntax is not a list of NumberSyntax cases, or if $maxDigits is
* less than 1.
*
* @pure
*/
final public static function parse(
string $value,
array $allowedSyntax,
int $maxDigits,
): static {
if (! array_is_list($allowedSyntax)) { // @phpstan-ignore function.alreadyNarrowedType
throw InvalidArgumentException::invalidAllowedSyntax();
}
foreach ($allowedSyntax as $syntax) {
if (! $syntax instanceof NumberSyntax) { // @phpstan-ignore instanceof.alwaysTrue
throw InvalidArgumentException::invalidAllowedSyntax();
}
}
if ($maxDigits < 1) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::nonPositiveMaxDigits();
}
$value = self::_parse($value, $allowedSyntax, $maxDigits);
if ($value instanceof static) {
// No conversion needed.
return $value;
}
$result = static::from($value);
// The conversion may expand the number (1/8 -> 0.125): the limit applies to the result as well.
if ($result->digitCount() > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
return $result;
}
/**
* Creates a BigNumber of the given string, limiting the allowed syntax and the number of digits, or returns null
* if the input is null.
*
* Behaves like {@see parse()} for non-null values.
*
* @param string|null $value The untrusted value to parse, or null.
* @param list<NumberSyntax> $allowedSyntax The allowed syntax features; plain integers are always accepted.
* @param positive-int $maxDigits The maximum number of digits, as written and in the resulting number.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
* @throws RoundingNecessaryException If the method is called on a subclass of BigNumber, and the value cannot be
* converted to an instance of the subclass without rounding.
* @throws InvalidArgumentException If $allowedSyntax is not a list of NumberSyntax cases, or if $maxDigits is
* less than 1.
*
* @pure
*/
final public static function parseNullable(
?string $value,
array $allowedSyntax,
int $maxDigits,
): ?static {
if ($value === null) {
if (! array_is_list($allowedSyntax)) { // @phpstan-ignore function.alreadyNarrowedType
throw InvalidArgumentException::invalidAllowedSyntax();
}
foreach ($allowedSyntax as $syntax) {
if (! $syntax instanceof NumberSyntax) { // @phpstan-ignore instanceof.alwaysTrue
throw InvalidArgumentException::invalidAllowedSyntax();
}
}
if ($maxDigits < 1) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::nonPositiveMaxDigits();
}
return null;
}
return static::parse($value, $allowedSyntax, $maxDigits);
}
/**
* Returns the minimum of the given values.
*
* If several values are equal and minimal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function min(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$min = static::of($a);
foreach ($n as $value) {
$value = static::of($value);
if ($value->isLessThan($min)) {
$min = $value;
}
}
return $min;
}
/**
* Returns the maximum of the given values.
*
* If several values are equal and maximal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function max(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$max = static::of($a);
foreach ($n as $value) {
$value = static::of($value);
if ($value->isGreaterThan($max)) {
$max = $value;
}
}
return $max;
}
/**
* Returns the sum of the given values.
*
* When called on BigNumber, sum() accepts any supported type and returns a result whose type is the widest among
* the given values (BigInteger < BigDecimal < BigRational).
*
* When called on BigInteger, BigDecimal, or BigRational, sum() requires that all values can be converted to that
* specific subclass, and returns a result of the same type.
*
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function sum(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$sum = static::of($a);
foreach ($n as $value) {
$sum = self::add($sum, static::of($value));
}
assert($sum instanceof static);
return $sum;
}
/**
* Checks if this number is equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) === 0;
}
/**
* Checks if this number is strictly less than the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isLessThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) < 0;
}
/**
* Checks if this number is less than or equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isLessThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) <= 0;
}
/**
* Checks if this number is strictly greater than the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isGreaterThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) > 0;
}
/**
* Checks if this number is greater than or equal to the given one.
*
* @throws MathException If the given number is not valid.
*
* @pure
*/
final public function isGreaterThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) >= 0;
}
/**
* Checks if this number equals zero.
*
* @pure
*/
final public function isZero(): bool
{
return $this->getSign() === 0;
}
/**
* Checks if this number is strictly negative.
*
* @pure
*/
final public function isNegative(): bool
{
return $this->getSign() < 0;
}
/**
* Checks if this number is negative or zero.
*
* @pure
*/
final public function isNegativeOrZero(): bool
{
return $this->getSign() <= 0;
}
/**
* Checks if this number is strictly positive.
*
* @pure
*/
final public function isPositive(): bool
{
return $this->getSign() > 0;
}
/**
* Checks if this number is positive or zero.
*
* @pure
*/
final public function isPositiveOrZero(): bool
{
return $this->getSign() >= 0;
}
/**
* Returns the absolute value of this number.
*
* @pure
*/
final public function abs(): static
{
return $this->isNegative() ? $this->negated() : $this;
}
/**
* Returns the negated value of this number.
*
* @pure
*/
abstract public function negated(): static;
/**
* Returns the sign of this number.
*
* Returns -1 if the number is negative, 0 if zero, 1 if positive.
*
* @return -1|0|1
*
* @pure
*/
abstract public function getSign(): int;
/**
* Compares this number to the given one.
*
* Returns -1 if `$this` is lower than, 0 if equal to, 1 if greater than `$that`.
*
* @return -1|0|1
*
* @throws MathException If the number is not valid.
*
* @pure
*/
abstract public function compareTo(BigNumber|int|string $that): int;
/**
* Limits (clamps) this number between the given minimum and maximum values.
*
* If the number is lower than $min, returns $min.
* If the number is greater than $max, returns $max.
* Otherwise, returns this number unchanged.
*
* @param BigNumber|int|string $min The minimum. Must be convertible to an instance of the class this method is called on.
* @param BigNumber|int|string $max The maximum. Must be convertible to an instance of the class this method is called on.
*
* @throws MathException If min/max are not convertible to an instance of the class this method is called on.
* @throws InvalidArgumentException If min is greater than max.
*
* @pure
*/
final public function clamp(BigNumber|int|string $min, BigNumber|int|string $max): static
{
$min = static::of($min);
$max = static::of($max);
if ($min->isGreaterThan($max)) {
throw InvalidArgumentException::minGreaterThanMax();
}
if ($this->isLessThan($min)) {
return $min;
}
if ($this->isGreaterThan($max)) {
return $max;
}
return $this;
}
/**
* Converts this number to a BigInteger.
*
* @throws RoundingNecessaryException If this number cannot be converted to a BigInteger without rounding.
*
* @pure
*/
abstract public function toBigInteger(): BigInteger;
/**
* Converts this number to a BigDecimal.
*
* @throws RoundingNecessaryException If this number cannot be converted to a BigDecimal without rounding.
*
* @pure
*/
abstract public function toBigDecimal(): BigDecimal;
/**
* Converts this number to a BigRational.
*
* @pure
*/
abstract public function toBigRational(): BigRational;
/**
* Converts this number to a BigDecimal with the given scale, using rounding if necessary.
*
* @param non-negative-int $scale The scale of the resulting `BigDecimal`. Must be non-negative.
* @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
*
* @throws InvalidArgumentException If the scale is negative.
* @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and this number cannot be converted to
* the given scale without rounding.
*
* @pure
*/
abstract public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal;
/**
* Returns the exact value of this number as a native integer.
*
* If this number cannot be converted to a native integer without losing precision, an exception is thrown.
* Note that the acceptable range for an integer depends on the platform and differs for 32-bit and 64-bit.
*
* @throws RoundingNecessaryException If this number cannot be converted to an integer without rounding.
* @throws IntegerOverflowException If this number is too large to fit in a native integer.
*
* @pure
*/
abstract public function toInt(): int;
/**
* Returns an approximation of this number as a floating-point value.
*
* Note that this method can discard information as the precision of a floating-point value
* is inherently limited.
*
* If the number is greater than the largest representable floating point number, positive infinity is returned.
* If the number is less than the smallest representable floating point number, negative infinity is returned.
* This method never returns NaN.
*
* @pure
*/
abstract public function toFloat(): float;
/**
* Returns a string representation of this number.
*
* The output of this method can be parsed by the `of()` factory method; this will yield an object equal to this
* one, but possibly of a different type if instantiated through `BigNumber::of()`.
*
* @return non-empty-string
*
* @pure
*/
abstract public function toString(): string;
/**
* @return non-empty-string
*/
#[Override]
final public function jsonSerialize(): string
{
return $this->toString();
}
/**
* @return non-empty-string
*
* @pure
*/
#[Override]
final public function __toString(): string
{
return $this->toString();
}
/**
* Overridden by subclasses to convert a BigNumber to an instance of the subclass.
*
* @throws RoundingNecessaryException If the value cannot be converted.
*
* @pure
*/
abstract protected static function from(BigNumber $number): static;
/**
* Returns the number of digits in this number, as written by toString().
*
* @pure
*/
abstract protected function digitCount(): int;
/**
* Proxy method to access BigInteger's protected constructor from sibling classes.
*
* @internal
*
* @pure
*/
final protected function newBigInteger(string $value): BigInteger
{
return new BigInteger($value);
}
/**
* Proxy method to access BigDecimal's protected constructor from sibling classes.
*
* @internal
*
* @param non-negative-int $scale
*
* @pure
*/
final protected function newBigDecimal(string $value, int $scale = 0): BigDecimal
{
return new BigDecimal($value, $scale);
}
/**
* Proxy method to access BigRational's protected constructor from sibling classes.
*
* @internal
*
* @pure
*/
final protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify): BigRational
{
return new BigRational($numerator, $denominator, $checkDenominator, $simplify);
}
/**
* @throws NumberFormatException If the format of the number is not valid.
*
* @pure
*/
private static function _of(BigNumber|int|string $value): BigNumber
{
if ($value instanceof BigNumber) {
return $value;
}
if (is_int($value)) {
return new BigInteger((string) $value);
}
return self::_parse($value, null, null);
}
/**
* Note: $allowedSyntax and $maxDigits are nullable as a performance optimization for of(): null behaves like
* `NumberSyntax::ALL` and `PHP_INT_MAX`, but skips the checks, which could never fail against those values.
*
* @param list<NumberSyntax>|null $allowedSyntax The allowed syntax features; plain integers are always accepted. Null for all.
* @param positive-int|null $maxDigits The maximum number of digits, as written and in the resulting number. Null for no limit.
*
* @throws NumberFormatException If the format of $value is invalid, if it uses a syntax that is not allowed
* by $allowedSyntax, or if it has more than $maxDigits digits.
*
* @pure
*/
private static function _parse(string $value, ?array $allowedSyntax, ?int $maxDigits): BigNumber
{
if ($value === '') {
throw NumberFormatException::emptyNumber();
}
if (str_contains($value, '/')) {
// Rational number
$result = preg_match(self::PARSE_REGEXP_RATIONAL, $value, $matches, PREG_UNMATCHED_AS_NULL);
if ($result === false) {
throw PlatformException::pcreFailure();
}
if ($result === 0) {
throw NumberFormatException::invalidFormat($value);
}
if ($allowedSyntax !== null && ! in_array(NumberSyntax::Fraction, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::Fraction);
}
$sign = $matches['sign'];
$numerator = self::cleanUp($sign, $matches['numerator']);
$denominator = self::cleanUp(null, $matches['denominator']);
if ($denominator === '0') {
throw NumberFormatException::zeroDenominator();
}
// The digit count is taken as written, before trimming zeros and before simplification:
// the final count will always be less or equal.
if ($maxDigits !== null && strlen($matches['numerator']) + strlen($matches['denominator']) > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
return new BigRational(
new BigInteger($numerator),
new BigInteger($denominator),
false,
true,
);
}
// Integer or decimal number
$result = preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL);
if ($result === false) {
throw PlatformException::pcreFailure();
}
if ($result === 0) {
throw NumberFormatException::invalidFormat($value);
}
$sign = $matches['sign'];
$point = $matches['point'];
$integral = $matches['integral'];
$fractional = $matches['fractional'];
$exponent = $matches['exponent'];
if ($integral === null && $fractional === null) {
throw NumberFormatException::invalidFormat($value);
}
if ($integral === null) {
$integral = '0';
}
if ($point === null && $exponent === null) {
// Integer number.
if ($maxDigits !== null && strlen($integral) > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
$integral = self::cleanUp($sign, $integral);
return new BigInteger($integral);
}
// Decimal number.
if ($allowedSyntax !== null) {
if ($point !== null && ! in_array(NumberSyntax::DecimalPoint, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::DecimalPoint);
}
if ($exponent !== null && ! in_array(NumberSyntax::Exponent, $allowedSyntax, true)) {
throw NumberFormatException::syntaxNotAllowed(NumberSyntax::Exponent);
}
}
if ($exponent === null) {
$exponent = 0;
} else {
$exponentSign = $exponent[0] === '-' ? '-' : '';
$exponent = ltrim(ltrim($exponent, '+-'), '0');
if ($exponent === '') {
$exponent = 0;
} else {
$exponent = filter_var($exponentSign . $exponent, FILTER_VALIDATE_INT);
if ($exponent === false) {
throw NumberFormatException::exponentTooLarge();
}
}
}
$fractional ??= '';
$unscaledValue = self::cleanUp($sign, $integral . $fractional);
$scale = strlen($fractional) - $exponent;
// @phpstan-ignore function.alreadyNarrowedType (may overflow to float)
if (! is_int($scale)) {
throw NumberFormatException::exponentTooLarge();
}
$unscaledDigits = strlen($unscaledValue) - (int) ($unscaledValue[0] === '-');
if ($scale < 0 && $unscaledValue !== '0') {
// The unscaled value is padded with -$scale zeros below.
$expandedDigits = $unscaledDigits - $scale;
} else {
// The fractional digits, plus at least a zero integer part.
$expandedDigits = max($unscaledDigits, $scale + 1);
}
// @phpstan-ignore function.alreadyNarrowedType (may overflow to float)
if (! is_int($expandedDigits)) {
throw NumberFormatException::tooManyDigits($maxDigits ?? PHP_INT_MAX);
}
if ($maxDigits !== null) {
// Digits as written: every digit of the input counts, including leading zeros and exponent digits.
$writtenDigits = strlen($matches['integral'] ?? '') + strlen($matches['fractional'] ?? '');
if ($matches['exponent'] !== null) {
$writtenDigits += strlen($matches['exponent']) - (int) ($matches['exponent'][0] === '-' || $matches['exponent'][0] === '+');
}
if ($expandedDigits > $maxDigits || $writtenDigits > $maxDigits) {
throw NumberFormatException::tooManyDigits($maxDigits);
}
}
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= str_repeat('0', Safe::neg($scale));
}
$scale = 0;
}
return new BigDecimal($unscaledValue, $scale);
}
/**
* Removes optional leading zeros and applies sign.
*
* @param '+'|'-'|null $sign The sign, optional. Null is allowed for convenience and treated as '+'.
* @param non-empty-string $number The number, validated as a string of digits.
*
* @pure
*/
private static function cleanUp(?string $sign, string $number): string
{
$number = ltrim($number, '0');
if ($number === '') {
return '0';
}
return $sign === '-' ? '-' . $number : $number;
}
/**
* Adds two BigNumber instances in the correct order to avoid a RoundingNecessaryException.
*
* @pure
*/
private static function add(BigNumber $a, BigNumber $b): BigNumber
{
if ($a instanceof BigRational) {
return $a->plus($b);
}
if ($b instanceof BigRational) {
return $b->plus($a);
}
if ($a instanceof BigDecimal) {
return $a->plus($b);
}
if ($b instanceof BigDecimal) {
return $b->plus($a);
}
return $a->plus($b);
}
}

605
vendor/brick/math/src/BigRational.php vendored Normal file
View file

@ -0,0 +1,605 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\DivisionByZeroException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Math\Internal\DecimalHelper;
use Brick\Math\Internal\Safe;
use LogicException;
use Override;
use function max;
use function min;
use function strlen;
use function substr;
/**
* An arbitrarily large rational number.
*
* This class is immutable.
*
* Fractions are automatically simplified to lowest terms. For example, `2/4` becomes `1/2`.
* The denominator is always strictly positive; the sign is carried by the numerator.
*/
final readonly class BigRational extends BigNumber
{
/**
* The numerator.
*/
private BigInteger $numerator;
/**
* The denominator. Always strictly positive.
*/
private BigInteger $denominator;
/**
* Protected constructor. Use a factory method to obtain an instance.
*
* @param BigInteger $numerator The numerator.
* @param BigInteger $denominator The denominator.
* @param bool $checkDenominator Whether to check the denominator for negative and zero.
* @param bool $simplify Whether to simplify the fraction to lowest terms.
*
* @throws DivisionByZeroException If the denominator is zero.
*
* @pure
*/
protected function __construct(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify)
{
if ($checkDenominator) {
if ($denominator->isZero()) {
throw DivisionByZeroException::zeroDenominator();
}
if ($denominator->isNegative()) {
$numerator = $numerator->negated();
$denominator = $denominator->negated();
}
}
if ($simplify) {
$gcd = $numerator->gcd($denominator);
$numerator = $numerator->quotient($gcd);
$denominator = $denominator->quotient($gcd);
}
$this->numerator = $numerator;
$this->denominator = $denominator;
}
/**
* Creates a BigRational out of a numerator and a denominator.
*
* If the denominator is negative, the signs of both the numerator and the denominator
* will be inverted to ensure that the denominator is always positive.
*
* @param BigNumber|int|string $numerator The numerator. Must be convertible to a BigInteger.
* @param BigNumber|int|string $denominator The denominator. Must be convertible to a BigInteger.
*
* @throws MathException If an argument is not valid, or is not convertible to a BigInteger.
* @throws DivisionByZeroException If the denominator is zero.
*
* @pure
*/
public static function ofFraction(
BigNumber|int|string $numerator,
BigNumber|int|string $denominator,
): BigRational {
$numerator = BigInteger::of($numerator);
$denominator = BigInteger::of($denominator);
return new BigRational($numerator, $denominator, true, true);
}
/**
* Returns a BigRational representing zero.
*
* @pure
*/
public static function zero(): BigRational
{
/** @var BigRational|null $zero */
static $zero;
if ($zero === null) {
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false, false);
}
return $zero;
}
/**
* Returns a BigRational representing one.
*
* @pure
*/
public static function one(): BigRational
{
/** @var BigRational|null $one */
static $one;
if ($one === null) {
$one = new BigRational(BigInteger::one(), BigInteger::one(), false, false);
}
return $one;
}
/**
* Returns a BigRational representing ten.
*
* @pure
*/
public static function ten(): BigRational
{
/** @var BigRational|null $ten */
static $ten;
if ($ten === null) {
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false, false);
}
return $ten;
}
/**
* Returns the numerator of this rational number.
*
* @pure
*/
public function getNumerator(): BigInteger
{
return $this->numerator;
}
/**
* Returns the denominator of this rational number.
*
* The denominator is always strictly positive.
*
* @pure
*/
public function getDenominator(): BigInteger
{
return $this->denominator;
}
/**
* Returns the integral part of this rational number.
*
* Examples:
*
* - `7/3` returns `2` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-2` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
public function getIntegralPart(): BigInteger
{
return $this->numerator->quotient($this->denominator);
}
/**
* Returns the fractional part of this rational number.
*
* Examples:
*
* - `7/3` returns `1/3` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-1/3` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
public function getFractionalPart(): BigRational
{
return new BigRational($this->numerator->remainder($this->denominator), $this->denominator, false, false);
}
/**
* Returns the sum of this number and the given one.
*
* @param BigNumber|int|string $that The number to add.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function plus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that;
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the difference of this number and the given one.
*
* @param BigNumber|int|string $that The number to subtract.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function minus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that->negated();
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->minus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the product of this number and the given one.
*
* @param BigNumber|int|string $that The multiplier.
*
* @throws MathException If the multiplier is not valid.
*
* @pure
*/
public function multipliedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero() || $this->isZero()) {
return BigRational::zero();
}
$numerator = $this->numerator->multipliedBy($that->numerator);
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the result of the division of this number by the given one.
*
* @param BigNumber|int|string $that The divisor.
*
* @throws MathException If the divisor is not valid.
* @throws DivisionByZeroException If the divisor is zero.
*
* @pure
*/
public function dividedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
throw DivisionByZeroException::divisionByZero();
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$denominator = $this->denominator->multipliedBy($that->numerator);
return new BigRational($numerator, $denominator, true, true);
}
/**
* Returns this number exponentiated to the given value.
*
* Unlike BigInteger and BigDecimal, BigRational supports negative exponents:
* the result is the reciprocal raised to the absolute value of the exponent.
*
* @throws DivisionByZeroException If the exponent is negative and this number is zero.
*
* @pure
*/
public function power(int $exponent): BigRational
{
if ($exponent === 0) {
return BigRational::one();
}
if ($exponent === 1) {
return $this;
}
if ($exponent < 0) {
if ($this->isZero()) {
throw DivisionByZeroException::zeroToNegativePower();
}
return $this->reciprocal()->power(Safe::neg($exponent));
}
return new BigRational(
$this->numerator->power($exponent),
$this->denominator->power($exponent),
false,
false,
);
}
/**
* Returns the reciprocal of this BigRational.
*
* The reciprocal has the numerator and denominator swapped.
*
* @throws DivisionByZeroException If this number is zero.
*
* @pure
*/
public function reciprocal(): BigRational
{
if ($this->isZero()) {
throw DivisionByZeroException::reciprocalOfZero();
}
return new BigRational($this->denominator, $this->numerator, true, false);
}
#[Override]
public function negated(): static
{
return new BigRational($this->numerator->negated(), $this->denominator, false, false);
}
#[Override]
public function compareTo(BigNumber|int|string $that): int
{
$that = BigRational::of($that);
if ($this->denominator->isEqualTo($that->denominator)) {
return $this->numerator->compareTo($that->numerator);
}
return $this->numerator
->multipliedBy($that->denominator)
->compareTo($that->numerator->multipliedBy($this->denominator));
}
#[Override]
public function getSign(): int
{
return $this->numerator->getSign();
}
#[Override]
public function toBigInteger(): BigInteger
{
if ($this->denominator->isEqualTo(1)) {
return $this->numerator;
}
throw RoundingNecessaryException::rationalNotConvertibleToInteger();
}
#[Override]
public function toBigDecimal(): BigDecimal
{
$scale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($scale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale)->strippedOfTrailingZeros();
}
#[Override]
public function toBigRational(): BigRational
{
return $this;
}
#[Override]
public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
{
if ($scale < 0) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::negativeScale();
}
if ($roundingMode === RoundingMode::Unnecessary) {
$requiredScale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($requiredScale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
if ($requiredScale > $scale) {
throw RoundingNecessaryException::rationalScaleTooSmall();
}
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode);
}
#[Override]
public function toInt(): int
{
return $this->toBigInteger()->toInt();
}
#[Override]
public function toFloat(): float
{
if ($this->denominator->isEqualTo(1)) {
return $this->numerator->toFloat();
}
// Avoid $this->numerator->toFloat() / $this->denominator->toFloat(): converting both operands to float first
// adds an extra rounding step before the division and can change the final float. Instead, divide in decimal
// first and convert the resulting decimal approximation to float once.
// We need ~17 significant digits for double precision (we use 20 for some margin). Since $scale controls
// decimal places (not significant digits), we subtract the estimated order of magnitude so that large results
// use fewer decimal places and small results use more (to look past leading zeros). Clamped to [0, 350] as
// doubles range from e-324 to e308 (350 ≈ 324 + 20 significant digits + margin).
$magnitude = strlen($this->numerator->abs()->toString()) - strlen($this->denominator->toString());
$scale = min(350, max(0, 20 - $magnitude));
$result = $this->numerator
->toBigDecimal()
->dividedBy($this->denominator, $scale, RoundingMode::HalfEven)
->toFloat();
// Preserve the sign when the decimal approximation underflows to zero.
if ($result === 0.0 && $this->numerator->isNegative()) {
return -0.0;
}
return $result;
}
#[Override]
public function toString(): string
{
$numerator = $this->numerator->toString();
$denominator = $this->denominator->toString();
if ($denominator === '1') {
return $numerator;
}
return $numerator . '/' . $denominator;
}
/**
* Returns the decimal representation of this rational number, with repeating decimals in parentheses.
*
* WARNING: This method is unbounded.
* The length of the repeating decimal period can be as large as `denominator - 1`.
* For fractions with large denominators, this method can use excessive memory and CPU time.
* For example, `1/100019` has a repeating period of 100,018 digits.
*
* Examples:
*
* - `10/3` returns `3.(3)`
* - `171/70` returns `2.4(428571)`
* - `1/2` returns `0.5`
*
* @return non-empty-string
*
* @pure
*/
public function toRepeatingDecimalString(): string
{
if ($this->isZero()) {
return '0';
}
$sign = $this->numerator->isNegative() ? '-' : '';
$numerator = $this->numerator->abs();
$denominator = $this->denominator;
$integral = $numerator->quotient($denominator);
$remainder = $numerator->remainder($denominator);
$integralString = $integral->toString();
if ($remainder->isZero()) {
return $sign . $integralString;
}
$digits = '';
$remainderPositions = [];
$index = 0;
while (! $remainder->isZero()) {
$remainderString = $remainder->toString();
if (isset($remainderPositions[$remainderString])) {
$repeatIndex = $remainderPositions[$remainderString];
$nonRepeating = substr($digits, 0, $repeatIndex);
$repeating = substr($digits, $repeatIndex);
return $sign . $integralString . '.' . $nonRepeating . '(' . $repeating . ')';
}
$remainderPositions[$remainderString] = $index;
$remainder = $remainder->multipliedBy(10);
$digits .= $remainder->quotient($denominator)->toString();
$remainder = $remainder->remainder($denominator);
$index++;
}
return $sign . $integralString . '.' . $digits;
}
/**
* This method is required for serializing the object and SHOULD NOT be accessed directly.
*
* @internal
*
* @return array{numerator: BigInteger, denominator: BigInteger}
*/
public function __serialize(): array
{
return ['numerator' => $this->numerator, 'denominator' => $this->denominator];
}
/**
* This method is only here to allow unserializing the object and cannot be accessed directly.
*
* @internal
*
* @param array{numerator: BigInteger, denominator: BigInteger} $data
*
* @throws LogicException
*/
public function __unserialize(array $data): void
{
if (isset($this->numerator)) {
throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
}
$this->numerator = $data['numerator'];
$this->denominator = $data['denominator'];
}
#[Override]
protected static function from(BigNumber $number): static
{
return $number->toBigRational();
}
#[Override]
protected function digitCount(): int
{
$count = $this->numerator->digitCount();
// Mirrors toString(), which does not write a denominator of 1.
if ($this->denominator->toString() === '1') {
return $count;
}
return $count + $this->denominator->digitCount();
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a division by zero occurs.
*/
final class DivisionByZeroException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function divisionByZero(): self
{
return new self('Division by zero.');
}
/**
* @internal
*
* @pure
*/
public static function zeroModulus(): self
{
return new self('The modulus must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function zeroDenominator(): self
{
return new self('The denominator of a rational number must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function reciprocalOfZero(): self
{
return new self('The reciprocal of zero is undefined.');
}
/**
* @internal
*
* @pure
*/
public static function zeroToNegativePower(): self
{
return new self('Cannot raise zero to a negative power.');
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Brick\Math\BigInteger;
use RuntimeException;
use function sprintf;
use const PHP_INT_MAX;
use const PHP_INT_MIN;
/**
* Exception thrown when a native integer overflow occurs.
*/
final class IntegerOverflowException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function integerOutOfRange(BigInteger $value): self
{
$message = '%s is out of range [%d, %d] and cannot be represented as an integer.';
return new self(sprintf($message, $value->toString(), PHP_INT_MIN, PHP_INT_MAX));
}
/**
* @internal
*
* @pure
*/
public static function nativeIntegerOverflow(string $expression): self
{
return new self(sprintf(
'Cannot compute %s because the result is outside the native integer range [%d, %d].',
$expression,
PHP_INT_MIN,
PHP_INT_MAX,
));
}
}

View file

@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use function sprintf;
/**
* Exception thrown when an invalid argument is provided.
*/
final class InvalidArgumentException extends \InvalidArgumentException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function baseOutOfRange(int $base): self
{
return new self(sprintf('Base %d is out of range [2, 36].', $base));
}
/**
* @internal
*
* @pure
*/
public static function negativeScale(): self
{
return new self('The scale must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitIndex(): self
{
return new self('The bit index must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitCount(): self
{
return new self('The bit count must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function alphabetTooShort(): self
{
return new self('The alphabet must contain at least 2 characters.');
}
/**
* @internal
*
* @pure
*/
public static function duplicateCharsInAlphabet(): self
{
return new self('The alphabet must not contain duplicate characters.');
}
/**
* @internal
*
* @pure
*/
public static function minGreaterThanMax(): self
{
return new self('The minimum value must be less than or equal to the maximum value.');
}
/**
* @internal
*
* @pure
*/
public static function cannotConvertFloat(string $type): self
{
return new self(sprintf('Cannot convert %s to a BigDecimal.', $type));
}
/**
* @internal
*
* @pure
*/
public static function negativeExponent(): self
{
return new self('The exponent must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeModulus(): self
{
return new self('The modulus must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function nonPositiveNthRootDegree(): self
{
return new self('The degree of an nth root must be a positive integer.');
}
/**
* @internal
*
* @pure
*/
public static function nonPositiveMaxDigits(): self
{
return new self('The maximum number of digits must be a positive integer.');
}
/**
* @internal
*
* @pure
*/
public static function invalidAllowedSyntax(): self
{
return new self('The allowed syntax must be a list of NumberSyntax cases.');
}
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Throwable;
/**
* Base interface for all math exceptions.
*/
interface MathException extends Throwable
{
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to perform an unsupported operation, such as a square root, on a negative number.
*/
final class NegativeNumberException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function squareRootOfNegativeNumber(): self
{
return new self('Cannot calculate the square root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function nthRootOfNegativeNumber(): self
{
return new self('Cannot take an even nth root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function toArbitraryBaseOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to an arbitrary base.');
}
/**
* @internal
*
* @pure
*/
public static function unsignedBytesOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to a byte string in unsigned mode.');
}
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to compute a modular inverse that does not exist.
*/
final class NoInverseException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function noModularInverse(): self
{
return new self('This number has no multiplicative inverse modulo the given modulus (they are not coprime).');
}
}

View file

@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use Brick\Math\NumberSyntax;
use RuntimeException;
use function ord;
use function sprintf;
use function strlen;
use function substr;
/**
* Exception thrown when attempting to create a number from a string with an invalid format.
*/
final class NumberFormatException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function invalidFormat(string $value): self
{
return new self(sprintf(
'Value "%s" does not represent a valid number.',
self::truncateAndEscape($value),
));
}
/**
* @internal
*
* @param string $char The failing character.
*
* @pure
*/
public static function charNotInAlphabet(string $char): self
{
return new self(sprintf(
'Character "%s" is not valid in the given alphabet.',
self::escapeChar($char),
));
}
/**
* @internal
*
* @pure
*/
public static function charNotValidInBase(string $char, int $base): self
{
return new self(sprintf(
'Character "%s" is not valid in base %d.',
self::escapeChar($char),
$base,
));
}
/**
* @internal
*
* @pure
*/
public static function emptyNumber(): self
{
return new self('The number must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function emptyByteString(): self
{
return new self('The byte string must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function exponentTooLarge(): self
{
return new self('The exponent is too large to be represented as an integer.');
}
/**
* @internal
*
* @pure
*/
public static function tooManyDigits(int $maxDigits): self
{
return new self(sprintf(
'The number exceeds the maximum number of %d digits.',
$maxDigits,
));
}
/**
* @internal
*
* @pure
*/
public static function syntaxNotAllowed(NumberSyntax $syntax): self
{
return new self(sprintf('The %s syntax is not allowed.', match ($syntax) {
NumberSyntax::DecimalPoint => 'decimal point',
NumberSyntax::Exponent => 'exponent',
NumberSyntax::Fraction => 'fraction',
}));
}
/**
* @internal
*
* @pure
*/
public static function zeroDenominator(): self
{
return new self('The denominator of a rational number must not be zero.');
}
/**
* @pure
*/
private static function truncateAndEscape(string $value): string
{
if (strlen($value) > 40) {
$value = substr($value, 0, 40) . '...';
}
$escaped = '';
$length = strlen($value);
for ($i = 0; $i < $length; $i++) {
$escaped .= self::escapeChar($value[$i]);
}
return $escaped;
}
/**
* @pure
*/
private static function escapeChar(string $char): string
{
$ord = ord($char);
return match (true) {
$char === "\t" => '\t',
$char === "\n" => '\n',
$char === "\r" => '\r',
$char === '\\' => '\\\\',
$char === '"' => '\"',
$ord < 32 || $ord > 126 => sprintf('\x%02X', $ord),
default => $char,
};
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use function preg_last_error_msg;
use function sprintf;
use const PHP_INT_SIZE;
/**
* Exception thrown when the current PHP platform does not support a required feature.
*/
final class PlatformException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*
* @codeCoverageIgnore
*/
public static function unsupportedFloatFormat(): self
{
return new self('Unsupported float format: expected IEEE-754 double.');
}
/**
* @internal
*
* @pure
*
* @codeCoverageIgnore
*/
public static function unsupportedIntSize(): self
{
return new self(sprintf('Unsupported integer size: %d bytes, expected 4 or 8.', PHP_INT_SIZE));
}
/**
* @internal
*
* @pure
*/
public static function pcreFailure(): self
{
return new self(sprintf(
'PCRE regular expression matching failed: %s. Check the pcre.* ini settings.',
preg_last_error_msg(),
));
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use Throwable;
use function get_debug_type;
use function sprintf;
/**
* Exception thrown when random byte generation fails.
*/
final class RandomSourceException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message, ?Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
/**
* @internal
*
* @pure
*/
public static function randomSourceFailure(Throwable $previous): self
{
return new self('Random byte generation failed.', $previous);
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesType(mixed $value): self
{
return new self(sprintf(
'The random bytes generator must return a string, got %s.',
get_debug_type($value),
));
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesLength(int $expectedLength, int $actualLength): self
{
return new self(sprintf(
'The random bytes generator returned %d byte(s), expected %d.',
$actualLength,
$expectedLength,
));
}
}

View file

@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a number cannot be represented at the requested scale without rounding.
*/
final class RoundingNecessaryException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function decimalScaleTooSmall(): self
{
return new self('This decimal number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalScaleTooSmall(): self
{
return new self('This rational number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerDivisionNotExact(): self
{
return new self('The division has a non-zero remainder and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionNotExact(): self
{
return new self('The division yields a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionScaleTooSmall(): self
{
return new self('The division result is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootScaleTooSmall(): self
{
return new self('The square root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootScaleTooSmall(): self
{
return new self('The nth root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNotConvertibleToInteger(): self
{
return new self('This decimal number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToInteger(): self
{
return new self('This rational number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToDecimal(): self
{
return new self('This rational number has a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
}

View file

@ -0,0 +1,723 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\RoundingMode;
use function chr;
use function intdiv;
use function ltrim;
use function ord;
use function str_repeat;
use function strlen;
use function strpos;
use function strrev;
use function strtolower;
use function substr;
/**
* Performs basic operations on arbitrary size integers.
*
* Unless otherwise specified, all parameters must be validated as non-empty strings of digits,
* without leading zero, and with an optional leading minus sign if the number is not zero.
*
* Any other parameter format will lead to undefined behaviour.
* All methods must return strings respecting this format, unless specified otherwise.
*
* @internal
*/
abstract readonly class Calculator
{
/**
* The alphabet for converting from and to base 2 to 36, lowercase.
*/
public const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
/**
* Returns the absolute value of a number.
*
* @pure
*/
final public function abs(string $n): string
{
return ($n[0] === '-') ? substr($n, 1) : $n;
}
/**
* Negates a number.
*
* @pure
*/
final public function neg(string $n): string
{
if ($n === '0') {
return '0';
}
if ($n[0] === '-') {
return substr($n, 1);
}
return '-' . $n;
}
/**
* Compares two numbers.
*
* Returns -1 if the first number is less than, 0 if equal to, 1 if greater than the second number.
*
* @return -1|0|1
*
* @pure
*/
final public function cmp(string $a, string $b): int
{
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
if ($aNeg && ! $bNeg) {
return -1;
}
if ($bNeg && ! $aNeg) {
return 1;
}
$aLen = strlen($aDig);
$bLen = strlen($bDig);
if ($aLen < $bLen) {
$result = -1;
} elseif ($aLen > $bLen) {
$result = 1;
} else {
$result = $aDig <=> $bDig;
}
return $aNeg ? -$result : $result;
}
/**
* Adds two numbers.
*
* @pure
*/
abstract public function add(string $a, string $b): string;
/**
* Subtracts two numbers.
*
* @pure
*/
abstract public function sub(string $a, string $b): string;
/**
* Multiplies two numbers.
*
* @pure
*/
abstract public function mul(string $a, string $b): string;
/**
* Returns the quotient of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return string The quotient.
*
* @pure
*/
abstract public function divQ(string $a, string $b): string;
/**
* Returns the remainder of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return string The remainder.
*
* @pure
*/
abstract public function divR(string $a, string $b): string;
/**
* Returns the quotient and remainder of the division of two numbers.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
*
* @return array{string, string} An array containing the quotient and remainder.
*
* @pure
*/
abstract public function divQR(string $a, string $b): array;
/**
* Exponentiates a number.
*
* @param string $a The base number.
* @param int $e The exponent, validated as a non-negative integer.
*
* @return string The power.
*
* @pure
*/
abstract public function pow(string $a, int $e): string;
/**
* @param string $b The modulus; must not be zero.
*
* @pure
*/
public function mod(string $a, string $b): string
{
return $this->divR($this->add($this->divR($a, $b), $b), $b);
}
/**
* Returns the modular multiplicative inverse of $x modulo $m.
*
* If $x has no multiplicative inverse mod m, this method must return null.
*
* This method can be overridden by the concrete implementation if the underlying library has built-in support.
*
* @param string $m The modulus; must not be negative or zero.
*
* @pure
*/
public function modInverse(string $x, string $m): ?string
{
if ($m === '1') {
return '0';
}
$modVal = $x;
if ($x[0] === '-' || ($this->cmp($this->abs($x), $m) >= 0)) {
$modVal = $this->mod($x, $m);
}
[$g, $x] = $this->gcdExtended($modVal, $m);
if ($g !== '1') {
return null;
}
return $this->mod($this->add($this->mod($x, $m), $m), $m);
}
/**
* Raises a number into power with modulo.
*
* @param string $base The base number.
* @param string $exp The exponent; must be positive or zero.
* @param string $mod The modulus; must be strictly positive.
*
* @pure
*/
abstract public function modPow(string $base, string $exp, string $mod): string;
/**
* Returns the greatest common divisor of the two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for GCD calculations.
*
* @return string The GCD, always positive, or zero if both arguments are zero.
*
* @pure
*/
public function gcd(string $a, string $b): string
{
while ($b !== '0') {
[$a, $b] = [$b, $this->divR($a, $b)];
}
return $this->abs($a);
}
/**
* Returns the least common multiple of the two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for LCM calculations.
*
* @return string The LCM, always positive, or zero if at least one argument is zero.
*
* @pure
*/
public function lcm(string $a, string $b): string
{
if ($a === '0' || $b === '0') {
return '0';
}
return $this->divQ($this->abs($this->mul($a, $b)), $this->gcd($a, $b));
}
/**
* Returns the square root of the given number, rounded down.
*
* The result is the largest x such that x² ≤ n.
* The input MUST NOT be negative.
*
* @pure
*/
abstract public function sqrt(string $n): string;
/**
* Returns the integer nth root of the given number, truncated toward zero.
*
* If $n is non-negative, the result is the largest x such that x^$k ≤ $n (floor).
* If $n is negative, $k MUST be odd, and the result is the negation of the floor root of |$n|
* (i.e., truncation toward zero: the smallest x such that x^$k ≥ $n).
*
* The caller MUST guarantee that $k ≥ 1 and that $n is non-negative when $k is even.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for nth root calculations.
*
* @param string $n The number. May be negative only when $k is odd.
* @param int $k The root degree. Must be strictly positive.
*
* @pure
*/
public function nthRoot(string $n, int $k): string
{
if ($n === '0') {
return '0';
}
$negative = ($n[0] === '-');
$m = $negative ? substr($n, 1) : $n;
if ($m === '1') {
return $negative ? '-1' : '1';
}
// Initial overshoot: 10^ceil(strlen(m)/k) is strictly greater than the true root.
// Newton-Raphson requires starting above the true root to converge monotonically down.
$x = '1' . str_repeat('0', intdiv(strlen($m) - 1, $k) + 1);
$kStr = (string) $k;
$kMinusOneStr = (string) ($k - 1);
// Newton-Raphson recurrence for integer nth root:
// x_{i+1} = floor(((k-1) * x_i + floor(m / x_i^{k-1})) / k)
for (; ;) {
$nx = $this->divQ(
$this->add(
$this->mul($kMinusOneStr, $x),
$this->divQ($m, $this->pow($x, $k - 1)),
),
$kStr,
);
if ($this->cmp($nx, $x) >= 0) {
break;
}
$x = $nx;
}
return $negative ? $this->neg($x) : $x;
}
/**
* Converts a number from an arbitrary base.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for base conversion.
*
* @param string $number The number, positive or zero, non-empty, case-insensitively validated for the given base.
* @param int $base The base of the number, validated from 2 to 36.
*
* @return string The converted number, following the Calculator conventions.
*
* @pure
*/
public function fromBase(string $number, int $base): string
{
return $this->fromArbitraryBase(strtolower($number), self::ALPHABET, $base);
}
/**
* Converts a number to an arbitrary base.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for base conversion.
*
* @param string $number The number to convert, following the Calculator conventions.
* @param int $base The base to convert to, validated from 2 to 36.
*
* @return string The converted number, lowercase.
*
* @pure
*/
public function toBase(string $number, int $base): string
{
$negative = ($number[0] === '-');
if ($negative) {
$number = substr($number, 1);
}
$number = $this->toArbitraryBase($number, self::ALPHABET, $base);
if ($negative) {
return '-' . $number;
}
return $number;
}
/**
* Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
*
* @param string $number The number to convert, validated as a non-empty string,
* containing only chars in the given alphabet/base.
* @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
* @param int $base The base of the number, validated from 2 to alphabet length.
*
* @return string The number in base 10, following the Calculator conventions.
*
* @pure
*/
final public function fromArbitraryBase(string $number, string $alphabet, int $base): string
{
// remove leading "zeros"
$number = ltrim($number, $alphabet[0]);
if ($number === '') {
return '0';
}
// optimize for "one"
if ($number === $alphabet[1]) {
return '1';
}
$result = '0';
$power = '1';
$base = (string) $base;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$index = strpos($alphabet, $number[$i]);
if ($index !== 0) {
$result = $this->add(
$result,
($index === 1) ? $power : $this->mul($power, (string) $index),
);
}
if ($i !== 0) {
$power = $this->mul($power, $base);
}
}
return $result;
}
/**
* Converts a non-negative number to an arbitrary base using a custom alphabet.
*
* @param string $number The number to convert, positive or zero, following the Calculator conventions.
* @param string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.
* @param int $base The base to convert to, validated from 2 to alphabet length.
*
* @return string The converted number in the given alphabet.
*
* @pure
*/
final public function toArbitraryBase(string $number, string $alphabet, int $base): string
{
if ($number === '0') {
return $alphabet[0];
}
$base = (string) $base;
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, $base);
$remainder = (int) $remainder;
$result .= $alphabet[$remainder];
}
return strrev($result);
}
/**
* Performs a rounded division.
*
* When the remainder of the division is not zero, rounding is performed according to the rounding mode provided,
* unless RoundingMode::Unnecessary is used, in which case the method returns null.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
* @param RoundingMode $roundingMode The rounding mode.
*
* @pure
*/
final public function divRound(string $a, string $b, RoundingMode $roundingMode): ?string
{
[$quotient, $remainder] = $this->divQR($a, $b);
$hasDiscardedFraction = ($remainder !== '0');
$isPositiveOrZero = ($a[0] === '-') === ($b[0] === '-');
$discardedFractionSign = function () use ($remainder, $b): int {
$r = $this->abs($this->mul($remainder, '2'));
$b = $this->abs($b);
return $this->cmp($r, $b);
};
$lastDigitIsEven = (int) $quotient[-1] % 2 === 0;
$increment = match ($roundingMode) {
RoundingMode::Unnecessary => $hasDiscardedFraction ? null : false,
RoundingMode::Up => $hasDiscardedFraction,
RoundingMode::Down => false,
RoundingMode::Ceiling => $hasDiscardedFraction && $isPositiveOrZero,
RoundingMode::Floor => $hasDiscardedFraction && ! $isPositiveOrZero,
RoundingMode::HalfUp => $discardedFractionSign() >= 0,
RoundingMode::HalfDown => $discardedFractionSign() > 0,
RoundingMode::HalfCeiling => $isPositiveOrZero ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0,
RoundingMode::HalfFloor => $isPositiveOrZero ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0,
RoundingMode::HalfEven => $lastDigitIsEven ? $discardedFractionSign() > 0 : $discardedFractionSign() >= 0,
RoundingMode::HalfOdd => $lastDigitIsEven ? $discardedFractionSign() >= 0 : $discardedFractionSign() > 0,
};
if ($increment === null) {
return null;
}
if ($increment) {
return $isPositiveOrZero
? $this->add($quotient, '1')
: $this->sub($quotient, '1');
}
return $quotient;
}
/**
* Calculates bitwise AND of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function and(string $a, string $b): string
{
return $this->bitwise('and', $a, $b);
}
/**
* Calculates bitwise OR of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function or(string $a, string $b): string
{
return $this->bitwise('or', $a, $b);
}
/**
* Calculates bitwise XOR of two numbers.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for bitwise operations.
*
* @pure
*/
public function xor(string $a, string $b): string
{
return $this->bitwise('xor', $a, $b);
}
/**
* Extracts the sign & digits of the operands.
*
* @return array{bool, bool, string, string} Whether $a and $b are negative, followed by their digits.
*
* @pure
*/
final protected function init(string $a, string $b): array
{
return [
$aNeg = ($a[0] === '-'),
$bNeg = ($b[0] === '-'),
$aNeg ? substr($a, 1) : $a,
$bNeg ? substr($b, 1) : $b,
];
}
/**
* @param string $a Must be non-negative.
* @param string $b Must be non-negative.
*
* @return array{string, string} GCD, X
*
* @pure
*/
private function gcdExtended(string $a, string $b): array
{
// Iterative extended Euclidean algorithm; recursion would exhaust memory on large inputs.
[$r0, $r1] = [$a, $b];
[$x0, $x1] = ['1', '0'];
while ($r1 !== '0') {
[$q, $r] = $this->divQR($r0, $r1);
[$r0, $r1] = [$r1, $r];
[$x0, $x1] = [$x1, $this->sub($x0, $this->mul($q, $x1))];
}
return [$r0, $x0];
}
/**
* Performs a bitwise operation on a decimal number.
*
* @param 'and'|'or'|'xor' $operator The operator to use.
* @param string $a The left operand.
* @param string $b The right operand.
*
* @pure
*/
private function bitwise(string $operator, string $a, string $b): string
{
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$aBin = $this->toBinary($aDig);
$bBin = $this->toBinary($bDig);
$aLen = strlen($aBin);
$bLen = strlen($bBin);
if ($aLen > $bLen) {
$bBin = str_repeat("\x00", $aLen - $bLen) . $bBin;
} elseif ($bLen > $aLen) {
$aBin = str_repeat("\x00", $bLen - $aLen) . $aBin;
}
if ($aNeg) {
$aBin = $this->twosComplement($aBin);
}
if ($bNeg) {
$bBin = $this->twosComplement($bBin);
}
$value = match ($operator) {
'and' => $aBin & $bBin,
'or' => $aBin | $bBin,
'xor' => $aBin ^ $bBin,
};
$negative = match ($operator) {
'and' => $aNeg and $bNeg,
'or' => $aNeg or $bNeg,
'xor' => $aNeg xor $bNeg,
};
if ($negative) {
$value = $this->twosComplement($value);
}
$result = $this->toDecimal($value);
return $negative ? $this->neg($result) : $result;
}
/**
* @param string $number A positive, binary number.
*
* @pure
*/
private function twosComplement(string $number): string
{
$xor = str_repeat("\xff", strlen($number));
$number ^= $xor;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$byte = ord($number[$i]);
if (++$byte !== 256) {
$number[$i] = chr($byte); // @phpstan-ignore argument.type
break;
}
$number[$i] = "\x00";
if ($i === 0) {
$number = "\x01" . $number;
}
}
return $number;
}
/**
* Converts a decimal number to a binary string.
*
* @param string $number The number to convert, positive or zero, only digits.
*
* @pure
*/
private function toBinary(string $number): string
{
$result = '';
while ($number !== '0') {
[$number, $remainder] = $this->divQR($number, '256');
$result .= chr((int) $remainder); // @phpstan-ignore argument.type
}
return strrev($result);
}
/**
* Returns the positive decimal representation of a binary number.
*
* @param string $bytes The bytes representing the number.
*
* @pure
*/
private function toDecimal(string $bytes): string
{
$result = '0';
$power = '1';
for ($i = strlen($bytes) - 1; $i >= 0; $i--) {
$index = ord($bytes[$i]);
if ($index !== 0) {
$result = $this->add(
$result,
($index === 1) ? $power : $this->mul($power, (string) $index),
);
}
if ($i !== 0) {
$power = $this->mul($power, '256');
}
}
return $result;
}
}

View file

@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Internal\Calculator;
use Override;
use function bcadd;
use function bcdiv;
use function bcmod;
use function bcmul;
use function bcpow;
use function bcpowmod;
use function bcsqrt;
use function bcsub;
/**
* Calculator implementation built around the bcmath library.
*
* @internal
*/
final readonly class BcMathCalculator extends Calculator
{
#[Override]
public function add(string $a, string $b): string
{
return bcadd($a, $b, 0);
}
#[Override]
public function sub(string $a, string $b): string
{
return bcsub($a, $b, 0);
}
#[Override]
public function mul(string $a, string $b): string
{
return bcmul($a, $b, 0);
}
#[Override]
public function divQ(string $a, string $b): string
{
return bcdiv($a, $b, 0);
}
#[Override]
public function divR(string $a, string $b): string
{
return bcmod($a, $b, 0);
}
#[Override]
public function divQR(string $a, string $b): array
{
$q = bcdiv($a, $b, 0);
$r = bcmod($a, $b, 0);
return [$q, $r];
}
#[Override]
public function pow(string $a, int $e): string
{
if ($e === 0) {
return '1';
}
// bcpow() allocates memory proportional to the exponent even when the base is trivial,
// exhausting memory on 32-bit builds at large exponents.
if ($a === '0' || $a === '1') {
return $a;
}
if ($a === '-1') {
return $e % 2 === 0 ? '1' : '-1';
}
return bcpow($a, (string) $e, 0);
}
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
// normalize to Euclidean representative so modPow() stays consistent with mod()
$base = $this->mod($base, $mod);
return bcpowmod($base, $exp, $mod, 0);
}
#[Override]
public function sqrt(string $n): string
{
return bcsqrt($n, 0);
}
}

View file

@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Internal\Calculator;
use GMP;
use Override;
use function gmp_add;
use function gmp_and;
use function gmp_div_q;
use function gmp_div_qr;
use function gmp_div_r;
use function gmp_gcd;
use function gmp_init;
use function gmp_invert;
use function gmp_lcm;
use function gmp_mul;
use function gmp_or;
use function gmp_pow;
use function gmp_powm;
use function gmp_root;
use function gmp_sqrt;
use function gmp_strval;
use function gmp_sub;
use function gmp_xor;
use function substr;
/**
* Calculator implementation built around the GMP library.
*
* @internal
*/
final readonly class GmpCalculator extends Calculator
{
#[Override]
public function add(string $a, string $b): string
{
return gmp_strval(gmp_add($a, $b));
}
#[Override]
public function sub(string $a, string $b): string
{
return gmp_strval(gmp_sub($a, $b));
}
#[Override]
public function mul(string $a, string $b): string
{
return gmp_strval(gmp_mul($a, $b));
}
#[Override]
public function divQ(string $a, string $b): string
{
return gmp_strval(gmp_div_q($a, $b));
}
#[Override]
public function divR(string $a, string $b): string
{
return gmp_strval(gmp_div_r($a, $b));
}
#[Override]
public function divQR(string $a, string $b): array
{
[$q, $r] = gmp_div_qr($a, $b);
/**
* @var GMP $q
* @var GMP $r
*/
return [
gmp_strval($q),
gmp_strval($r),
];
}
#[Override]
public function pow(string $a, int $e): string
{
return gmp_strval(gmp_pow($a, $e));
}
#[Override]
public function modInverse(string $x, string $m): ?string
{
$result = gmp_invert($x, $m);
if ($result === false) {
return null;
}
return gmp_strval($result);
}
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
return gmp_strval(gmp_powm($base, $exp, $mod));
}
#[Override]
public function gcd(string $a, string $b): string
{
return gmp_strval(gmp_gcd($a, $b));
}
#[Override]
public function lcm(string $a, string $b): string
{
return gmp_strval(gmp_lcm($a, $b));
}
#[Override]
public function fromBase(string $number, int $base): string
{
return gmp_strval(gmp_init($number, $base));
}
#[Override]
public function toBase(string $number, int $base): string
{
return gmp_strval($number, $base);
}
#[Override]
public function and(string $a, string $b): string
{
return gmp_strval(gmp_and($a, $b));
}
#[Override]
public function or(string $a, string $b): string
{
return gmp_strval(gmp_or($a, $b));
}
#[Override]
public function xor(string $a, string $b): string
{
return gmp_strval(gmp_xor($a, $b));
}
#[Override]
public function sqrt(string $n): string
{
return gmp_strval(gmp_sqrt($n));
}
#[Override]
public function nthRoot(string $n, int $k): string
{
// Delegate on the absolute value and re-apply the sign ourselves so the
// truncation-toward-zero convention matches the shared Newton-Raphson fallback
// bit-for-bit, regardless of any PHP/GMP behaviour changes for negative inputs.
if ($n[0] === '-') {
return '-' . gmp_strval(gmp_root(substr($n, 1), $k));
}
return gmp_strval(gmp_root($n, $k));
}
}

View file

@ -0,0 +1,618 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal\Calculator;
use Brick\Math\Exception\PlatformException;
use Brick\Math\Internal\Calculator;
use Override;
use function assert;
use function in_array;
use function intdiv;
use function is_int;
use function ltrim;
use function str_pad;
use function str_repeat;
use function strcmp;
use function strlen;
use function substr;
use const PHP_INT_SIZE;
use const STR_PAD_LEFT;
/**
* Calculator implementation using only native PHP code.
*
* @internal
*/
final readonly class NativeCalculator extends Calculator
{
/**
* The max number of digits the platform can natively add, subtract, multiply or divide without overflow.
* For multiplication, this represents the max sum of the lengths of both operands.
*
* In addition, it is assumed that an extra digit can hold a carry (1) without overflowing.
* Example: 32-bit: max number 1,999,999,999 (9 digits + carry)
* 64-bit: max number 1,999,999,999,999,999,999 (18 digits + carry)
*/
private int $maxDigits;
/**
* @pure
*
* @codeCoverageIgnore
*/
public function __construct()
{
$this->maxDigits = match (PHP_INT_SIZE) {
4 => 9,
8 => 18, // @phpstan-ignore match.alwaysTrue
default => throw PlatformException::unsupportedIntSize(),
};
}
#[Override]
public function add(string $a, string $b): string
{
/**
* @var numeric-string $a
* @var numeric-string $b
*/
$result = $a + $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0') {
return $b;
}
if ($b === '0') {
return $a;
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig);
if ($aNeg) {
$result = $this->neg($result);
}
return $result;
}
#[Override]
public function sub(string $a, string $b): string
{
return $this->add($a, $this->neg($b));
}
#[Override]
public function mul(string $a, string $b): string
{
/**
* @var numeric-string $a
* @var numeric-string $b
*/
$result = $a * $b;
if (is_int($result)) {
return (string) $result;
}
if ($a === '0' || $b === '0') {
return '0';
}
if ($a === '1') {
return $b;
}
if ($b === '1') {
return $a;
}
if ($a === '-1') {
return $this->neg($b);
}
if ($b === '-1') {
return $this->neg($a);
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
$result = $this->doMul($aDig, $bDig);
if ($aNeg !== $bNeg) {
$result = $this->neg($result);
}
return $result;
}
#[Override]
public function divQ(string $a, string $b): string
{
return $this->divQR($a, $b)[0];
}
#[Override]
public function divR(string $a, string $b): string
{
return $this->divQR($a, $b)[1];
}
#[Override]
public function divQR(string $a, string $b): array
{
if ($a === '0') {
return ['0', '0'];
}
if ($a === $b) {
return ['1', '0'];
}
if ($b === '1') {
return [$a, '0'];
}
if ($b === '-1') {
return [$this->neg($a), '0'];
}
/** @var numeric-string $a */
$na = $a * 1; // cast to number
if (is_int($na)) {
/** @var numeric-string $b */
$nb = $b * 1;
if (is_int($nb)) {
// the only division that may overflow is PHP_INT_MIN / -1,
// which cannot happen here as we've already handled a divisor of -1 above.
$q = intdiv($na, $nb);
$r = $na % $nb;
return [
(string) $q,
(string) $r,
];
}
}
[$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b);
[$q, $r] = $this->doDiv($aDig, $bDig);
if ($aNeg !== $bNeg) {
$q = $this->neg($q);
}
if ($aNeg) {
$r = $this->neg($r);
}
return [$q, $r];
}
#[Override]
public function pow(string $a, int $e): string
{
if ($e === 0) {
return '1';
}
if ($e === 1) {
return $a;
}
$odd = $e % 2;
$e -= $odd;
$aa = $this->mul($a, $a);
$result = $this->pow($aa, $e / 2);
if ($odd === 1) {
$result = $this->mul($result, $a);
}
return $result;
}
/**
* Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/.
*/
#[Override]
public function modPow(string $base, string $exp, string $mod): string
{
// normalize to Euclidean representative so modPow() stays consistent with mod()
$base = $this->mod($base, $mod);
// special case: the algorithm below fails with power 0 mod 1 (returns 1 instead of 0)
if ($exp === '0' && $mod === '1') {
return '0';
}
$x = $base;
$res = '1';
// numbers are positive, so we can use remainder instead of modulo
$x = $this->divR($x, $mod);
while ($exp !== '0') {
if (in_array($exp[-1], ['1', '3', '5', '7', '9'])) { // odd
$res = $this->divR($this->mul($res, $x), $mod);
}
$exp = $this->divQ($exp, '2');
$x = $this->divR($this->mul($x, $x), $mod);
}
return $res;
}
/**
* Adapted from https://cp-algorithms.com/num_methods/roots_newton.html.
*/
#[Override]
public function sqrt(string $n): string
{
if ($n === '0') {
return '0';
}
// initial approximation
$x = str_repeat('9', intdiv(strlen($n), 2) ?: 1);
$decreased = false;
for (; ;) {
$nx = $this->divQ($this->add($x, $this->divQ($n, $x)), '2');
if ($x === $nx || $this->cmp($nx, $x) > 0 && $decreased) {
break;
}
$decreased = $this->cmp($nx, $x) < 0;
$x = $nx;
}
return $x;
}
/**
* Performs the addition of two non-signed large integers.
*
* @pure
*/
private function doAdd(string $a, string $b): string
{
[$a, $b, $length] = $this->pad($a, $b);
$carry = 0;
$result = '';
for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
/** @var numeric-string $blockA */
$blockA = substr($a, $i, $blockLength);
/** @var numeric-string $blockB */
$blockB = substr($b, $i, $blockLength);
$sum = (string) ($blockA + $blockB + $carry);
$sumLength = strlen($sum);
if ($sumLength > $blockLength) {
$sum = substr($sum, 1);
$carry = 1;
} else {
if ($sumLength < $blockLength) {
$sum = str_repeat('0', $blockLength - $sumLength) . $sum;
}
$carry = 0;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
if ($carry === 1) {
$result = '1' . $result;
}
return $result;
}
/**
* Performs the subtraction of two non-signed large integers.
*
* @pure
*/
private function doSub(string $a, string $b): string
{
if ($a === $b) {
return '0';
}
// Ensure that we always subtract to a positive result: biggest minus smallest.
$cmp = $this->doCmp($a, $b);
$invert = ($cmp === -1);
if ($invert) {
$c = $a;
$a = $b;
$b = $c;
}
[$a, $b, $length] = $this->pad($a, $b);
$carry = 0;
$result = '';
$complement = 10 ** $this->maxDigits;
for ($i = $length - $this->maxDigits; ; $i -= $this->maxDigits) {
$blockLength = $this->maxDigits;
if ($i < 0) {
$blockLength += $i;
$i = 0;
}
/** @var numeric-string $blockA */
$blockA = substr($a, $i, $blockLength);
/** @var numeric-string $blockB */
$blockB = substr($b, $i, $blockLength);
$sum = $blockA - $blockB - $carry;
if ($sum < 0) {
$sum += $complement;
$carry = 1;
} else {
$carry = 0;
}
$sum = (string) $sum;
$sumLength = strlen($sum);
if ($sumLength < $blockLength) {
$sum = str_repeat('0', $blockLength - $sumLength) . $sum;
}
$result = $sum . $result;
if ($i === 0) {
break;
}
}
// Carry cannot be 1 when the loop ends, as a > b
assert($carry === 0);
$result = ltrim($result, '0');
if ($invert) {
$result = $this->neg($result);
}
return $result;
}
/**
* Performs the multiplication of two non-signed large integers.
*
* @pure
*/
private function doMul(string $a, string $b): string
{
$x = strlen($a);
$y = strlen($b);
$maxDigits = intdiv($this->maxDigits, 2);
$complement = 10 ** $maxDigits;
$result = '0';
for ($i = $x - $maxDigits; ; $i -= $maxDigits) {
$blockALength = $maxDigits;
if ($i < 0) {
$blockALength += $i;
$i = 0;
}
$blockA = (int) substr($a, $i, $blockALength);
$line = '';
$carry = 0;
for ($j = $y - $maxDigits; ; $j -= $maxDigits) {
$blockBLength = $maxDigits;
if ($j < 0) {
$blockBLength += $j;
$j = 0;
}
$blockB = (int) substr($b, $j, $blockBLength);
$mul = $blockA * $blockB + $carry;
$value = $mul % $complement;
$carry = ($mul - $value) / $complement;
$value = (string) $value;
$value = str_pad($value, $maxDigits, '0', STR_PAD_LEFT);
$line = $value . $line;
if ($j === 0) {
break;
}
}
if ($carry !== 0) {
$line = $carry . $line;
}
$line = ltrim($line, '0');
if ($line !== '') {
$line .= str_repeat('0', $x - $blockALength - $i);
$result = $this->add($result, $line);
}
if ($i === 0) {
break;
}
}
return $result;
}
/**
* Performs the division of two non-signed large integers.
*
* @return string[] The quotient and remainder.
*
* @pure
*/
private function doDiv(string $a, string $b): array
{
$cmp = $this->doCmp($a, $b);
if ($cmp === -1) {
return ['0', $a];
}
$x = strlen($a);
$y = strlen($b);
// we now know that a >= b && x >= y
$q = '0'; // quotient
$r = $a; // remainder
$z = $y; // focus length, always $y or $y+1
/** @var numeric-string $b */
$nb = $b * 1; // cast to number
// performance optimization in cases where the remainder will never cause int overflow
if (is_int(($nb - 1) * 10 + 9)) {
$r = (int) substr($a, 0, $z - 1);
for ($i = $z - 1; $i < $x; $i++) {
$n = $r * 10 + (int) $a[$i];
/** @var int $nb */
$q .= intdiv($n, $nb);
$r = $n % $nb;
}
return [ltrim($q, '0') ?: '0', (string) $r];
}
for (; ;) {
$focus = substr($a, 0, $z);
$cmp = $this->doCmp($focus, $b);
if ($cmp === -1) {
if ($z === $x) { // remainder < dividend
break;
}
$z++;
}
$zeros = str_repeat('0', $x - $z);
$q = $this->add($q, '1' . $zeros);
$a = $this->sub($a, $b . $zeros);
$r = $a;
if ($r === '0') { // remainder == 0
break;
}
$x = strlen($a);
if ($x < $y) { // remainder < dividend
break;
}
$z = $y;
}
return [$q, $r];
}
/**
* Compares two non-signed large numbers.
*
* @return -1|0|1
*
* @pure
*/
private function doCmp(string $a, string $b): int
{
$x = strlen($a);
$y = strlen($b);
$cmp = $x <=> $y;
if ($cmp !== 0) {
return $cmp;
}
return strcmp($a, $b) <=> 0; // enforce -1|0|1
}
/**
* Pads the left of one of the given numbers with zeros if necessary to make both numbers the same length.
*
* The numbers must only consist of digits, without leading minus sign.
*
* @return array{string, string, int}
*
* @pure
*/
private function pad(string $a, string $b): array
{
$x = strlen($a);
$y = strlen($b);
if ($x > $y) {
$b = str_repeat('0', $x - $y) . $b;
return [$a, $b, $x];
}
if ($x < $y) {
$a = str_repeat('0', $y - $x) . $a;
return [$a, $b, $y];
}
return [$a, $b, $x];
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use function extension_loaded;
/**
* Stores the current Calculator instance used by BigNumber classes.
*
* @internal
*/
final class CalculatorRegistry
{
/**
* The Calculator instance in use.
*/
private static ?Calculator $instance = null;
/**
* Sets the Calculator instance to use.
*
* An instance is typically set only in unit tests: autodetect is usually the best option.
*
* @param Calculator|null $calculator The calculator instance, or null to revert to autodetect.
*/
final public static function set(?Calculator $calculator): void
{
self::$instance = $calculator;
}
/**
* Returns the Calculator instance to use.
*
* If none has been explicitly set, the fastest available implementation will be returned.
*
* Note: even though this method is not technically pure, it is considered pure when used in a normal context, when
* only relying on autodetect.
*
* @pure
*/
final public static function get(): Calculator
{
/** @phpstan-ignore impure.staticPropertyAccess */
if (self::$instance === null) {
/** @phpstan-ignore impure.propertyAssign */
self::$instance = self::detect();
}
/** @phpstan-ignore impure.staticPropertyAccess */
return self::$instance;
}
/**
* Returns the fastest available Calculator implementation.
*
* @pure
*
* @codeCoverageIgnore
*/
private static function detect(): Calculator
{
if (extension_loaded('gmp')) {
return new Calculator\GmpCalculator();
}
if (extension_loaded('bcmath')) {
return new Calculator\BcMathCalculator();
}
return new Calculator\NativeCalculator();
}
}

View file

@ -0,0 +1,180 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\RoundingMode;
use function ltrim;
use function rtrim;
use function str_pad;
use function str_repeat;
use function strlen;
use function substr;
use const STR_PAD_LEFT;
/**
* Shared helper for decimal operations.
*
* @internal
*/
final class DecimalHelper
{
/**
* @codeCoverageIgnore
*/
private function __construct()
{
}
/**
* Computes the scale needed to represent the exact decimal result of a reduced fraction.
*
* Returns null if the denominator has prime factors other than 2 or 5.
*
* @param string $denominator The denominator of the reduced fraction. Must be strictly positive.
*
* @return non-negative-int|null
*
* @pure
*/
public static function computeScaleFromReducedFractionDenominator(string $denominator): ?int
{
$calculator = CalculatorRegistry::get();
$d = rtrim($denominator, '0');
/** @var non-negative-int $scale rtrim can only shorten a string */
$scale = strlen($denominator) - strlen($d);
foreach ([5, 2] as $prime) {
for (; ;) {
$lastDigit = (int) $d[-1];
if ($lastDigit % $prime !== 0) {
break;
}
$d = $calculator->divQ($d, (string) $prime);
$scale++;
}
}
return $d === '1' ? $scale : null;
}
/**
* Scales an unscaled decimal value to the requested scale.
*
* Returns null when rounding is necessary and the rounding mode is Unnecessary.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
* @param RoundingMode $roundingMode The rounding mode.
*
* @return string|null The unscaled value at the target scale, or null if RoundingMode::Unnecessary is used and rounding is necessary.
*
* @pure
*/
public static function scale(string $value, int $currentScale, int $targetScale, RoundingMode $roundingMode): ?string
{
$scaled = self::tryScaleExactly($value, $currentScale, $targetScale);
if ($scaled !== null) {
return $scaled;
}
if ($roundingMode === RoundingMode::Unnecessary) {
return null;
}
$divisor = '1' . str_repeat('0', $currentScale - $targetScale);
return CalculatorRegistry::get()->divRound($value, $divisor, $roundingMode);
}
/**
* Adds leading zeros if necessary to represent the full decimal number.
*
* @param string $value The unscaled value.
* @param int $scale The current scale.
*
* @pure
*/
public static function padUnscaledValue(string $value, int $scale): string
{
$targetLength = $scale + 1;
$negative = ($value[0] === '-');
$length = strlen($value);
if ($negative) {
$length--;
}
if ($length >= $targetLength) {
return $value;
}
if ($negative) {
$value = substr($value, 1);
}
$value = str_pad($value, $targetLength, '0', STR_PAD_LEFT);
if ($negative) {
$value = '-' . $value;
}
return $value;
}
/**
* Tries to scale exactly without rounding, returning null when rounding would be required.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
*
* @return string|null The unscaled value at the target scale, or null if rounding would be required.
*
* @pure
*/
public static function tryScaleExactly(string $value, int $currentScale, int $targetScale): ?string
{
if ($value === '0' || $targetScale === $currentScale) {
return $value;
}
if ($targetScale > $currentScale) {
return $value . str_repeat('0', $targetScale - $currentScale);
}
$negative = ($value[0] === '-');
if ($negative) {
$value = substr($value, 1);
}
$value = self::padUnscaledValue($value, $currentScale);
$discardedDigits = $currentScale - $targetScale;
if (substr($value, -$discardedDigits) !== str_repeat('0', $discardedDigits)) {
return null;
}
$value = substr($value, 0, -$discardedDigits);
$value = ltrim($value, '0');
if ($value === '') {
return '0';
}
if ($negative) {
$value = '-' . $value;
}
return $value;
}
}

84
vendor/brick/math/src/Internal/Safe.php vendored Normal file
View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\Exception\IntegerOverflowException;
use function is_int;
use function sprintf;
use const PHP_INT_MIN;
/**
* Helpers for arithmetic operations that throw on native integer overflow.
*
* @internal
*/
final class Safe
{
/**
* @codeCoverageIgnore
*/
private function __construct()
{
}
/**
* @pure
*/
public static function add(int $a, int $b): int
{
$result = $a + $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d + %d', $a, $b));
}
/**
* @pure
*/
public static function sub(int $a, int $b): int
{
$result = $a - $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d - %d', $a, $b));
}
/**
* @pure
*/
public static function mul(int $a, int $b): int
{
$result = $a * $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d * %d', $a, $b));
}
/**
* @pure
*/
public static function neg(int $value): int
{
if ($value === PHP_INT_MIN) {
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('-(%d)', $value));
}
return -$value;
}
}

75
vendor/brick/math/src/NumberSyntax.php vendored Normal file
View file

@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
/**
* A syntax feature that {@see BigNumber::parse()} can accept.
*
* Plain signed integers such as `123` and `-7` are the base language: they are always accepted.
* Each case allows one additional feature:
*
* - DecimalPoint: `.`
* - Exponent: `e` or `E`
* - Fraction: `/`
*
* In addition to its cases, this enum provides list constants for the most common combinations, from INTEGER to ALL.
*/
enum NumberSyntax
{
/**
* Allows the decimal point: `1.5`, `.5`, `1.`.
*/
case DecimalPoint;
/**
* Allows the exponent: `5e3`, `15E-2`.
*/
case Exponent;
/**
* Allows the fraction form: `2/4`. The numerator and denominator are unsigned integers; an optional sign
* precedes the whole fraction.
*/
case Fraction;
/**
* Integers only: `123`.
* The base language, with no additional notation.
*/
public const INTEGER = [];
/**
* Integers and decimal numbers: `123`, `123.45`.
* Typical for monetary input.
*/
public const DECIMAL = [
self::DecimalPoint,
];
/**
* Integers and decimal numbers, with exponents: `123`, `123.45`, `1.5e-3`.
* Accepts every JSON number.
*/
public const SCIENTIFIC = [
self::DecimalPoint,
self::Exponent,
];
/**
* Integers and fractions: `123`, `22/7`.
*/
public const RATIONAL = [
self::Fraction,
];
/**
* The full syntax accepted by {@see BigNumber::of()}: `123`, `123.45`, `1.5e-3`, `22/7`.
*/
public const ALL = [
self::DecimalPoint,
self::Exponent,
self::Fraction,
];
}

147
vendor/brick/math/src/RoundingMode.php vendored Normal file
View file

@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
namespace Brick\Math;
/**
* Specifies rounding behavior by defining how discarded digits affect the returned result when an exact value cannot
* be represented at the requested scale.
*/
enum RoundingMode
{
/**
* Asserts that the requested operation has an exact result, hence no rounding is necessary.
*
* If this rounding mode is specified on an operation that yields a result that
* cannot be represented at the requested scale, a RoundingNecessaryException is thrown.
*
* Equivalent native PHP rounding mode: none.
*/
case Unnecessary;
/**
* Rounds away from zero.
*
* Always increments the digit prior to a nonzero discarded fraction.
* Note that this rounding mode never decreases the magnitude of the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::AwayFromZero}.
*/
case Up;
/**
* Rounds towards zero.
*
* Never increments the digit prior to a discarded fraction (i.e., truncates).
* Note that this rounding mode never increases the magnitude of the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::TowardsZero}.
*/
case Down;
/**
* Rounds towards positive infinity.
*
* If the result is positive, behaves as for Up; if negative, behaves as for Down.
* Note that this rounding mode never decreases the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::PositiveInfinity}.
*/
case Ceiling;
/**
* Rounds towards negative infinity.
*
* If the result is positive, behaves as for Down; if negative, behaves as for Up.
* Note that this rounding mode never increases the calculated value.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::NegativeInfinity}.
*/
case Floor;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
*
* Behaves as for Up if the discarded fraction is >= 0.5; otherwise, behaves as for Down.
* Note that this is the rounding mode commonly taught at school.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfAwayFromZero}.
*/
case HalfUp;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
*
* Behaves as for Up if the discarded fraction is > 0.5; otherwise, behaves as for Down.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfTowardsZero}.
*/
case HalfDown;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity.
*
* If the result is positive, behaves as for HalfUp; if negative, behaves as for HalfDown.
*
* Equivalent native PHP rounding mode: none.
*/
case HalfCeiling;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity.
*
* If the result is positive, behaves as for HalfDown; if negative, behaves as for HalfUp.
*
* Equivalent native PHP rounding mode: none.
*/
case HalfFloor;
/**
* Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor.
*
* Behaves as for HalfUp if the digit to the left of the discarded fraction is odd;
* behaves as for HalfDown if it's even.
*
* Note that this is the rounding mode that statistically minimizes
* cumulative error when applied repeatedly over a sequence of calculations.
* It is sometimes known as "Banker's rounding", and is the default rounding mode in IEEE 754.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfEven}.
*/
case HalfEven;
/**
* Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the odd neighbor.
*
* Behaves as for HalfUp if the digit to the left of the discarded fraction is even;
* behaves as for HalfDown if it's odd.
*
* Like HalfEven, this rounding mode is free of bias towards or away from zero on ties;
* unlike HalfEven, ties never round to an even digit — in particular, never to zero or to a multiple of ten.
*
* Equivalent native PHP rounding mode: {@see \RoundingMode::HalfOdd}.
*/
case HalfOdd;
/**
* Returns the equivalent of the given native PHP rounding mode.
*
* Note that PHP's RoundingMode enum is only available on PHP 8.4 and later.
*
* @pure
*/
public static function fromNativeRoundingMode(\RoundingMode $roundingMode): self
{
return match ($roundingMode) {
\RoundingMode::AwayFromZero => self::Up,
\RoundingMode::TowardsZero => self::Down,
\RoundingMode::PositiveInfinity => self::Ceiling,
\RoundingMode::NegativeInfinity => self::Floor,
\RoundingMode::HalfAwayFromZero => self::HalfUp,
\RoundingMode::HalfTowardsZero => self::HalfDown,
\RoundingMode::HalfEven => self::HalfEven,
\RoundingMode::HalfOdd => self::HalfOdd,
};
}
}