-
Notifications
You must be signed in to change notification settings - Fork 6
fix: multiply percentages by 100 internally to match FormatJS #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -40,6 +40,7 @@ | |
| use function assert; | ||
| use function is_callable; | ||
| use function is_int; | ||
| use function is_numeric; | ||
| use function preg_match; | ||
| use function sprintf; | ||
|
|
||
|
|
@@ -68,7 +69,7 @@ public function __construct(?LocaleInterface $locale = null) | |
| public function format(string $pattern, array $values = []): string | ||
| { | ||
| try { | ||
| $pattern = $this->applyCallbacks($pattern, $values); | ||
| $pattern = $this->applyPreprocessing($pattern, $values); | ||
| $formatter = new PhpMessageFormatter((string) $this->locale->baseName(), $pattern); | ||
|
|
||
| $formattedMessage = $formatter->format($values); | ||
|
|
@@ -107,21 +108,19 @@ public function format(string $pattern, array $values = []): string | |
| * @throws UnableToFormatMessageException | ||
| * @throws CollectionMismatchException | ||
| */ | ||
| private function applyCallbacks(string $pattern, array &$values = []): string | ||
| private function applyPreprocessing(string $pattern, array &$values = []): string | ||
| { | ||
| $callbacks = array_filter($values, fn ($value): bool => is_callable($value)); | ||
|
|
||
| // If $values doesn't contain any callables, go ahead and return. | ||
| if (!$callbacks) { | ||
| return $pattern; | ||
| } | ||
|
|
||
| // Remove the callbacks from the values, since we will use them below. | ||
| foreach (array_keys($callbacks) as $key) { | ||
| unset($values[$key]); | ||
| } | ||
|
|
||
| $parser = new Parser($pattern); | ||
| $parserOptions = new Parser\Options(); | ||
| $parserOptions->shouldParseSkeletons = true; | ||
|
|
||
| $parser = new Parser($pattern, $parserOptions); | ||
| $parsed = $parser->parse(); | ||
|
|
||
| if ($parsed->err !== null) { | ||
|
|
@@ -130,18 +129,20 @@ private function applyCallbacks(string $pattern, array &$values = []): string | |
|
|
||
| assert($parsed->val instanceof Parser\Type\ElementCollection); | ||
|
|
||
| return (new Printer())->printAst($this->processAstWithCallbacks($parsed->val, $callbacks)); | ||
| return (new Printer())->printAst($this->processAst($parsed->val, $callbacks, $values)); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<array-key, callable(string):string> $callbacks | ||
| * @param array<array-key, float | int | string | callable(string):string> $values | ||
| * | ||
| * @throws CollectionMismatchException | ||
| * @throws UnableToFormatMessageException | ||
| */ | ||
| private function processAstWithCallbacks( | ||
| private function processAst( | ||
| Parser\Type\ElementCollection $ast, | ||
| array $callbacks | ||
| array $callbacks, | ||
| array &$values | ||
| ): Parser\Type\ElementCollection { | ||
| $processedAst = new Parser\Type\ElementCollection(); | ||
|
|
||
|
|
@@ -152,16 +153,20 @@ private function processAstWithCallbacks( | |
|
|
||
| if ($clone instanceof PluralElement || $clone instanceof SelectElement) { | ||
| foreach ($clone->options as $option) { | ||
| $option->value = $this->processAstWithCallbacks($option->value, $callbacks); | ||
| $option->value = $this->processAst($option->value, $callbacks, $values); | ||
| } | ||
| } | ||
|
|
||
| if ($clone instanceof Parser\Type\TagElement) { | ||
| $processedAst = $processedAst->merge($this->processTagElement($clone, $callbacks)); | ||
| $processedAst = $processedAst->merge($this->processTagElement($clone, $callbacks, $values)); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| if ($clone instanceof Parser\Type\NumberElement) { | ||
| $clone = $this->processNumberElement($clone, $values); | ||
| } | ||
|
|
||
| if ($clone instanceof Parser\Type\LiteralElement) { | ||
| $clone = $this->processLiteralElement($clone, $callbacks); | ||
| } | ||
|
|
@@ -174,13 +179,15 @@ private function processAstWithCallbacks( | |
|
|
||
| /** | ||
| * @param array<array-key, callable(string):string> $callbacks | ||
| * @param array<array-key, float | int | string | callable(string):string> $values | ||
| * | ||
| * @throws CollectionMismatchException | ||
| * @throws UnableToFormatMessageException | ||
| */ | ||
| private function processTagElement( | ||
| Parser\Type\TagElement $tagElement, | ||
| array $callbacks | ||
| array $callbacks, | ||
| array &$values | ||
| ): Parser\Type\ElementCollection { | ||
| if (!array_key_exists($tagElement->value, $callbacks)) { | ||
| // We don't have a callback for this tag. | ||
|
|
@@ -190,7 +197,7 @@ private function processTagElement( | |
| $result = ($callbacks[$tagElement->value])(self::CALLBACK_REPLACEMENT); | ||
| if (preg_match(self::CALLBACK_RESULT_PATTERN, $result, $matches)) { | ||
| $start = new Parser\Type\LiteralElement($matches[1], $tagElement->location); | ||
| $middle = $this->processAstWithCallbacks($tagElement->children, $callbacks); | ||
| $middle = $this->processAst($tagElement->children, $callbacks, $values); | ||
| $end = new Parser\Type\LiteralElement($matches[2], $tagElement->location); | ||
|
|
||
| return new Parser\Type\ElementCollection([$start, ...array_values($middle->toArray()), $end]); | ||
|
|
@@ -199,6 +206,65 @@ private function processTagElement( | |
| return new Parser\Type\ElementCollection([new Parser\Type\LiteralElement($result, $tagElement->location)]); | ||
| } | ||
|
|
||
| /** | ||
| * Performs special processing for number elements | ||
| * | ||
| * If the parameter is a percent-style number, then we multiply the value | ||
| * by 100. This is in keeping with the ECMA-402 draft, which specifies the | ||
| * `Intl.NumberFormat` rules. When using `Intl.NumberFormat` to format | ||
| * percentages, the number must first be multiplied by 100 before any | ||
| * formatting occurs. See section 15.1.6 of ECMA-402, specifically step 5.b. | ||
| * | ||
| * ECMA-402, however, doesn't define an API for MessageFormat, so FormatJS | ||
| * implements this on their own, using `Intl.NumberFormat` to process any | ||
| * number parameters it encounters. As a result, all number parameters in | ||
| * ICU message syntax that specify the `::percent` stem (i.e., | ||
| * "{0, number, ::percent}") have their values first multiplied by 100 | ||
| * before formatting them. | ||
| * | ||
| * This may not be considered a bug in FormatJS, since it is adhering to the | ||
| * ECMA-402 specification. However, it does not follow the rules for | ||
| * percentages as programmed in icu4c (the underlying library PHP uses), so | ||
| * in order to match the expected output of FormatJS, we multiply percent | ||
| * values by 100 before formatting them. | ||
| * | ||
| * Oddly enough, PHP's `NumberFormatter` has the same rules, and it uses | ||
| * the underlying ICU implementation of the number formatter: | ||
| * | ||
| * $nf = new NumberFormatter('en-US', NumberFormatter::PERCENT); | ||
| * echo $nf->format(25); // Produces "2,500%" | ||
| * | ||
| * While: | ||
| * | ||
| * $mf = new MessageFormatter('en-US', '{0, number, ::percent}'); | ||
| * echo $mf->format([25]); // Produces "25%" | ||
| * | ||
| * So, one could argue this is a bug in the ICU implementation of the | ||
| * percent number skeleton. | ||
| * | ||
| * @link https://tc39.es/ecma402/#sec-partitionnumberpattern | ||
| * @link https://formatjs.io/docs/core-concepts/icu-syntax/#number-type | ||
| * | ||
| * @param array<array-key, float | int | string | callable(string):string> $values | ||
| */ | ||
| private function processNumberElement( | ||
| Parser\Type\NumberElement $numberElement, | ||
| array &$values | ||
| ): Parser\Type\NumberElement { | ||
| if (!$numberElement->style instanceof Parser\Type\NumberSkeleton) { | ||
| return $numberElement; | ||
| } | ||
|
|
||
| if ($numberElement->style->parsedOptions->style === NumberFormatOptions::STYLE_PERCENT) { | ||
| $key = $numberElement->value; | ||
| if (is_numeric($values[$key])) { | ||
| $values[$key] *= 100; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💯 |
||
| } | ||
| } | ||
|
|
||
| return $numberElement; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<array-key, callable(string):string> $callbacks | ||
| * | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.