@@ -111,6 +111,8 @@ public function slug(string $string, string $separator = '-', string $locale = n
111
111
}
112
112
113
113
if ($ this ->symbolsMap instanceof \Closure) {
114
+ // If the symbols map is passed as a closure, there is no need to fallback to the parent locale
115
+ // as the closure can just provide substitutions for all locales of interest.
114
116
$ symbolsMap = $ this ->symbolsMap ;
115
117
array_unshift ($ transliterator , static function ($ s ) use ($ symbolsMap , $ locale ) {
116
118
return $ symbolsMap ($ s , $ locale );
@@ -119,9 +121,20 @@ public function slug(string $string, string $separator = '-', string $locale = n
119
121
120
122
$ unicodeString = (new UnicodeString ($ string ))->ascii ($ transliterator );
121
123
122
- if (\is_array ($ this ->symbolsMap ) && isset ($ this ->symbolsMap [$ locale ])) {
123
- foreach ($ this ->symbolsMap [$ locale ] as $ char => $ replace ) {
124
- $ unicodeString = $ unicodeString ->replace ($ char , ' ' .$ replace .' ' );
124
+ if (\is_array ($ this ->symbolsMap )) {
125
+ $ map = null ;
126
+ if (isset ($ this ->symbolsMap [$ locale ])) {
127
+ $ map = $ this ->symbolsMap [$ locale ];
128
+ } else {
129
+ $ parent = self ::getParentLocale ($ locale );
130
+ if ($ parent && isset ($ this ->symbolsMap [$ parent ])) {
131
+ $ map = $ this ->symbolsMap [$ parent ];
132
+ }
133
+ }
134
+ if ($ map ) {
135
+ foreach ($ map as $ char => $ replace ) {
136
+ $ unicodeString = $ unicodeString ->replace ($ char , ' ' .$ replace .' ' );
137
+ }
125
138
}
126
139
}
127
140
@@ -143,17 +156,28 @@ private function createTransliterator(string $locale): ?\Transliterator
143
156
}
144
157
145
158
// Locale not supported and no parent, fallback to any-latin
146
- if (false === $ str = strrchr ($ locale, ' _ ' )) {
159
+ if (! $ parent = self :: getParentLocale ($ locale )) {
147
160
return $ this ->transliterators [$ locale ] = null ;
148
161
}
149
162
150
163
// Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales
151
- $ parent = substr ($ locale , 0 , -\strlen ($ str ));
152
-
153
164
if ($ id = self ::LOCALE_TO_TRANSLITERATOR_ID [$ parent ] ?? null ) {
154
165
$ transliterator = \Transliterator::create ($ id .'/BGN ' ) ?? \Transliterator::create ($ id );
155
166
}
156
167
157
168
return $ this ->transliterators [$ locale ] = $ this ->transliterators [$ parent ] = $ transliterator ?? null ;
158
169
}
170
+
171
+ private static function getParentLocale (?string $ locale ): ?string
172
+ {
173
+ if (!$ locale ) {
174
+ return null ;
175
+ }
176
+ if (false === $ str = strrchr ($ locale , '_ ' )) {
177
+ // no parent locale
178
+ return null ;
179
+ }
180
+
181
+ return substr ($ locale , 0 , -\strlen ($ str ));
182
+ }
159
183
}
0 commit comments