self::MAX_CENTS) { throw new InvalidMoneyAmount; } $this->cents = $cents; } public static function fromCents(int $cents): self { return new self($cents); } /** * Parses "85", "85,50", "85.5", "1 200,00" or "85 €"; null for an empty value. * * @throws InvalidMoneyAmount */ 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,9})(?:\.(\d{1,2}))?$/', $value, $matches) !== 1) { throw new InvalidMoneyAmount; } $fraction = str_pad($matches[2] ?? '', 2, '0'); return new self((int) $matches[1] * 100 + (int) $fraction); } /** * Finnish notation with the currency, e.g. "1 200,50 €". */ public function format(): string { return $this->amount(self::NO_BREAK_SPACE).self::NO_BREAK_SPACE.'€'; } /** * The amount for an input field, e.g. "1200,50". */ public function inputValue(): string { return $this->amount(''); } private function amount(string $thousandsSeparator): string { return number_format($this->cents / 100, 2, ',', $thousandsSeparator); } }