N°5655 - Add utils::ToSnakeCase() method

This commit is contained in:
Molkobain
2022-12-13 11:40:51 +01:00
parent 7083e1263d
commit 32297d93dd
2 changed files with 86 additions and 4 deletions

View File

@@ -3045,18 +3045,35 @@ HTML;
}
/**
* Transform a snake_case $sInput into a CamelCase string
*
* @param string $sInput
*
* @return string
* @return string Camel case representation of $sInput (eg. "something_new" becomes "SomethingNew")
* @since 2.7.0
*/
public static function ToCamelCase($sInput)
public static function ToCamelCase($sInput): string
{
return str_replace(' ', '', ucwords(strtr($sInput, '_-', ' ')));
}
/**
* @param string $sInput
*
* @return string Snake case representation of $sInput (eg. "SomethingNew" becomes "something_new")
* @since 3.1.0
* @link https://stackoverflow.com/a/19533226/2710325
*/
public static function ToSnakeCase(string $sInput): string
{
// Remove special chars to join words
$sOutput = preg_replace('/(\W)/', '_', $sInput);
// Transform camel case words to snake case
$sOutput = preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $sOutput);
// Lowercase everything
$sOutput = mb_strtolower($sOutput);
// Trim outer underscores
return trim($sOutput, '_');
}
/**
* @param string $sInput
*

View File

@@ -469,6 +469,71 @@ class UtilsTest extends ItopTestCase
];
}
/**
* @dataProvider ToSnakeCaseProvider
* @covers utils::ToSnakeCase
*
* @param string $sInput
* @param string $sExpectedOutput
*
* @return void
*/
public function testToSnakeCase(string $sInput, string $sExpectedOutput)
{
$sTestedOutput = utils::ToSnakeCase($sInput);
$this->assertEquals($sExpectedOutput, $sTestedOutput, "Snake case transformation for '$sInput' doesn't match. Got '$sTestedOutput', expected '$sExpectedOutput'.");
}
/**
* @since 3.1.0
* @return \string[][]
*/
public function ToSnakeCaseProvider(): array
{
return [
'One word lowercase' => [
'hello',
'hello',
],
'One word uppercase' => [
'HELLO',
'hello',
],
'One word capitalize' => [
'Hello',
'hello',
],
'Two words separated with space' => [
'hello world',
'hello_world',
],
'Two words separated with underscore' => [
'hello_world',
'hello_world',
],
'Two words separated with dash' => [
'hello-world',
'hello_world',
],
'Two words separated with dot' => [
'hello.world',
'hello_world',
],
'Two words camel cased' => [
'HelloWorld',
'hello_world',
],
'Two words camel cased with acronym' => [
'HTMLWorld',
'html_world',
],
'Three words separated with underscore and space' => [
'hello_there world',
'hello_there_world',
],
];
}
/**
* @dataProvider ToAcronymProvider
* @covers utils::ToAcronym