Skip to content

Instantly share code, notes, and snippets.

@edgrosvenor
Created June 14, 2021 18:11
Show Gist options
  • Save edgrosvenor/f382a9315d5e0314ca9536a0e2812fa6 to your computer and use it in GitHub Desktop.
Save edgrosvenor/f382a9315d5e0314ca9536a0e2812fa6 to your computer and use it in GitHub Desktop.
Hacky script I ran in Tinkerwell to replace direct array access with data_get() in blade templates. Mostly works.
foreach (\File::files(resource_path('views')) as $file) {
if (str_contains($file->getPathname(), 'blade.php')) {
$contents = \File::get($file);
$contents = str_replace('{{', '{{ ', $contents);
$contents = str_replace('}}', ' }}', $contents);
$contents = str_replace('])', '] )', $contents);
preg_match_all('/\$[a-zA-Z](.*?)[ \}]/', $contents, $match);
$replace = [];
foreach ($match[0] as $item) {
if (preg_match('/\[/', $item) && substr_count($item, '$') === 1) {
$original = $item;
$item = str_replace("']['", '.', $item);
$item = str_replace(["'", ")", "]"], '', $item);
list ($var, $key) = explode('[', $item);
$replace[trim($original)] = "data_get({$var}, '".
str_replace(["'", "]", " "], '', $key)."')";
}
}
foreach ($replace as $k => $v) {
$contents = str_replace($k, $v, $contents);
}
\File::put($file, $contents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment