36 lines
1.5 KiB
PHP
36 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace Tempo\Inventory;
|
|
|
|
use Brick\Math\BigInteger;
|
|
use InvalidArgumentException;
|
|
|
|
/** Exact physical quantities; never prices or implicit unit assumptions. */
|
|
final class QuantityConversion
|
|
{
|
|
public static function toBase(string $quantityMilli, string $numerator, string $denominator): string
|
|
{
|
|
foreach ([$quantityMilli, $numerator, $denominator] as $value) {
|
|
if (!preg_match('/^\d{1,19}$/D', $value)) {
|
|
throw new InvalidArgumentException('A quantidade e os termos do factor devem ser inteiros explícitos.');
|
|
}
|
|
}
|
|
$quantity = BigInteger::of($quantityMilli);
|
|
$top = BigInteger::of($numerator);
|
|
$bottom = BigInteger::of($denominator);
|
|
if ($top->isZero() || $bottom->isZero() || $quantity->isGreaterThan(PHP_INT_MAX)) {
|
|
throw new InvalidArgumentException('Factor positivo e quantidade inteira suportada obrigatórios.');
|
|
}
|
|
[$converted, $remainder] = $quantity->multipliedBy($top)->quotientAndRemainder($bottom);
|
|
if (!$remainder->isZero() || $converted->isGreaterThan(PHP_INT_MAX)) {
|
|
throw new InvalidArgumentException('Quantidade física não representável em milésimos sem arredondamento.');
|
|
}
|
|
return (string)$converted;
|
|
}
|
|
|
|
public static function fromBase(string $quantityMilli, string $numerator, string $denominator): string
|
|
{
|
|
return self::toBase($quantityMilli, $denominator, $numerator);
|
|
}
|
|
}
|