Decamelize function (#6615)

* New decamelize helper.

* Add additional tests
This commit is contained in:
Lonnie Ezell 2022-10-02 23:05:05 -05:00 committed by GitHub
parent e6f640632f
commit 514e535ef7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 67 additions and 0 deletions

View File

@ -185,6 +185,21 @@ if (! function_exists('underscore')) {
}
}
if (! function_exists('decamelize')) {
/**
* Decamelize
*
* Takes multiple words separated by camel case and
* underscores them.
*
* @param string $string Input string
*/
function decamelize(string $string): string
{
return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', trim($string)));
}
}
if (! function_exists('humanize')) {
/**
* Humanize

View File

@ -285,4 +285,41 @@ final class InflectorHelperTest extends CIUnitTestCase
$this->assertSame($suffixed, $ordinalized);
}
}
public function testDecamelizeToSnakeCase()
{
$strings = [
'simpleTest' => 'simple_test',
'easy' => 'easy',
'HTML' => 'html',
'simpleXML' => 'simple_xml',
'PDFLoad' => 'pdf_load',
'startMIDDLELast' => 'start_middle_last',
'AString' => 'a_string',
'Some4Numbers234' => 'some4_numbers234',
'TEST123String' => 'test123_string',
'hello_world' => 'hello_world',
'hello___world' => 'hello___world',
'_hello_world_' => '_hello_world_',
'HelloWorld' => 'hello_world',
'helloWorldFoo' => 'hello_world_foo',
'hello_World' => 'hello_world',
'hello-world' => 'hello-world',
'myHTMLFiLe' => 'my_html_fi_le',
'aBaBaB' => 'a_ba_ba_b',
'BaBaBa' => 'ba_ba_ba',
'libC' => 'lib_c',
'a' => 'a',
'A' => 'a',
'aB' => 'a_b',
'AB' => 'ab',
'ab' => 'ab',
'Ab' => 'ab',
];
foreach ($strings as $camelized => $expects) {
$underscored = decamelize($camelized);
$this->assertSame($expects, $underscored);
}
}
}

View File

@ -148,6 +148,7 @@ Helpers and Functions
- Added new Form helper function :php:func:`validation_errors()`, :php:func:`validation_list_errors()` and :php:func:`validation_show_error()` to display Validation Errors.
- You can set the locale to :php:func:`route_to()` if you pass a locale value as the last parameter.
- Added :php:func:`request()` and :php:func:`response()` functions.
- Add :php:func:`decamelize()` function to convert camelCase to snake_case.
Others
======

View File

@ -85,6 +85,17 @@ The following functions are available:
.. literalinclude:: inflector_helper/007.php
.. php:function:: decamelize($string)
:param string $string: Input string
:returns: String containing underscores between words
:rtype: string
Takes multiple words in camelCase or PascalCase and converts them to snake_case.
Example:
.. literalinclude:: inflector_helper/007.php
.. php:function:: humanize($string[, $separator = '_'])
:param string $string: Input string

View File

@ -0,0 +1,3 @@
<?php
echo decamelize('myDogSpot'); // Prints 'my_dog_spot'