self::MAX_MILLI) { throw new InvalidStockQuantity; } return new self($milli); } /** * A quantity greater than zero, as typed in. * * @throws InvalidStockQuantity */ public static function parsePositive(string $value): self { $quantity = self::parse($value); if ($quantity === null || $quantity->milli <= 0) { throw new InvalidStockQuantity; } return $quantity; } /** * A quantity of zero or more as typed in, or null for an empty value. * * @throws InvalidStockQuantity */ public static function parse(string $value): ?self { $value = preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? ''; $value = str_replace(',', '.', $value); if ($value === '') { return null; } if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) { throw new InvalidStockQuantity; } return new self((int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0')); } public function negated(): self { return new self(-$this->milli); } /** * Finnish format without trailing zeros: "2,5", "-1", "1 200". */ public static function format(int $milli): string { $whole = intdiv(abs($milli), 1000); $fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0'); return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction); } /** * The value for an input field: "2,5" without thousands separators. */ public static function inputValue(int $milli): string { return str_replace("\u{00A0}", '', self::format($milli)); } }