forked from Skillshare/formatphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisplayNames.php
More file actions
244 lines (201 loc) · 7.98 KB
/
DisplayNames.php
File metadata and controls
244 lines (201 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php
/**
* This file is part of formatphp/formatphp
*
* formatphp/formatphp is open source software: you can distribute
* it and/or modify it under the terms of the MIT License
* (the "License"). You may not use this file except in
* compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* @copyright Copyright (c) Skillshare, Inc. <https://www.skillshare.com>
* @copyright Copyright (c) FormatPHP Contributors <https://formatphp.dev>
* @license https://opensource.org/licenses/MIT MIT License
*/
declare(strict_types=1);
namespace FormatPHP\Intl;
use FormatPHP\Exception\InvalidArgumentException;
use FormatPHP\Exception\UnableToFormatDisplayNameException;
use FormatPHP\Icu\MessageFormat\Parser;
use Locale as PhpLocale;
use MessageFormatter;
use function implode;
use function in_array;
use function mb_strtolower;
use function preg_match;
use function preg_match_all;
use function sprintf;
/**
* Formats a locale-appropriate display name for properties of a given locale
*/
class DisplayNames implements DisplayNamesInterface
{
private const CURRENCY_FORMAT = '{0, number, ::currency/%s %s precision-currency-standard/w}';
private const STYLE_CURRENCY_WIDTH = [
'long' => 'unit-width-full-name',
'narrow' => 'unit-width-narrow',
'short' => 'unit-width-iso-code',
];
private const STYLE_CURRENCY_DEFAULT = 'unit-width-full-name';
private string $localeName;
private DisplayNamesOptions $options;
private const VALID_TYPES = [
DisplayNamesOptions::TYPE_CURRENCY,
DisplayNamesOptions::TYPE_LANGUAGE,
DisplayNamesOptions::TYPE_REGION,
DisplayNamesOptions::TYPE_SCRIPT,
];
/**
* @throws InvalidArgumentException
*/
public function __construct(?LocaleInterface $locale = null, ?DisplayNamesOptions $options = null)
{
$this->options = $options ? clone $options : new DisplayNamesOptions();
if ($this->options->type === null) {
throw new InvalidArgumentException('The type property must be set');
}
if (!in_array($this->options->type, self::VALID_TYPES)) {
throw new InvalidArgumentException(
'The type property must be either "language", "region", "script", or "currency"',
);
}
$locale = $locale ?? new Locale(PhpLocale::getDefault());
$this->localeName = $locale->toString();
}
/**
* @throws UnableToFormatDisplayNameException
*/
public function of(string $code): ?string
{
return $this->doFormat($code);
}
/**
* @throws UnableToFormatDisplayNameException
*/
private function doFormat(string $code): ?string
{
$result = '';
$changed = false;
switch ($this->options->type) {
case DisplayNamesOptions::TYPE_LANGUAGE:
[$result, $changed] = $this->formatLanguage($code);
break;
case DisplayNamesOptions::TYPE_REGION:
[$result, $changed] = $this->formatRegion($code);
break;
case DisplayNamesOptions::TYPE_SCRIPT:
[$result, $changed] = $this->formatScript($code);
break;
case DisplayNamesOptions::TYPE_CURRENCY:
[$result, $changed] = $this->formatCurrency($code);
break;
}
// If the value hasn't changed, then we assume ICU couldn't find a
// display name for it for this locale. Normally, we return the original
// code as the fallback, but if fallback is "none," we return `null`.
if (!$changed && $this->options->fallback === DisplayNamesOptions::FALLBACK_NONE) {
return null;
}
return $result;
}
/**
* @return array{string, bool}
*/
private function formatLanguage(string $code): array
{
$result = PhpLocale::getDisplayName($code, $this->localeName);
return [$result, $this->isChanged($result, $code)];
}
/**
* @return array{string, bool}
*
* @throws UnableToFormatDisplayNameException
*/
private function formatRegion(string $code): array
{
if (!preg_match('/^([A-Za-z]{2}|[0-9]{3})$/', $code)) {
throw new UnableToFormatDisplayNameException(sprintf('Invalid value "%s" for option region', $code));
}
$result = PhpLocale::getDisplayRegion("-$code", $this->localeName);
return [$result, $this->isChanged($result, $code)];
}
/**
* @return array{string, bool}
*
* @throws UnableToFormatDisplayNameException
*/
private function formatScript(string $code): array
{
if (!preg_match('/^([A-Za-z]{4})$/', $code)) {
throw new UnableToFormatDisplayNameException(sprintf('Invalid value "%s" for option script', $code));
}
$result = PhpLocale::getDisplayScript("-$code", $this->localeName);
return [$result, $this->isChanged($result, $code)];
}
/**
* @return array{string, bool}
*
* @throws UnableToFormatDisplayNameException
*/
private function formatCurrency(string $code): array
{
if (!preg_match('/^([A-Za-z]{3})$/', $code)) {
throw new UnableToFormatDisplayNameException(sprintf('Invalid value "%s" for option currency', $code));
}
$pattern = sprintf(
self::CURRENCY_FORMAT,
$code,
self::STYLE_CURRENCY_WIDTH[$this->options->style] ?? self::STYLE_CURRENCY_DEFAULT,
);
$formatter = new MessageFormatter($this->localeName, $pattern);
$result = $this->parseCurrencyFromMessage((string) $formatter->format([1]), $code);
return [$result, $this->isCurrencyChanged($result, $code)];
}
/**
* Returns `true` if the currency result is not the same as the original
* currency code (i.e., it has changed)
*
* We apply special handling if currency style is "short." In this event,
* if the currency code is "USD" and the style is "short," then some locales
* will use "USD" as the short version. The normal `isChanged()` method will
* return `false`, in this case. However, if it's a valid currency, we want
* to track it as if it did change. To check whether it's a valid currency,
* we will generate a long version of the currency name and compare it to
* the $result provided. If they are different, then it's a valid currency,
* and we can return `true` and track it as if it changed.
*
* If they are the same, then we can assume that ICU could not find a
* display name for the currency code in this locale, so we will return
* `false` so the calling code can decide how best to handle this condition.
*/
private function isCurrencyChanged(string $result, string $code): bool
{
if ($this->options->style !== DisplayNamesOptions::STYLE_SHORT) {
return $this->isChanged($result, $code);
}
$formatter = new MessageFormatter(
$this->localeName,
sprintf(self::CURRENCY_FORMAT, $code, self::STYLE_CURRENCY_DEFAULT),
);
$longResult = $this->parseCurrencyFromMessage((string) $formatter->format([1]), $code);
return $this->isChanged($longResult, $result);
}
/**
* Returns `true` if the result is not the same as the original code
* (i.e., it has changed)
*/
private function isChanged(string $result, string $code): bool
{
return mb_strtolower($result, Parser::ENCODING) !== mb_strtolower($code, Parser::ENCODING);
}
private function parseCurrencyFromMessage(string $message, string $code): string
{
preg_match_all('/[^0-9\s]+/u', $message, $matches);
return implode(' ', $matches[0]) ?: $code;
}
}