Commit 63268781a40 for php
commit 63268781a40bbd3df888a05e555537c838ea989a
Author: ChrisAbner <chrisabner@hotmail.com>
Date: Fri Dec 4 15:36:03 2026 +0000
ext/intl: Locale::composeLocale() option to keep keywords
Locale::composeLocale() / locale_compose() only read the subtag keys
(language, script, region, variant, extlang, private, grandfathered) and
dropped everything else, so the keywords returned by getKeywords() could
not be composed back.
With the new optional Locale::COMPOSE_ADD_KEYWORDS flag, the entries that
are not subtags are added as keywords with uloc_setKeywordValue(), which
validates and sorts them. Keys and values in BCP 47 form ("tz" => "nlams")
are converted to the legacy ones that getKeywords() returns ("timezone" =>
"Europe/Amsterdam"), and legacy values keep their case, as in getKeywords()
and canonicalize().
The "x" keyword that getKeywords() returns for a BCP 47 private use part
("en-US-x-a-b") is added as private subtags and replaces the private keys,
as parseLocale() returns only part of it ("private0" => "a").
An invalid keyword or value makes it return false with an intl error, as
for the other parts. So do a key that differs from a subtag key only in
case ("Region"), two keys for the same keyword ("tz" and "timezone"), and
keywords next to a grandfathered tag, instead of dropping or guessing.
Without the flag nothing changes.
Close GH-20393
Close GH-25914
diff --git a/NEWS b/NEWS
index 498c80ed3cb..5cfb6b3daa5 100644
--- a/NEWS
+++ b/NEWS
@@ -72,6 +72,8 @@ PHP NEWS
. Fixed UConverter::setSubstChars() truncating the substitution string
length. (Weilin Du)
. Added grapheme_str_pad(). (Chris Abner Herrera Navarro)
+ . Added Locale::COMPOSE_ADD_KEYWORDS flag to Locale::composeLocale() and
+ locale_compose() (GH-20393). (Chris Abner Herrera Navarro)
- JSON:
. Improved performance of json_encode() for strings with non-ASCII
diff --git a/UPGRADING b/UPGRADING
index fe6d35628c9..ab5e4d1e83f 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -127,6 +127,13 @@ PHP 8.7 UPGRADE NOTES
locales known to ICU, and the matching entry is returned as passed.
A ValueError is thrown if the array is empty or contains an invalid
locale, and a TypeError if it contains a non-string value.
+ . Locale::composeLocale() and locale_compose() now accept an optional $flags
+ argument. With Locale::COMPOSE_ADD_KEYWORDS, the array entries that are
+ not subtags are added as keywords, so the result of Locale::getKeywords()
+ can be composed back. Keys and values in BCP 47 form, such as
+ 'tz' => 'nlams', are converted to the legacy form that
+ Locale::getKeywords() returns. An invalid keyword or value makes it return
+ false.
- Streams:
. The so_linger, so_rcvbuf and so_sndbuf stream socket context options are
diff --git a/ext/intl/locale/locale.h b/ext/intl/locale/locale.h
index 1c40871d206..401260901bb 100644
--- a/ext/intl/locale/locale.h
+++ b/ext/intl/locale/locale.h
@@ -27,6 +27,9 @@
#define LOC_PRIVATE_TAG "private"
#define LOC_CANONICALIZE_TAG "canonicalize"
+/* locale_compose() flag: keep the array entries that are not subtags as keywords */
+#define LOC_COMPOSE_ADD_KEYWORDS 1
+
#define LOCALE_INI_NAME "intl.default_locale"
#endif // LOCALE_LOCALE_H
diff --git a/ext/intl/locale/locale.stub.php b/ext/intl/locale/locale.stub.php
index 3fd11034d27..57ff2f97d48 100644
--- a/ext/intl/locale/locale.stub.php
+++ b/ext/intl/locale/locale.stub.php
@@ -24,6 +24,8 @@ class Locale
public const string GRANDFATHERED_LANG_TAG = UNKNOWN;
/** @cvalue LOC_PRIVATE_TAG */
public const string PRIVATE_TAG = UNKNOWN;
+ /** @cvalue LOC_COMPOSE_ADD_KEYWORDS */
+ public const int COMPOSE_ADD_KEYWORDS = UNKNOWN;
/**
* @tentative-return-type
@@ -106,7 +108,7 @@ public static function getDisplayKeywordValue(string $locale, string $keyword, ?
* @tentative-return-type
* @alias locale_compose
*/
- public static function composeLocale(array $subtags): string|false {}
+ public static function composeLocale(array $subtags, int $flags = 0): string|false {}
/**
* @tentative-return-type
diff --git a/ext/intl/locale/locale_arginfo.h b/ext/intl/locale/locale_arginfo.h
index a95494580c0..38e9adba7b1 100644
Binary files a/ext/intl/locale/locale_arginfo.h and b/ext/intl/locale/locale_arginfo.h differ
diff --git a/ext/intl/locale/locale_methods.cpp b/ext/intl/locale/locale_methods.cpp
index 136ba010950..a6b842ba03f 100644
--- a/ext/intl/locale/locale_methods.cpp
+++ b/ext/intl/locale/locale_methods.cpp
@@ -55,6 +55,10 @@ ZEND_EXTERN_MODULE_GLOBALS( intl )
#define MAX_NO_LOOKUP_LANG_TAG 100
#define LOC_NOT_FOUND 1
+#define LOC_INVALID_KEYWORD 2
+#define LOC_SUBTAG_KEY_CASE 3
+#define LOC_DUPLICATE_KEYWORD 4
+#define LOC_GRANDFATHERED_KEYWORD 5
/* Sizes required for the strings "variant15" , "extlang3", "private12" etc. */
#define VARIANT_KEYNAME_LEN 11
@@ -980,6 +984,212 @@ static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr,
}
/* }}} */
+/* Whether key is tag, optionally followed by a number (variant, variant0...).
+ * With ignore_case, "Variant0" and "VARIANT" match too. */
+static bool is_numbered_tag_key(const zend_string *key, const char *tag, bool ignore_case = false)
+{
+ size_t tag_len = strlen(tag);
+ if (ZSTR_LEN(key) < tag_len) {
+ return false;
+ }
+ if (ignore_case ? zend_binary_strncasecmp(ZSTR_VAL(key), tag_len, tag, tag_len, tag_len) != 0
+ : memcmp(ZSTR_VAL(key), tag, tag_len) != 0) {
+ return false;
+ }
+ for (const char *p = ZSTR_VAL(key) + tag_len; p < ZSTR_VAL(key) + ZSTR_LEN(key); p++) {
+ if (*p < '0' || *p > '9') {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* Whether key is one of the subtag keys that locale_compose() reads itself:
+ * language, script, region, grandfathered, and variant, extlang and private
+ * with or without a number (variant0, variant1...) */
+static bool is_compose_subtag_key(const zend_string *key, bool ignore_case = false)
+{
+ static const char *const single_tags[] = {LOC_LANG_TAG, LOC_SCRIPT_TAG, LOC_REGION_TAG, LOC_GRANDFATHERED_LANG_TAG};
+ static const char *const multiple_tags[] = {LOC_VARIANT_TAG, LOC_EXTLANG_TAG, LOC_PRIVATE_TAG};
+
+ for (const char *tag : single_tags) {
+ if (ignore_case ? zend_string_equals_cstr_ci(key, tag, strlen(tag)) : zend_string_equals_cstr(key, tag, strlen(tag))) {
+ return true;
+ }
+ }
+ for (const char *tag : multiple_tags) {
+ if (is_numbered_tag_key(key, tag, ignore_case)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* Whether hash_arr has a string key that append_keywords() would add as a keyword */
+static bool has_keyword_keys(HashTable* hash_arr)
+{
+ zend_string *key;
+
+ ZEND_HASH_FOREACH_STR_KEY(hash_arr, key) {
+ if (key && !is_compose_subtag_key(key)) {
+ return true;
+ }
+ } ZEND_HASH_FOREACH_END();
+ return false;
+}
+
+/* Whether hash_arr has the "x" keyword, the private use part as locale_get_keywords() returns it */
+static bool has_private_use_keyword(HashTable* hash_arr)
+{
+ zend_string *key;
+
+ ZEND_HASH_FOREACH_STR_KEY(hash_arr, key) {
+ if (key && zend_string_equals_literal_ci(key, PRIVATE_PREFIX)) {
+ return true;
+ }
+ } ZEND_HASH_FOREACH_END();
+ return false;
+}
+
+/* Appends the "x" keyword (the private use part, as locale_get_keywords() returns it
+ * for "en-US-x-abc-def") as private subtags, in the same form as the private keys */
+static int append_private_use_keyword(smart_str* loc_name, const zend_string *value)
+{
+ const char *p = ZSTR_VAL(value);
+ const char *end = p + ZSTR_LEN(value);
+
+ if (p == end) {
+ return LOC_INVALID_KEYWORD;
+ }
+ for (const char *c = p; c < end; c++) {
+ bool is_separator = *c == '-' || *c == '_';
+ if (!is_separator && !isalnum(static_cast<unsigned char>(*c))) {
+ return LOC_INVALID_KEYWORD;
+ }
+ if (is_separator && (c == p || c + 1 == end || c[1] == '-' || c[1] == '_')) {
+ return LOC_INVALID_KEYWORD;
+ }
+ }
+
+ add_prefix(loc_name, LOC_PRIVATE_TAG);
+ while (p < end) {
+ const char *subtag_end = p;
+ while (subtag_end < end && *subtag_end != '-' && *subtag_end != '_') {
+ subtag_end++;
+ }
+ smart_str_appendl(loc_name, SEPARATOR, sizeof(SEPARATOR) - 1);
+ smart_str_appendl(loc_name, p, subtag_end - p);
+ p = subtag_end + 1;
+ }
+ return SUCCESS;
+}
+
+struct locale_keyword {
+ const char *key;
+ const char *type;
+};
+
+/* Called from locale_compose() with LOC_COMPOSE_ADD_KEYWORDS.
+ * Adds the entries of hash_arr that are not subtags as keywords (@key=value;...).
+ * The BCP 47 forms ("tz" => "nlams") are converted to the legacy ones that
+ * locale_get_keywords() returns ("timezone" => "Europe/Amsterdam"), and ICU sorts them.
+ * The "x" keyword is the private use part: it is added as private subtags, and
+ * locale_compose() then skips the private keys (locale_parse() returns both for
+ * "en-US-x-abc", but only the first subtag of "en-US-x-a-b").
+ * A key that differs from a subtag key only in case ("Region"), and two keys that give
+ * the same keyword ("tz" and "timezone"), are rejected instead of being guessed.
+ * Returns SUCCESS, FAILURE if a value is not a string, LOC_INVALID_KEYWORD,
+ * LOC_SUBTAG_KEY_CASE or LOC_DUPLICATE_KEYWORD. */
+static int append_keywords(smart_str* loc_name, HashTable* hash_arr)
+{
+ zend_string *key;
+ zval *ele_value;
+ /* emalloc'd rather than a std::vector, so that a bailout in emalloc() below cannot leak it */
+ std::unique_ptr<locale_keyword, char_deleter> keywords(static_cast<locale_keyword *>(
+ safe_emalloc(zend_hash_num_elements(hash_arr), sizeof(locale_keyword), 0)));
+ size_t keyword_count = 0;
+ zend_string *private_use = nullptr;
+
+ ZEND_HASH_FOREACH_STR_KEY_VAL(hash_arr, key, ele_value) {
+ if (!key || is_compose_subtag_key(key)) {
+ continue;
+ }
+ if (is_compose_subtag_key(key, true)) {
+ return LOC_SUBTAG_KEY_CASE;
+ }
+ ZVAL_DEREF(ele_value);
+ if (Z_TYPE_P(ele_value) != IS_STRING) {
+ return FAILURE;
+ }
+ if (ZSTR_LEN(key) != strlen(ZSTR_VAL(key)) || Z_STRLEN_P(ele_value) != strlen(Z_STRVAL_P(ele_value))) {
+ return LOC_INVALID_KEYWORD;
+ }
+ if (zend_string_equals_literal_ci(key, PRIVATE_PREFIX)) {
+ if (private_use) {
+ return LOC_DUPLICATE_KEYWORD;
+ }
+ private_use = Z_STR_P(ele_value);
+ continue;
+ }
+ const char *legacy_key = uloc_toLegacyKey(ZSTR_VAL(key));
+ const char *legacy_type = legacy_key ? uloc_toLegacyType(legacy_key, Z_STRVAL_P(ele_value)) : nullptr;
+ if (!legacy_type) {
+ return LOC_INVALID_KEYWORD;
+ }
+ /* ICU keeps the case of a legacy value ("EUR", "Europe/Amsterdam"): only use
+ * the converted one when it is really different, e.g. "nlams" */
+ if (zend_binary_strcasecmp(legacy_type, strlen(legacy_type), Z_STRVAL_P(ele_value), Z_STRLEN_P(ele_value)) == 0) {
+ legacy_type = Z_STRVAL_P(ele_value);
+ }
+ for (size_t i = 0; i < keyword_count; i++) {
+ if (strcasecmp(keywords.get()[i].key, legacy_key) == 0) {
+ return LOC_DUPLICATE_KEYWORD;
+ }
+ }
+ keywords.get()[keyword_count++] = {legacy_key, legacy_type};
+ } ZEND_HASH_FOREACH_END();
+
+ if (private_use) {
+ int result = append_private_use_keyword(loc_name, private_use);
+ if (result != SUCCESS) {
+ return result;
+ }
+ }
+ if (keyword_count == 0) {
+ return SUCCESS;
+ }
+
+ size_t base_len = loc_name->s ? ZSTR_LEN(loc_name->s) : 0;
+ size_t capacity = base_len + 2;
+ for (size_t i = 0; i < keyword_count; i++) {
+ capacity += strlen(keywords.get()[i].key) + strlen(keywords.get()[i].type) + 2;
+ }
+ if (capacity > INT32_MAX) {
+ return LOC_INVALID_KEYWORD;
+ }
+
+ char *buf = static_cast<char *>(emalloc(capacity));
+ if (base_len) {
+ memcpy(buf, ZSTR_VAL(loc_name->s), base_len);
+ }
+ buf[base_len] = '\0';
+
+ UErrorCode status = U_ZERO_ERROR;
+ int32_t len = static_cast<int32_t>(base_len);
+ for (size_t i = 0; i < keyword_count; i++) {
+ len = uloc_setKeywordValue(keywords.get()[i].key, keywords.get()[i].type, buf, static_cast<int32_t>(capacity), &status);
+ if (U_FAILURE(status)) {
+ efree(buf);
+ return LOC_INVALID_KEYWORD;
+ }
+ }
+
+ smart_str_free(loc_name);
+ smart_str_appendl(loc_name, buf, len);
+ efree(buf);
+ return SUCCESS;
+}
+
/*{{{
* If applicable sets error message and aborts locale_compose gracefully
* returns 0 if locale_compose needs to be aborted
@@ -994,6 +1204,20 @@ static int handleAppendResult( int result, smart_str* loc_name)
smart_str_free(loc_name);
return 0;
}
+ if (result == LOC_INVALID_KEYWORD || result == LOC_SUBTAG_KEY_CASE || result == LOC_DUPLICATE_KEYWORD
+ || result == LOC_GRANDFATHERED_KEYWORD) {
+ const char *msg = "parameter array contains an invalid keyword or keyword value";
+ if (result == LOC_SUBTAG_KEY_CASE) {
+ msg = "parameter array contains a key that differs from a subtag key only in case";
+ } else if (result == LOC_DUPLICATE_KEYWORD) {
+ msg = "parameter array contains two keys for the same keyword";
+ } else if (result == LOC_GRANDFATHERED_KEYWORD) {
+ msg = "parameter array contains keywords for a grandfathered tag";
+ }
+ intl_error_set(nullptr, U_ILLEGAL_ARGUMENT_ERROR, msg);
+ smart_str_free(loc_name);
+ return 0;
+ }
return 1;
}
/* }}} */
@@ -1010,11 +1234,19 @@ PHP_INTL_FUNCTION_WITH_ERROR_RESET(locale_compose)
zval* arr = nullptr;
HashTable* hash_arr = nullptr;
int result = 0;
+ zend_long flags = 0;
- ZEND_PARSE_PARAMETERS_START(1, 1)
+ ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY(arr)
+ Z_PARAM_OPTIONAL
+ Z_PARAM_LONG(flags)
ZEND_PARSE_PARAMETERS_END();
+ if (flags & ~LOC_COMPOSE_ADD_KEYWORDS) {
+ zend_argument_value_error(2, "must be 0 or Locale::COMPOSE_ADD_KEYWORDS");
+ RETURN_THROWS();
+ }
+
hash_arr = Z_ARRVAL_P( arr );
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 )
@@ -1023,6 +1255,11 @@ PHP_INTL_FUNCTION_WITH_ERROR_RESET(locale_compose)
/* Check for grandfathered first */
result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG);
if( result == SUCCESS){
+ /* A grandfathered tag cannot take keywords: do not drop them without a word */
+ if ((flags & LOC_COMPOSE_ADD_KEYWORDS) && has_keyword_keys(hash_arr)) {
+ handleAppendResult(LOC_GRANDFATHERED_KEYWORD, loc_name);
+ RETURN_FALSE;
+ }
RETURN_SMART_STR(loc_name);
}
if( !handleAppendResult( result, loc_name)){
@@ -1064,10 +1301,20 @@ PHP_INTL_FUNCTION_WITH_ERROR_RESET(locale_compose)
RETURN_FALSE;
}
- /* Private */
- result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG);
- if( !handleAppendResult( result, loc_name)){
- RETURN_FALSE;
+ /* Private, unless append_keywords() adds the whole private use part from the "x" keyword */
+ if (!(flags & LOC_COMPOSE_ADD_KEYWORDS) || !has_private_use_keyword(hash_arr)) {
+ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG);
+ if( !handleAppendResult( result, loc_name)){
+ RETURN_FALSE;
+ }
+ }
+
+ /* Keywords */
+ if (flags & LOC_COMPOSE_ADD_KEYWORDS) {
+ result = append_keywords(loc_name, hash_arr);
+ if (!handleAppendResult(result, loc_name)) {
+ RETURN_FALSE;
+ }
}
RETURN_SMART_STR(loc_name);
diff --git a/ext/intl/php_intl.stub.php b/ext/intl/php_intl.stub.php
index 5141f4c7262..167b3344b2b 100644
--- a/ext/intl/php_intl.stub.php
+++ b/ext/intl/php_intl.stub.php
@@ -495,7 +495,7 @@ function locale_get_display_keyword(string $keyword, ?string $displayLocale = nu
function locale_get_display_keyword_value(string $locale, string $keyword, ?string $displayLocale = null): string|false {}
-function locale_compose(array $subtags): string|false {}
+function locale_compose(array $subtags, int $flags = 0): string|false {}
function locale_parse(string $locale): ?array {}
diff --git a/ext/intl/php_intl_arginfo.h b/ext/intl/php_intl_arginfo.h
index e98d5f8c2e6..7d3edf3c5f7 100644
Binary files a/ext/intl/php_intl_arginfo.h and b/ext/intl/php_intl_arginfo.h differ
diff --git a/ext/intl/tests/locale_bug74439.phpt b/ext/intl/tests/locale_bug74439.phpt
index 5d9a8086be6..8de99d75bd0 100644
--- a/ext/intl/tests/locale_bug74439.phpt
+++ b/ext/intl/tests/locale_bug74439.phpt
@@ -35,7 +35,7 @@
getDefault: 0, 0
acceptFromHttp: 2, 1
canonicalize: 1, 1
-composeLocale: 1, 1
+composeLocale: 2, 1
getAllVariants: 1, 1
getKeywords: 1, 1
getPrimaryLanguage: 1, 1
diff --git a/ext/intl/tests/locale_compose_add_keywords.phpt b/ext/intl/tests/locale_compose_add_keywords.phpt
new file mode 100644
index 00000000000..9f9a10ebeba
--- /dev/null
+++ b/ext/intl/tests/locale_compose_add_keywords.phpt
@@ -0,0 +1,200 @@
+--TEST--
+Locale::composeLocale() with Locale::COMPOSE_ADD_KEYWORDS adds keywords (GH-20393)
+--EXTENSIONS--
+intl
+--FILE--
+<?php
+
+function show(string|false $result): void
+{
+ var_dump($result);
+ if ($result === false) {
+ echo intl_get_error_message(), PHP_EOL;
+ }
+}
+
+echo "-- GH-20393: change language and region, keep the keywords\n";
+$first = 'en_US@timezone=Europe/Amsterdam';
+$merged = [
+ ...Locale::parseLocale($first),
+ ...Locale::getKeywords($first) ?? [],
+ ...Locale::parseLocale('nl_NL'),
+];
+show(Locale::composeLocale($merged));
+show(Locale::composeLocale($merged, Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- BCP 47 keys and types become the legacy ones\n";
+show(Locale::composeLocale(['language' => 'en', 'region' => 'US', 'tz' => 'nlams'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'de', 'ca' => 'gregory', 'cu' => 'eur'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Legacy values keep their case, as in getKeywords() and canonicalize()\n";
+show(Locale::composeLocale(['language' => 'en', 'calendar' => 'Buddhist', 'currency' => 'EUR'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Several keywords are sorted, with script and variants\n";
+show(Locale::composeLocale([
+ 'language' => 'sr',
+ 'script' => 'Latn',
+ 'region' => 'RS',
+ 'variant0' => 'POSIX',
+ 'numbers' => 'latn',
+ 'currency' => 'RSD',
+ 'calendar' => 'gregorian',
+], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Round trip of parseLocale() + getKeywords()\n";
+foreach ([
+ 'en_US@timezone=Europe/Amsterdam',
+ 'de_DE@collation=phonebook;currency=EUR',
+ 'ja_JP@calendar=japanese',
+ 'zh_Hant_TW@collation=stroke',
+ 'fr',
+] as $locale) {
+ $parts = [...Locale::parseLocale($locale), ...Locale::getKeywords($locale) ?? []];
+ $composed = Locale::composeLocale($parts, Locale::COMPOSE_ADD_KEYWORDS);
+ echo $locale, ' => ', $composed, ' ', $composed === $locale ? 'same' : 'DIFFERENT', PHP_EOL;
+}
+
+echo "-- BCP 47 input: getKeywords() reads the extensions, the private use part is not repeated\n";
+foreach ([
+ 'en-US-u-tz-nlams',
+ 'de-DE-1996-u-co-phonebk',
+ 'sr-Latn-RS-u-nu-latn',
+ 'ja-JP-u-ca-japanese-x-foo',
+ 'en-US-x-private',
+] as $locale) {
+ $parts = [...Locale::parseLocale($locale), ...Locale::getKeywords($locale) ?? []];
+ echo $locale, ' => ', Locale::composeLocale($parts, Locale::COMPOSE_ADD_KEYWORDS), PHP_EOL;
+}
+
+echo "-- The x keyword alone is the private use part\n";
+show(Locale::composeLocale(['language' => 'en', 'x' => 'abc-def', 'calendar' => 'buddhist'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'x' => 'a--b'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Without the flag nothing changes\n";
+show(Locale::composeLocale(['language' => 'en', 'region' => 'US', 'calendar' => 'buddhist']));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => []]));
+
+echo "-- Integer keys are ignored, as without the flag\n";
+show(Locale::composeLocale(['language' => 'en', 0 => 'ignored', 'currency' => 'USD'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Errors\n";
+show(Locale::composeLocale(['language' => 'en', 'cal endar' => 'buddhist'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => 'bud;dhist'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => "bud\0dhist"], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => []], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => ''], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', '' => 'buddhist'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', "cal\0endar" => 'buddhist'], Locale::COMPOSE_ADD_KEYWORDS));
+// uloc_setKeywordValue() fails for a value this long before ICU 75, and accepts it since
+$long = str_repeat('a', 100);
+$result = Locale::composeLocale(['language' => 'en', 'calendar' => $long], Locale::COMPOSE_ADD_KEYWORDS);
+var_dump(version_compare(INTL_ICU_VERSION, '75', '<')
+ ? $result === false && intl_get_error_code() === U_ILLEGAL_ARGUMENT_ERROR
+ : $result === "en@calendar=$long");
+foreach ([2, -1] as $flags) {
+ try {
+ Locale::composeLocale(['language' => 'en'], $flags);
+ } catch (ValueError $e) {
+ echo $e->getMessage(), PHP_EOL;
+ }
+}
+var_dump(Locale::composeLocale(['language' => 'en', 'currency' => 'EUR'], Locale::COMPOSE_ADD_KEYWORDS), intl_get_error_code());
+
+echo "-- A key that differs from a subtag key only in case is rejected\n";
+show(Locale::composeLocale(['language' => 'en', 'LANGUAGE' => 'de'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'Region' => 'US'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'Variant0' => 'POSIX'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Two keys for the same keyword are rejected\n";
+show(Locale::composeLocale(['language' => 'en', 'tz' => 'nlams', 'timezone' => 'Europe/Paris'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'calendar' => 'buddhist', 'Calendar' => 'japanese'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['language' => 'en', 'x' => 'abc', 'X' => 'def'], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- A grandfathered tag takes no keywords\n";
+show(Locale::composeLocale(['grandfathered' => 'i-klingon', 'calendar' => 'buddhist'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['grandfathered' => 'i-klingon'], Locale::COMPOSE_ADD_KEYWORDS));
+show(Locale::composeLocale(['grandfathered' => 'i-klingon', 'calendar' => 'buddhist']));
+
+echo "-- Values by reference\n";
+$calendar = 'buddhist';
+show(Locale::composeLocale(['language' => 'en', 'calendar' => &$calendar], Locale::COMPOSE_ADD_KEYWORDS));
+
+echo "-- Procedural\n";
+show(locale_compose(['language' => 'pt', 'region' => 'BR', 'currency' => 'BRL'], Locale::COMPOSE_ADD_KEYWORDS));
+
+?>
+--EXPECT--
+-- GH-20393: change language and region, keep the keywords
+string(5) "nl_NL"
+string(31) "nl_NL@timezone=Europe/Amsterdam"
+-- BCP 47 keys and types become the legacy ones
+string(31) "en_US@timezone=Europe/Amsterdam"
+string(34) "de@calendar=gregorian;currency=eur"
+-- Legacy values keep their case, as in getKeywords() and canonicalize()
+string(33) "en@calendar=Buddhist;currency=EUR"
+-- Several keywords are sorted, with script and variants
+string(61) "sr_Latn_RS_POSIX@calendar=gregorian;currency=RSD;numbers=latn"
+-- Round trip of parseLocale() + getKeywords()
+en_US@timezone=Europe/Amsterdam => en_US@timezone=Europe/Amsterdam same
+de_DE@collation=phonebook;currency=EUR => de_DE@collation=phonebook;currency=EUR same
+ja_JP@calendar=japanese => ja_JP@calendar=japanese same
+zh_Hant_TW@collation=stroke => zh_Hant_TW@collation=stroke same
+fr => fr same
+-- BCP 47 input: getKeywords() reads the extensions, the private use part is not repeated
+en-US-u-tz-nlams => en_US@timezone=Europe/Amsterdam
+de-DE-1996-u-co-phonebk => de_DE_1996@collation=phonebook
+sr-Latn-RS-u-nu-latn => sr_Latn_RS@numbers=latn
+ja-JP-u-ca-japanese-x-foo => ja_JP_x_foo@calendar=japanese
+en-US-x-private => en_US_x_private
+-- The x keyword alone is the private use part
+string(30) "en_x_abc_def@calendar=buddhist"
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+-- Without the flag nothing changes
+string(5) "en_US"
+string(2) "en"
+-- Integer keys are ignored, as without the flag
+string(15) "en@currency=USD"
+-- Errors
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array element is not a string: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains an invalid keyword or keyword value: U_ILLEGAL_ARGUMENT_ERROR
+bool(true)
+Locale::composeLocale(): Argument #2 ($flags) must be 0 or Locale::COMPOSE_ADD_KEYWORDS
+Locale::composeLocale(): Argument #2 ($flags) must be 0 or Locale::COMPOSE_ADD_KEYWORDS
+string(15) "en@currency=EUR"
+int(0)
+-- A key that differs from a subtag key only in case is rejected
+bool(false)
+Locale::composeLocale(): parameter array contains a key that differs from a subtag key only in case: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains a key that differs from a subtag key only in case: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains a key that differs from a subtag key only in case: U_ILLEGAL_ARGUMENT_ERROR
+-- Two keys for the same keyword are rejected
+bool(false)
+Locale::composeLocale(): parameter array contains two keys for the same keyword: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains two keys for the same keyword: U_ILLEGAL_ARGUMENT_ERROR
+bool(false)
+Locale::composeLocale(): parameter array contains two keys for the same keyword: U_ILLEGAL_ARGUMENT_ERROR
+-- A grandfathered tag takes no keywords
+bool(false)
+Locale::composeLocale(): parameter array contains keywords for a grandfathered tag: U_ILLEGAL_ARGUMENT_ERROR
+string(9) "i-klingon"
+string(9) "i-klingon"
+-- Values by reference
+string(20) "en@calendar=buddhist"
+-- Procedural
+string(18) "pt_BR@currency=BRL"
diff --git a/ext/intl/tests/locale_compose_add_keywords_private.phpt b/ext/intl/tests/locale_compose_add_keywords_private.phpt
new file mode 100644
index 00000000000..842630af5de
--- /dev/null
+++ b/ext/intl/tests/locale_compose_add_keywords_private.phpt
@@ -0,0 +1,24 @@
+--TEST--
+Locale::composeLocale() with Locale::COMPOSE_ADD_KEYWORDS keeps the whole private use part and any keyword
+--EXTENSIONS--
+intl
+--FILE--
+<?php
+
+foreach ([
+ 'ja-JP-u-ca-japanese-x-a-b',
+ 'en-US-x-a-b',
+] as $locale) {
+ $parts = [...Locale::parseLocale($locale), ...Locale::getKeywords($locale) ?? []];
+ echo $locale, ' => ', Locale::composeLocale($parts, Locale::COMPOSE_ADD_KEYWORDS), PHP_EOL;
+}
+
+var_dump(Locale::composeLocale(['language' => 'en', 'private0' => 'a', 'x' => 'a-b'], Locale::COMPOSE_ADD_KEYWORDS));
+var_dump(Locale::composeLocale(['language' => 'en', 'name' => 'English'], Locale::COMPOSE_ADD_KEYWORDS));
+
+?>
+--EXPECT--
+ja-JP-u-ca-japanese-x-a-b => ja_JP_x_a_b@calendar=japanese
+en-US-x-a-b => en_US_x_a_b
+string(8) "en_x_a_b"
+string(15) "en@name=English"