Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions Tests/StringHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Joomla\String\StringHelper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;

/**
Expand Down Expand Up @@ -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
*
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
22 changes: 22 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
@@ -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.
111 changes: 76 additions & 35 deletions src/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@
],
];

/**
* Collators by locale, used by strcmp() and strcasecmp().
*
* @var array<string, \Collator|null>
* @since __DEPLOY_VERSION__
*/
private static $collators = [];

/**
* Increments a trailing number in a string.
*
Expand Down Expand Up @@ -330,7 +338,7 @@
*/
public static function str_pad($input, $length, $padStr = ' ', $type = STR_PAD_RIGHT)
{
return mb_str_pad($input, $length, $padStr, $type);

Check failure on line 341 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_str_pad not found.
}

/**
Expand All @@ -356,15 +364,18 @@
*
* 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)
Expand All @@ -375,55 +386,84 @@
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);
}

/**
* UTF-8/LOCALE aware alternative to strcmp()
*
* 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;
}
Expand All @@ -443,9 +483,10 @@
}

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);
}

/**
Expand Down Expand Up @@ -605,10 +646,10 @@
}

if ($charlist === false) {
return mb_ltrim($str);

Check failure on line 649 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_ltrim not found.
}

return mb_ltrim($str, $charlist);

Check failure on line 652 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_ltrim not found.
}

/**
Expand All @@ -632,10 +673,10 @@
}

if ($charlist === false) {
return mb_rtrim($str);

Check failure on line 676 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_rtrim not found.
}

return mb_rtrim($str, $charlist);

Check failure on line 679 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_rtrim not found.
}

/**
Expand All @@ -659,10 +700,10 @@
}

if ($charlist === false) {
return mb_trim($str);

Check failure on line 703 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_trim not found.
}

return mb_trim($str, $charlist);

Check failure on line 706 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_trim not found.
}

/**
Expand All @@ -684,14 +725,14 @@
public static function ucfirst($str, $delimiter = null, $newDelimiter = null)
{
if ($delimiter === null) {
return mb_ucfirst($str);

Check failure on line 728 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Function mb_ucfirst not found.
}

if ($newDelimiter === null) {
$newDelimiter = $delimiter;
}

return implode($newDelimiter, array_map('mb_ucfirst', explode($delimiter, $str)));

Check failure on line 735 in src/StringHelper.php

View workflow job for this annotation

GitHub Actions / framework-ci / Run PHPstan

Parameter #1 $callback of function array_map expects (callable(string): mixed)|null, 'mb_ucfirst' given.
}

/**
Expand Down
Loading