From c900b98eb5486517503cc118f878ae5f52d98b8b Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Fri, 13 Nov 2026 01:16:21 +0100 Subject: [PATCH] Compare strings with a locale using Collator StringHelper::strcmp() and strcasecmp() with a locale called setlocale(LC_COLLATE, $locale) and never restored the previous locale. setlocale() is process-wide, so every comparison changed the collation of unrelated code, including other threads under ZTS. strcoll() is also deprecated as of PHP 8.6. Compare with the Collator class of ext-intl instead, which neither touches the process locale nor needs strcoll(). Without ext-intl, keep the setlocale()/strcoll() path but restore the locale afterwards, and deprecate it. From PHP 8.6 on, the fallback compares bytes instead of calling the deprecated strcoll(). Co-Authored-By: Claude Opus 5.5 --- Tests/StringHelperTest.php | 92 ++++++++++++++++++++++++++++++ composer.json | 1 + docs/overview.md | 22 ++++++++ src/StringHelper.php | 111 +++++++++++++++++++++++++------------ 4 files changed, 191 insertions(+), 35 deletions(-) diff --git a/Tests/StringHelperTest.php b/Tests/StringHelperTest.php index 8d6fd578..1408df69 100644 --- a/Tests/StringHelperTest.php +++ b/Tests/StringHelperTest.php @@ -9,6 +9,7 @@ use Joomla\String\StringHelper; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\TestCase; /** @@ -702,6 +703,97 @@ public function testStrcmp(string $string1, string $string2, $locale, int $expec $this->assertEquals($expected, $actual); } + /** + * Data provider for testStrcmpWithCollator + * + * @return array + */ + public static function seedTestStrcmpWithCollator(): array + { + return [ + ['a', 'B', 'fr_FR', -1], + ['B', 'a', 'fr_FR', 1], + ['Àbc', 'abc', 'fr_FR.UTF-8', 1], + ['Àbc', 'bcd', 'fr_FR', -1], + ['É', 'è', 'fr_FR', -1], + ['é', 'È', 'fr_FR', -1], + ['Œ', 'p', 'fr_FR', -1], + ['Œ', 'n', 'fr_FR', 1], + ['abc', 'abc', 'fr_FR', 0], + ]; + } + + /** + * @testdox strcmp() with a locale compares with the collation rules of that locale + * + * @param string $string1 String 1 to compare + * @param string $string2 String 2 to compare + * @param string $locale The locale + * @param integer $expected Expected result + */ + #[DataProvider('seedTestStrcmpWithCollator')] + #[RequiresPhpExtension('intl')] + public function testStrcmpWithCollator(string $string1, string $string2, string $locale, int $expected) + { + $this->assertSame($expected, StringHelper::strcmp($string1, $string2, $locale) <=> 0); + } + + /** + * Data provider for testStrcasecmpWithCollator + * + * @return array + */ + public static function seedTestStrcasecmpWithCollator(): array + { + return [ + ['THIS IS STRING1', 'this is string1', 'fr_FR', 0], + ['àbc', 'abc', 'fr_FR', 1], + ['àbc', 'bcd', 'fr_FR.UTF-8', -1], + ['é', 'è', 'fr_FR', -1], + ['É', 'é', 'fr_FR', 0], + ['œ', 'p', 'fr_FR', -1], + ['œ', 'n', 'fr_FR', 1], + ]; + } + + /** + * @testdox strcasecmp() with a locale compares with the collation rules of that locale + * + * @param string $string1 String 1 to compare + * @param string $string2 String 2 to compare + * @param string $locale The locale + * @param integer $expected Expected result + */ + #[DataProvider('seedTestStrcasecmpWithCollator')] + #[RequiresPhpExtension('intl')] + public function testStrcasecmpWithCollator(string $string1, string $string2, string $locale, int $expected) + { + $this->assertSame($expected, StringHelper::strcasecmp($string1, $string2, $locale) <=> 0); + } + + /** + * @testdox strcmp() and strcasecmp() with a locale do not change the process-wide LC_COLLATE locale + */ + public function testComparisonWithLocaleKeepsProcessLocale() + { + $original = setlocale(LC_COLLATE, '0'); + $other = setlocale(LC_COLLATE, 'de_DE.UTF-8', 'de_DE.utf8', 'de_DE', 'German_Germany.1252', 'en_US.UTF-8', 'en_US.utf8', 'C.UTF-8'); + + if ($other === false || $other === 'C') { + setlocale(LC_COLLATE, $original); + $this->markTestSkipped('No locale other than "C" is available.'); + } + + try { + StringHelper::strcmp('a', 'b', 'C'); + StringHelper::strcasecmp('a', 'b', 'C'); + + $this->assertSame($other, setlocale(LC_COLLATE, '0')); + } finally { + setlocale(LC_COLLATE, $original); + } + } + /** * @testdox UTF-8 aware strcspn() is performed on a string * diff --git a/composer.json b/composer.json index 5ddf279e..b2d4402d 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,7 @@ }, "suggest": { "ext-mbstring": "For improved processing", + "ext-intl": "To compare strings with a locale in StringHelper::strcmp() and StringHelper::strcasecmp()", "doctrine/inflector": "To use the string inflector" }, "autoload": { diff --git a/docs/overview.md b/docs/overview.md index 5c220497..5b8d2087 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,3 +1,25 @@ # String package TODO + +## Comparing strings with a locale + +`StringHelper::strcmp($str1, $str2, $locale)` and `StringHelper::strcasecmp($str1, $str2, $locale)` +compare two UTF-8 strings with the collation rules of `$locale` when a locale is given. They use the +`Collator` class of the `intl` extension, so install `ext-intl` to use them: + +```php +use Joomla\String\StringHelper; + +StringHelper::strcmp('a', 'B', 'fr_FR'); // < 0 (byte comparison: > 0) +StringHelper::strcasecmp('É', 'é', 'fr_FR'); // 0 +``` + +The locale is an ICU locale identifier such as `fr_FR`; a POSIX suffix like `.UTF-8` is ignored. +The process-wide locale (`setlocale()`) is not changed. ICU uses the root collation for locales it +does not know, such as Windows names like `French_Standard`. + +Without `ext-intl`, both methods fall back to `setlocale(LC_COLLATE, $locale)` and `strcoll()`, and +restore the previous `LC_COLLATE` locale afterwards. This fallback is deprecated and triggers a +deprecation notice: `strcoll()` itself is deprecated as of PHP 8.6, and from PHP 8.6 on the fallback +compares the strings byte by byte instead. diff --git a/src/StringHelper.php b/src/StringHelper.php index 98f73e7d..cce0eac0 100644 --- a/src/StringHelper.php +++ b/src/StringHelper.php @@ -36,6 +36,14 @@ abstract class StringHelper ], ]; + /** + * Collators by locale, used by strcmp() and strcasecmp(). + * + * @var array + * @since __DEPLOY_VERSION__ + */ + private static $collators = []; + /** * Increments a trailing number in a string. * @@ -356,15 +364,18 @@ public static function str_split($str, $splitLen = 1) * * A case insensitive string comparison. * + * With a locale, the strings are compared with the collation rules of that locale, using the Collator class of the intl + * extension. The process-wide locale is not changed. Without the intl extension, the comparison falls back to setlocale() + * and strcoll(), which is deprecated. + * * @param string $str1 string 1 to compare * @param string $str2 string 2 to compare - * @param string|boolean $locale The locale used by strcoll or false to use classical comparison + * @param string|boolean $locale The locale used for the collation or false to use classical comparison * * @return integer Either < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. * * @link https://www.php.net/strcasecmp - * @link https://www.php.net/strcoll - * @link https://www.php.net/setlocale + * @link https://www.php.net/collator.compare * @since 1.3.0 */ public static function strcasecmp($str1, $str2, $locale = false) @@ -375,31 +386,7 @@ public static function strcasecmp($str1, $str2, $locale = false) return strcmp($strX, $strY); } - // Get current locale - $locale0 = setlocale(LC_COLLATE, '0'); - - if (!$locale = setlocale(LC_COLLATE, $locale)) { - $locale = $locale0; - } - - // See if we have successfully set locale to UTF-8 - if (!stristr($locale, 'UTF-8') && stristr($locale, '_') && preg_match('~\.(\d+)$~', $locale, $m)) { - $encoding = 'CP' . $m[1]; - } elseif (stristr($locale, 'UTF-8') || stristr($locale, 'utf8')) { - $encoding = 'UTF-8'; - } else { - $encoding = 'nonrecodable'; - } - - // If we successfully set encoding it to utf-8 or encoding is sth weird don't recode - if ($encoding == 'UTF-8' || $encoding == 'nonrecodable') { - return strcoll(mb_strtolower($str1), mb_strtolower($str2)); - } - - return strcoll( - static::transcode(mb_strtolower($str1), 'UTF-8', $encoding), - static::transcode(mb_strtolower($str2), 'UTF-8', $encoding) - ); + return self::compareWithLocale(mb_strtolower($str1), mb_strtolower($str2), $locale); } /** @@ -407,23 +394,76 @@ public static function strcasecmp($str1, $str2, $locale = false) * * A case sensitive string comparison. * + * With a locale, the strings are compared with the collation rules of that locale, using the Collator class of the intl + * extension. The process-wide locale is not changed. Without the intl extension, the comparison falls back to setlocale() + * and strcoll(), which is deprecated. + * * @param string $str1 string 1 to compare * @param string $str2 string 2 to compare - * @param mixed $locale The locale used by strcoll or false to use classical comparison + * @param mixed $locale The locale used for the collation or false to use classical comparison * * @return integer Either < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. * * @link https://www.php.net/strcmp - * @link https://www.php.net/strcoll - * @link https://www.php.net/setlocale + * @link https://www.php.net/collator.compare * @since 1.3.0 */ public static function strcmp($str1, $str2, $locale = false) { if ($locale) { - // Get current locale - $locale0 = setlocale(LC_COLLATE, '0'); + return self::compareWithLocale($str1, $str2, $locale); + } + + return strcmp($str1, $str2); + } + + /** + * Compares two UTF-8 strings with the collation rules of a locale. + * + * @param string $str1 String 1 to compare + * @param string $str2 String 2 to compare + * @param string|string[] $locale The locale, or a list of locales to try with setlocale() + * + * @return integer Either < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. + * + * @since __DEPLOY_VERSION__ + */ + private static function compareWithLocale(string $str1, string $str2, $locale): int + { + $collatorLocale = (string) (\is_array($locale) ? reset($locale) : $locale); + + if (class_exists(\Collator::class)) { + if (!\array_key_exists($collatorLocale, self::$collators)) { + try { + self::$collators[$collatorLocale] = new \Collator($collatorLocale); + } catch (\Throwable $e) { + self::$collators[$collatorLocale] = null; + } + } + + $result = self::$collators[$collatorLocale] ? self::$collators[$collatorLocale]->compare($str1, $str2) : false; + + if ($result !== false) { + return $result; + } + } + + trigger_deprecation( + 'joomla/string', + '__DEPLOY_VERSION__', + 'Comparing strings with a locale in %1$s::strcmp() and %1$s::strcasecmp() without the intl extension is deprecated. Install the intl extension.', + self::class + ); + + // strcoll() is deprecated as of PHP 8.6 + if (\PHP_VERSION_ID >= 80600 || !\function_exists('strcoll')) { + return strcmp($str1, $str2); + } + // Get current locale + $locale0 = setlocale(LC_COLLATE, '0'); + + try { if (!$locale = setlocale(LC_COLLATE, $locale)) { $locale = $locale0; } @@ -443,9 +483,10 @@ public static function strcmp($str1, $str2, $locale = false) } return strcoll(static::transcode($str1, 'UTF-8', $encoding), static::transcode($str2, 'UTF-8', $encoding)); + } finally { + // Restore the process-wide locale + setlocale(LC_COLLATE, $locale0); } - - return strcmp($str1, $str2); } /**