1

I need a code sniffer for converting all the variables in all of my PHP file from snake_case to camelCase.

I don't need the functions which do it in php on a string, I want to convert the variables in my PHP files to camelCase.

I appreciate you in advanced.

Malus Jan
  • 1,860
  • 2
  • 22
  • 26

1 Answers1

1

I found a way to do it. I integrate the code for cakePHP (There is the file with ctp extension and the variable passed to view by set function).

Save the below code as tocamelcase.php

php tocamelcase.php the/path/of/your/app

file content:

<?php
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) {
    global $j;
    $name = '/(\$[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(->[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(::[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\sfunction\s+[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\$this->set\(\'[a-zA-Z0-9]+_[a-zA-Z0-9_]+\'\,)|'.
            '(\$this->set\(\"[a-zA-Z0-9]+_[a-zA-Z0-9_]+\"\,)'.
            '/i';
    $str = preg_replace_callback($name, function($matches){
        return snakeToCamel($matches[0]);   
    },$str);
    return $str;
}

$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$i=1;
foreach($Iterator as $file){
    if(substr($file,-4) !== '.php' && substr($file,-4) !== '.ctp')
        continue;
    echo($i.": ".$file."\n");
    $i++;
    $out = convert(file_get_contents($file));
    file_put_contents($file, $out);
}
Malus Jan
  • 1,860
  • 2
  • 22
  • 26