Developer Blog

  • Blog
  • /
  • Convert snake case methods, properties and variables to camel case
By Dracony on 6 March 2014

Today I started refactoring the code I have for PHPixie 3 to comply with PSR standards. Thankfully there is already a great tool for this, the PHP CS Fixer, that will replace your tabs with spaces, put brackets appropriately etc. But there is one feature it doesn’t have, the option to convert snake_case() to camelCase(). Obviously there is a good reason for that, a formatter shouldn’t be meddling with the actual logic.

Never the less I still needed to convert my snake case entities, so I wrote a quick script that will do just that, here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function snakeToCamel($val) {  
    preg_match('#^_*#', $val, $underscores);
    $underscores = current($underscores);
    $camel = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));  
    $camel = strtolower(substr($camel, 0, 1)).substr($camel, 1);

    return $underscores.$camel;  
}  

function convert($str) {
    $name = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
    $snake_regexps = array(
        "#->($name)#i",
        '#\$('.$name.')#i',
        "#function ($name)#i",
    );
    foreach($snake_regexps as $regexp)
        $str = preg_replace_callback($regexp, function($matches) {
            //print_r($matches);
            $camel = snakeToCamel($matches[1]);
            return str_replace($matches[1],$camel,$matches[0]);
        },$str);
    return $str;

}

$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($Iterator as $file){
    if(substr($file,-4) !== '.php')
        continue;
    echo($file);
    $out = convert(file_get_contents($file));
    file_put_contents($file, $out);
}

To use it, just pass the path to your project as a parameter:

1
php convertCase.php /projects/project1/

Ideally you would run it on both your classes and tests, then run PHP CS Fixer, and then run your tests to make sure nothing broke.

Hope it helps someone port their project to PSR faster

comments powered by Disqus