From ee5612ee223f47ce4d2e76c2b13d3f78fdc49c60 Mon Sep 17 00:00:00 2001 From: Claudio Zizza Date: Thu, 23 Nov 2023 23:27:31 +0100 Subject: [PATCH] Use first class callables in LocaleFormatter --- src/Formatter/LocaleFormatter.php | 44 ++++++++++++++++++------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/Formatter/LocaleFormatter.php b/src/Formatter/LocaleFormatter.php index 991358f..d1ae884 100644 --- a/src/Formatter/LocaleFormatter.php +++ b/src/Formatter/LocaleFormatter.php @@ -14,27 +14,11 @@ class LocaleFormatter implements FormatterInterface /** @phpstan-var array */ 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(...), ]; } @@ -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; + } }