Skip to content

Commit

Permalink
Merge pull request #29 from citrus-framework/add_snake_case
Browse files Browse the repository at this point in the history
snakeCase処理の追加
  • Loading branch information
take64 committed Jul 24, 2020
2 parents 23968ba + 92bdde8 commit 8d0a7b2
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Variable/Strings.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,38 @@ public static function upperCamelCase(string $context, string $delimiter = '_'):
// 連結して返却
return implode('', $converted_parts);
}



/**
* 文字列をスネークケースに変換する
*
* @param string $context 対象文字列
* @param string $glue グルー文字列
* @return string
*/
public static function snakeCase(string $context, string $glue = '_'): string
{
$result = '';
$ascii_a = ord('A');
$ascii_z = ord('Z');

$length = strlen($context);
for ($pos = 0; $pos < $length; $pos++)
{
$char = substr($context, $pos, 1);
$ascii_dec = ord($char);
// 先頭文字以外で
// 文字が大文字の範囲
if (0 < $pos and ($ascii_a <= $ascii_dec and $ascii_dec <= $ascii_z))
{
// 大文字の前にグルー文字列をつける
$result .= $glue;
}

$result .= strtolower($char);
}

return $result;
}
}
15 changes: 15 additions & 0 deletions tests/Variable/StringsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,19 @@ public function upperCamelCase_想定通り()
// 検算
$this->assertSame('ApplicationName', Strings::upperCamelCase($snake_case_context));
}


/**
* @test
*/
public function snakeCase_想定通り()
{
// アッパーキャメルケース
$upper_camel_case_context = 'ApplicationName';
$this->assertSame('application_name', Strings::snakeCase($upper_camel_case_context));

// ロウアーキャメルケース
$lower_camel_case_context = 'applicationName';
$this->assertSame('application_name', Strings::snakeCase($lower_camel_case_context));
}
}

0 comments on commit 8d0a7b2

Please sign in to comment.