1313
1414namespace Sylius \PayPalPlugin \Processor ;
1515
16+ use Sylius \PayPalPlugin \Resolver \SupportedLocaleResolverInterface ;
1617use Symfony \Component \Intl \Locales ;
1718
1819final class LocaleProcessor implements LocaleProcessorInterface
1920{
21+ private const ALLOWED_LOCALE_PATTERN = '/^[a-z]{2}(_[A-Z]{2})?$/ ' ;
22+
23+ public function __construct (
24+ private readonly ?SupportedLocaleResolverInterface $ supportedLocaleResolver = null ,
25+ ) {
26+ if (null === $ this ->supportedLocaleResolver ) {
27+ trigger_deprecation (
28+ 'sylius/paypal-plugin ' ,
29+ '1.7 ' ,
30+ sprintf (
31+ 'Not passing an instance of "%s" is deprecated and will be prohibited in 3.0 ' ,
32+ SupportedLocaleResolverInterface::class,
33+ ),
34+ );
35+ }
36+ }
37+
2038 public function process (string $ locale ): string
2139 {
22- if ($ this ->isValidLocale ($ locale )) {
40+ if (null !== $ this ->supportedLocaleResolver ) {
41+ $ locale = trim ($ locale );
42+
43+ if ($ this ->isValidLocale ($ locale )) {
44+ return $ this ->supportedLocaleResolver ->resolve ($ locale );
45+ }
46+
47+ throw new \UnexpectedValueException (sprintf ('Locale "%s" is not valid. ' , $ locale ));
48+ }
49+
50+ return $ this ->legacyProcess ($ locale );
51+ }
52+
53+ private function legacyProcess (string $ locale ): string
54+ {
55+ if (str_contains ($ locale , '_ ' )) {
2356 return $ locale ;
2457 }
2558
@@ -29,21 +62,24 @@ public function process(string $locale): string
2962
3063 $ locales = array_filter (Locales::getLocales (), function (string $ targetLocale ) use ($ locale ): bool {
3164 return
32- strpos ($ targetLocale , $ locale ) === 0 &&
33- strpos ($ targetLocale, ' _ ' ) !== false &&
34- strlen ($ targetLocale ) === 5
65+ str_starts_with ($ targetLocale , $ locale ) &&
66+ strlen ($ targetLocale) === 5 &&
67+ $ this -> isValidLocale ($ targetLocale )
3568 ;
3669 });
3770
3871 if ([] === $ locales ) {
3972 throw new \UnexpectedValueException (sprintf ('Locale "%s" is not supported by PayPal. ' , $ locale ));
4073 }
4174
42- return $ locales [ array_key_first ($ locales )] ;
75+ return array_shift ($ locales );
4376 }
4477
4578 private function isValidLocale (string $ locale ): bool
4679 {
47- return strpos ($ locale , '_ ' ) !== false ;
80+ return
81+ false === str_contains ($ locale , ' ' ) &&
82+ 1 === preg_match (self ::ALLOWED_LOCALE_PATTERN , $ locale )
83+ ;
4884 }
4985}
0 commit comments