Browse Source

DX: simplify Utils::camelCaseToUnderscore

Kuba Werłos 5 years ago
parent
commit
b974c57bf4
2 changed files with 30 additions and 8 deletions
  1. 2 8
      src/Utils.php
  2. 28 0
      tests/UtilsTest.php

+ 2 - 8
src/Utils.php

@@ -45,7 +45,7 @@ final class Utils
     }
 
     /**
-     * Converts a camel cased string to an snake cased string.
+     * Converts a camel cased string to a snake cased string.
      *
      * @param string $string
      *
@@ -53,13 +53,7 @@ final class Utils
      */
     public static function camelCaseToUnderscore($string)
     {
-        return Preg::replaceCallback(
-            '/(^|[a-z0-9])([A-Z])/',
-            static function (array $matches) {
-                return strtolower('' !== $matches[1] ? $matches[1].'_'.$matches[2] : $matches[2]);
-            },
-            $string
-        );
+        return strtolower(Preg::replace('/(?<!^)((?=[A-Z][^A-Z])|(?<![A-Z])(?=[A-Z]))/', '_', $string));
     }
 
     /**

+ 28 - 0
tests/UtilsTest.php

@@ -63,6 +63,34 @@ final class UtilsTest extends TestCase
             [
                 'utf8_encoder_fixer',
             ],
+            [
+                'a',
+                'A',
+            ],
+            [
+                'aa',
+                'AA',
+            ],
+            [
+                'foo',
+                'FOO',
+            ],
+            [
+                'foo_bar_baz',
+                'FooBarBAZ',
+            ],
+            [
+                'foo_bar_baz',
+                'FooBARBaz',
+            ],
+            [
+                'foo_bar_baz',
+                'FOOBarBaz',
+            ],
+            [
+                'mr_t',
+                'MrT',
+            ],
         ];
     }