Files
2026-09-15 10:35:56 +08:00

48 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Model\Coupon;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\SalesRule\Model\Rule;
class DiscountFormatter
{
public function __construct(private readonly PriceCurrencyInterface $priceCurrency)
{
}
public function format(Rule $rule): string
{
$amount = (float)$rule->getDiscountAmount();
return match ((string)$rule->getSimpleAction()) {
Rule::BY_PERCENT_ACTION => (string)__('%1% OFF', $this->formatNumber($amount)),
Rule::TO_PERCENT_ACTION => (string)__('Pay %1% of the item price', $this->formatNumber($amount)),
Rule::BY_FIXED_ACTION => (string)__(
'%1 OFF eligible items',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::TO_FIXED_ACTION => (string)__(
'Eligible items for %1',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::CART_FIXED_ACTION => (string)__(
'%1 OFF',
$this->priceCurrency->convertAndFormat($amount, false)
),
Rule::BUY_X_GET_Y_ACTION => (string)__(
'Buy %1, get %2 free',
max(1, (int)$rule->getDiscountStep()),
max(1, (int)$amount)
),
default => (string)__('Special offer'),
};
}
private function formatNumber(float $number): string
{
return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}
}