Skip to content

Instantly share code, notes, and snippets.

@iluuu1994
Last active April 15, 2024 10:45
Show Gist options
  • Save iluuu1994/72e2154fc4150f2258316b0255b698f2 to your computer and use it in GitHub Desktop.
Save iluuu1994/72e2154fc4150f2258316b0255b698f2 to your computer and use it in GitHub Desktop.
${} string interpolation migration script

Copy the migrator.php file to the root of your project and run the following command:

for file in **/*.php; do php ./migrator.php "$file"; done

BACK UP YOUR REPOSITORY BEFORE RUNNING THIS SCRIPT!

<?php
if ($argc !== 2) {
fwrite(STDERR, "Missing input script\n");
die(1);
}
$fileName = $argv[1];
$fileContent = file_get_contents($fileName);
$phpBinary = PHP_BINARY;
exec("$phpBinary -l $fileName", $output, $status);
if ($status !== 0) {
die($status);
}
$tokens = \PhpToken::tokenize($fileContent);
$nestingStack = [];
foreach ($tokens as $i => $token) {
$nextToken = $tokens[$i + 1] ?? null;
if ($token->id === T_DOLLAR_OPEN_CURLY_BRACES) {
if ($nextToken?->id === T_STRING_VARNAME) {
// Option 3
$tokens[$i] = new \PhpToken(T_CURLY_OPEN, '{');
$tokens[$i + 1] = new \PhpToken(T_VARIABLE, "\$$nextToken->text");
} else {
// Option 4
$token->text = '{${';
$nestingStack[] = 0;
}
}
if ($token->text === '{' && !empty($nestingStack)) {
++$nestingStack[array_key_last($nestingStack)];
}
if ($token->text === '}' && !empty($nestingStack)) {
$nesting = $nestingStack[array_key_last($nestingStack)];
if ($nesting === 0) {
$token->text = '}}';
array_pop($nestingStack);
} else {
--$nestingStack[array_key_last($nestingStack)];
}
}
}
$result = join('', array_map(fn ($t) => $t->text, $tokens));
file_put_contents($fileName, $result);
<?php
// Simple
"$foo";
"{$foo}";
"${foo}";
// DIM
"$foo[bar]";
"{$foo['bar']}";
"${foo['bar']}";
// Property
"$foo->bar";
"{$foo->bar}";
// Method
"{$foo->bar()}";
// Closure
"{$foo()}";
// Chain
"{$foo['bar']->baz()()}";
// Variable variables
"${$bar}";
"${(foo)}";
"${foo->bar}";
// Nested
"${foo["${bar}"]}";
"${foo["${bar['baz']}"]}";
"${foo->{$baz}}";
"${foo->{${'a'}}}";
"${foo->{"${'a'}"}}";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment