Skip to content

Commit b974c57

Browse files
kubawerlosSpacePossum
authored andcommitted
DX: simplify Utils::camelCaseToUnderscore
1 parent a8385e5 commit b974c57

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

src/Utils.php

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,21 +45,15 @@ public static function calculateBitmask(array $options)
4545
}
4646

4747
/**
48-
* Converts a camel cased string to an snake cased string.
48+
* Converts a camel cased string to a snake cased string.
4949
*
5050
* @param string $string
5151
*
5252
* @return string
5353
*/
5454
public static function camelCaseToUnderscore($string)
5555
{
56-
return Preg::replaceCallback(
57-
'/(^|[a-z0-9])([A-Z])/',
58-
static function (array $matches) {
59-
return strtolower('' !== $matches[1] ? $matches[1].'_'.$matches[2] : $matches[2]);
60-
},
61-
$string
62-
);
56+
return strtolower(Preg::replace('/(?<!^)((?=[A-Z][^A-Z])|(?<![A-Z])(?=[A-Z]))/', '_', $string));
6357
}
6458

6559
/**

tests/UtilsTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,34 @@ public function provideCamelCaseToUnderscoreCases()
6363
[
6464
'utf8_encoder_fixer',
6565
],
66+
[
67+
'a',
68+
'A',
69+
],
70+
[
71+
'aa',
72+
'AA',
73+
],
74+
[
75+
'foo',
76+
'FOO',
77+
],
78+
[
79+
'foo_bar_baz',
80+
'FooBarBAZ',
81+
],
82+
[
83+
'foo_bar_baz',
84+
'FooBARBaz',
85+
],
86+
[
87+
'foo_bar_baz',
88+
'FOOBarBaz',
89+
],
90+
[
91+
'mr_t',
92+
'MrT',
93+
],
6694
];
6795
}
6896

0 commit comments

Comments
 (0)