Creating this question to answer myself, as I couldn't find it anywhere and I'm hoping it'll help someone else!
When writing PHP (e.g. Laravel) I often have an arrow function that I want to convert back to a regular function for debugging purposes or to add complexity to the return statement or closure process.
For example:
// Convert this:
collect($someArray)->map(fn($item) => $item->value);
// To this:
collect($someArray)->map(function ($item) {
dd($item);
return $item->value;
});
Once I'm done debugging and figure out the correct code I want to leave in there, I'll often want to put it back the way it was, like:
// Convert this:
collect($someArray)->map(function ($item) {
// dd($item);
return $item->correct_value;
});
// To this:
collect($someArray)->map(fn($item) => $item->correct_value);
I looked all over but couldn't find an existing VSCode snippet to accomplish this.
I've created a public gist with the snippets here but for convenience, here they are inline. Just select the function you want to convert use cmd+shift+p
to open the command palette and select "Snippets: Insert Snippet" and then search for "converToArrow
" or "convertFromArrow
".
// Place this snippet in php.json to allow it only in PHP files
{
// Other Snippets Here
"Convert PHP function to fat arrow function": {
"prefix": "convertToArrow",
"body": [
"${TM_SELECTED_TEXT/function\\s*\\(([^)]*)\\)(?:\\s*use\\s*\\([^)]*\\))?\\s*\\{\\s*(?:return\\s+)?([^;]+);\\s*\\}/fn($1) => $2/}"
},
"Convert fat arrow function to standard PHP function": {
"prefix": "convertFromArrow",
"body": [
"${TM_SELECTED_TEXT/fn\\s*\\(([^)]*)\\)\\s*=>\\s*([^;]+)/function ($1) { return $2; }/}"
],
"description": "Convert a fat arrow function to a standard PHP function"
}
}
Happy VSCoding + PHPing! 🥳