insecure-bank/webroot/lib/View/MoneyFormatter.php

31 lines
797 B
PHP

<?php
declare(strict_types=1);
namespace View;
class MoneyFormatter
{
public static function formatAmount(int $amount): string
{
if ($amount < 0) {
$inner = static::formatAmount(-$amount);
return "<span class=\"negative\">- {$inner}</span>";
}
$euro = intdiv($amount, 100);
$cent = sprintf("%02d", $amount % 100);
return "{$euro},{$cent}";
}
public static function parseAmount(string $amount): ?int
{
$pattern = '/^([0-9]+)(,([0-9]{2}))?$/';
if (preg_match($pattern, $amount, $matches)) {
$euro = (int) $matches[1];
$cent = (int) ($matches[3] ?? 0);
$amount = 100 * $euro + $cent;
return (int) $amount;
}
return null;
}
}