Skip to content

Commit

Permalink
Use first class callables in LocaleFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
SenseException committed Nov 23, 2023
1 parent 9a53a1f commit ee5612e
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions src/Formatter/LocaleFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,11 @@ class LocaleFormatter implements FormatterInterface
/** @phpstan-var array<callable(string $value): string> */
private array $formatFunctions;

public function __construct(string $locale)
public function __construct(private string $locale)
{
$this->formatFunctions = [
'language' => static function (string $value) use ($locale): string {
$language = Locale::getDisplayLanguage($value, $locale);

if ($value === $language) {
throw InvalidValueException::invalidLocale($value);
}

return $language;
},
'region' => static function (string $value) use ($locale): string {
$region = Locale::getDisplayRegion($value, $locale);

if ($region === '') {
throw InvalidValueException::invalidLocale($value);
}

return $region;
},
'language' => $this->formatLanguage(...),
'region' => $this->formatRegion(...),
];
}

Expand All @@ -51,4 +35,26 @@ public function has(string $typeSpecifier): bool
{
return isset($this->formatFunctions[$typeSpecifier]);
}

private function formatLanguage(string $value): string
{
$language = Locale::getDisplayLanguage($value, $this->locale);

if ($value === $language) {
throw InvalidValueException::invalidLocale($value);
}

return $language;
}

private function formatRegion(string $value): string
{
$region = Locale::getDisplayRegion($value, $this->locale);

if ($region === '') {
throw InvalidValueException::invalidLocale($value);
}

return $region;
}
}

0 comments on commit ee5612e

Please sign in to comment.