Skip to content

Instantly share code, notes, and snippets.

@marcocesarato
Last active October 31, 2019 11:49
Show Gist options
  • Save marcocesarato/ac883da221f15b8f1e7700a65c307264 to your computer and use it in GitHub Desktop.
Save marcocesarato/ac883da221f15b8f1e7700a65c307264 to your computer and use it in GitHub Desktop.
Convert php file variables. methods and variables from snake case to camel case
#!/usr/bin/env php
<?php
$path = $argv[1];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($iterator as $file) {
if (substr($file, -4) !== '.php') {
continue;
}
echo "Converted: " . $file . PHP_EOL;
$out = convert(file_get_contents($file));
file_put_contents($file, $out);
}
/**
* Convert string Snake case to Camel case
* @param $val
* @return string
*/
function snakeToCamel($val)
{
if (in_array($val, array(
'_SERVER',
'_POST',
'_GET',
'_REQUEST',
'_ENV',
'_COOKIE',
'_SESSION',
'_FILES',
'GLOBALS',
'argc',
'argv',
'php_error_msg',
'http_response_header',
))) {
return $val;
}
$starts = array(
"HTTP_",
);
foreach ($starts as $start) {
if (strpos($val, $start) === 0) {
return $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;
}
/**
* Convert Snake case to Camel case
* @param $str
* @return string|string[]|null
*/
function convert($str)
{
$name = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$snakeRegexps = array(
"#->($name)#i",
'#\$(' . $name . ')#i',
"#function ($name)#i",
);
foreach ($snakeRegexps as $regexp) {
$str = preg_replace_callback($regexp, function ($matches) {
$camel = snakeToCamel($matches[1]);
return str_replace($matches[1], $camel, $matches[0]);
}, $str);
}
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment