Skip to content

Commit 55d53fc

Browse files
jakejackson1claude
andcommitted
Format numbers, amounts, dates and addresses as a country writes them
A Formatter writes a document's numbers, amounts, rates and dates by the convention of a country's preset, and lays out each party's address as that party's country does: - 21 presets following CLDR: the United States, English Canada and Quebec, Australia, New Zealand, the United Kingdom, China, Japan, India, and the ten most populous EU countries plus Sweden, with Dutch and French Belgium. A preset is AbstractPreset's properties, overridden where its country differs; PresetInterface is there for any other. - India's lakh grouping, the whole four-digit numbers of Spain, Poland and Portugal, currencies without a minor unit, and each language's month names for dates written out. - withDateFormat(), withLongDates(), withCurrencyFormat(), withPercentFormat() and withAddressFormat() adjust a copy. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent af74f6a commit 55d53fc

25 files changed

Lines changed: 1517 additions & 0 deletions

‎src/Invoice/Formatter.php‎

Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
<?php
2+
3+
namespace Mpdf\Invoice;
4+
5+
use Mpdf\Invoice\Preset\PresetInterface;
6+
use Mpdf\MpdfException;
7+
use Mpdf\Strict;
8+
use Mpdf\Utils\Arrays;
9+
use Mpdf\Utils\NumericString;
10+
11+
/**
12+
* How a printed trade document writes its numbers, amounts, rates, dates and addresses
13+
*
14+
* It follows the preset of a country, one of those in Mpdf\Invoice\Preset or a PresetInterface of your own, including
15+
* its month names. withDateFormat() and the other with methods return a copy adjusted further:
16+
*
17+
* (new Formatter(new GermanyPreset()))->withCurrencyFormat('GBP', '£%s')
18+
*
19+
* Amounts have two decimals, or none in a currency without a minor unit such as the yen, and up to four when they
20+
* carry more, as a unit price of 0.125 does. An address is laid out as its party's country lays it out, whichever
21+
* preset is used: 75002 Paris, but New York, NY 10118.
22+
*/
23+
class Formatter
24+
{
25+
26+
use Strict;
27+
28+
/**
29+
* The lines of an address in the countries that do not write the postcode, city and state on one line after the
30+
* street, in that order. A Latin-script address in China or Japan follows the Western order.
31+
*
32+
* @var string[][]
33+
*/
34+
private $addressFormats = [
35+
'AU' => ['{street}', '{additional}', '{city} {subdivision} {postcode}', '{country}'],
36+
'CA' => ['{street}', '{additional}', '{city} {subdivision} {postcode}', '{country}'],
37+
'CN' => ['{street}', '{additional}', '{city}, {subdivision} {postcode}', '{country}'],
38+
'GB' => ['{street}', '{additional}', '{city}', '{postcode}', '{country}'],
39+
'IN' => ['{street}', '{additional}', '{city} {postcode}', '{subdivision}', '{country}'],
40+
'JP' => ['{street}', '{additional}', '{city}, {subdivision} {postcode}', '{country}'],
41+
'NZ' => ['{street}', '{additional}', '{city} {postcode}', '{country}'],
42+
'US' => ['{street}', '{additional}', '{city}, {subdivision} {postcode}', '{country}'],
43+
];
44+
45+
/**
46+
* The lines of an address in every other country
47+
*
48+
* @var string[]
49+
*/
50+
private static $defaultAddressFormat = ['{street}', '{additional}', '{postcode} {city} {subdivision}', '{country}'];
51+
52+
/**
53+
* The ISO 4217 currencies with no minor unit, whose amounts are written whole
54+
*
55+
* @var bool[]
56+
*/
57+
private static $wholeCurrencies = [
58+
'BIF' => true, 'CLP' => true, 'DJF' => true, 'GNF' => true, 'ISK' => true, 'JPY' => true, 'KMF' => true, 'KRW' => true,
59+
'PYG' => true, 'RWF' => true, 'UGX' => true, 'VND' => true, 'VUV' => true, 'XAF' => true, 'XOF' => true, 'XPF' => true,
60+
];
61+
62+
/**
63+
* @var \Mpdf\Invoice\Preset\PresetInterface
64+
*/
65+
private $preset;
66+
67+
/**
68+
* @var string
69+
*/
70+
private $dateFormat;
71+
72+
/**
73+
* @var string[]
74+
*/
75+
private $currencyFormats;
76+
77+
/**
78+
* @var string
79+
*/
80+
private $percentFormat;
81+
82+
/**
83+
* @param \Mpdf\Invoice\Preset\PresetInterface $preset
84+
*
85+
* @throws \Mpdf\MpdfException When the preset gives no date format
86+
*/
87+
public function __construct(PresetInterface $preset)
88+
{
89+
if (!is_string($preset->getDateFormat())) {
90+
throw new MpdfException(sprintf('%s gives no date format', get_class($preset)));
91+
}
92+
93+
$this->preset = $preset;
94+
$this->dateFormat = $preset->getDateFormat();
95+
$this->currencyFormats = $preset->getCurrencyFormats();
96+
$this->percentFormat = $preset->getPercentFormat();
97+
}
98+
99+
/**
100+
* A copy writing dates by another format
101+
*
102+
* @param string $format As DateTimeInterface::format() takes it, with {month} for the month's name in the preset's
103+
* language, e.g. 'Y-m-d' or 'jS {month} Y'
104+
*
105+
* @return self
106+
*/
107+
public function withDateFormat($format)
108+
{
109+
$formatter = clone $this;
110+
$formatter->dateFormat = $format;
111+
112+
return $formatter;
113+
}
114+
115+
/**
116+
* A copy writing dates out as the preset does in a letter: 23. September 2026, or September 23, 2026
117+
*
118+
* @return self
119+
*/
120+
public function withLongDates()
121+
{
122+
return $this->withDateFormat($this->preset->getLongDateFormat());
123+
}
124+
125+
/**
126+
* A copy writing amounts in a currency by a format of its own; a currency without one has its code after the amount
127+
*
128+
* @param string $currency ISO 4217 code
129+
* @param string $format A sprintf() format for the amount, e.g. '$%s'
130+
*
131+
* @return self
132+
*/
133+
public function withCurrencyFormat($currency, $format)
134+
{
135+
$formatter = clone $this;
136+
$formatter->currencyFormats[$currency] = $format;
137+
138+
return $formatter;
139+
}
140+
141+
/**
142+
* A copy writing rates by another format
143+
*
144+
* @param string $format A sprintf() format for the rate, e.g. '%s%%'
145+
*
146+
* @return self
147+
*/
148+
public function withPercentFormat($format)
149+
{
150+
$formatter = clone $this;
151+
$formatter->percentFormat = $format;
152+
153+
return $formatter;
154+
}
155+
156+
/**
157+
* A copy laying out the addresses of a country another way
158+
*
159+
* @param string $country ISO 3166-1 alpha-2 code
160+
* @param string[] $lines Each line from {street}, {additional}, {postcode}, {city}, {subdivision} and {country},
161+
* e.g. ['{street}', '{city} {postcode}', '{country}']
162+
*
163+
* @return self
164+
*/
165+
public function withAddressFormat($country, array $lines)
166+
{
167+
$formatter = clone $this;
168+
$formatter->addressFormats[$country] = $lines;
169+
170+
return $formatter;
171+
}
172+
173+
/**
174+
* A quantity, to at most four decimals and without trailing zeros
175+
*
176+
* @param float $number
177+
*
178+
* @return string
179+
*/
180+
public function number($number)
181+
{
182+
return $this->separate(NumericString::decimal($number, 4));
183+
}
184+
185+
/**
186+
* A rate, such as a VAT rate, as a number with its percent sign
187+
*
188+
* @param float $rate
189+
*
190+
* @return string
191+
*/
192+
public function percent($rate)
193+
{
194+
return sprintf($this->percentFormat, $this->number($rate));
195+
}
196+
197+
/**
198+
* An amount to the cent, or whole in a currency without cents, and to at most four decimals when it has more; the
199+
* sign goes ahead of any symbol: -$100.00
200+
*
201+
* @param float $amount
202+
* @param string $currency ISO 4217 code
203+
*
204+
* @return string
205+
*/
206+
public function money($amount, $currency)
207+
{
208+
$decimal = NumericString::decimal($amount, 4);
209+
$parts = explode('.', ltrim($decimal, '-') . '.');
210+
$fraction = str_pad($parts[1], isset(self::$wholeCurrencies[$currency]) ? 0 : 2, '0');
211+
$format = Arrays::get($this->currencyFormats, $currency, '%s ' . $currency);
212+
$money = sprintf($format, $this->separate($parts[0] . ($fraction !== '' ? '.' . $fraction : '')));
213+
214+
return $decimal[0] === '-' ? '-' . $money : $money;
215+
}
216+
217+
/**
218+
* A date in the preset's format, or the one given to withDateFormat()
219+
*
220+
* @param \DateTimeInterface $date
221+
*
222+
* @return string
223+
*/
224+
public function date(\DateTimeInterface $date)
225+
{
226+
// The name goes in after formatting, so its letters are not read as format characters
227+
$formatted = $date->format(str_replace('{month}', "\x01", $this->dateFormat));
228+
229+
$monthNames = $this->preset->getMonthNames();
230+
231+
return str_replace("\x01", $monthNames[$date->format('n') - 1], $formatted);
232+
}
233+
234+
/**
235+
* A party's address in the lines its country lays it out in, leaving out the parts it has none of and any line
236+
* they leave empty
237+
*
238+
* @param \Mpdf\Invoice\Party $party
239+
*
240+
* @return string[]
241+
*/
242+
public function address(Party $party)
243+
{
244+
$country = $party->getCountryCode();
245+
$lines = Arrays::get($this->addressFormats, $country, self::$defaultAddressFormat);
246+
247+
$parts = [
248+
'{street}' => (string) $party->getStreet(),
249+
'{additional}' => (string) $party->getAdditionalStreet(),
250+
'{postcode}' => (string) $party->getPostcode(),
251+
'{city}' => (string) $party->getCity(),
252+
'{subdivision}' => (string) $party->getCountrySubdivision(),
253+
'{country}' => $country,
254+
];
255+
256+
$missing = array_keys($parts, '', true);
257+
258+
$address = [];
259+
foreach ($lines as $line) {
260+
// Take the missing parts out of the layout before filling it, closing the gaps and commas they leave, so the
261+
// party's own text is never touched
262+
$line = trim(preg_replace(['/\s+/', '/ ?(, ?)+/'], [' ', ', '], str_replace($missing, '', $line)), ' ,');
263+
if ($line !== '') {
264+
$address[] = strtr($line, $parts);
265+
}
266+
}
267+
268+
return $address;
269+
}
270+
271+
/**
272+
* A plain decimal such as -1234567.25 with its digits grouped and its decimal point as the preset writes them
273+
*
274+
* @param string $decimal
275+
*
276+
* @return string
277+
*/
278+
private function separate($decimal)
279+
{
280+
$sign = $decimal[0] === '-' ? '-' : '';
281+
$parts = explode('.', ltrim($decimal, '-'));
282+
$integer = $parts[0];
283+
$sizes = $this->preset->getGroupingSizes();
284+
$size = $sizes[0];
285+
$laterSize = end($sizes);
286+
287+
if (strlen($integer) >= $size + $this->preset->getMinimumGroupingDigits()) {
288+
$groups = [];
289+
while (strlen($integer) > $size) {
290+
array_unshift($groups, substr($integer, -$size));
291+
$integer = substr($integer, 0, -$size);
292+
$size = $laterSize;
293+
}
294+
array_unshift($groups, $integer);
295+
$integer = implode($this->preset->getThousandsSeparator(), $groups);
296+
}
297+
298+
return $sign . $integer . (isset($parts[1]) ? $this->preset->getDecimalPoint() . $parts[1] : '');
299+
}
300+
301+
}

0 commit comments

Comments
 (0)