When I work on a project I like to be sure the code is written consistently, with no files left carrying an extra space here or a missing line break there. On a team it matters even more: if everyone writes code the same way, nobody wastes time reading differences that mean nothing.
That is what I use Laravel Pint for. It is a code formatter that rewrites your files, fixing the indentation you got wrong, adding the line break you missed, sorting imports, and so on.
Pint ships with Laravel by default, so to use it you only need to open a terminal and run:
./vendor/bin/pint
The catch is that you have to remember to run it every time you finish working, or before pushing your changes. Digging around, I found a way to have it run on its own, against the file you are actually editing.
Install the RunOnSave extension
This extension is what runs the command for us. You can install it from the VS Code extensions tab or from its Marketplace page.
Then edit your VS Code settings: press Ctrl + Shift + P on Windows or Cmd + Shift + P on Mac, and pick the option to edit your user settings as JSON.
Add the following:
"emeraldwalk.runonsave": {
"commands": [
{
"match": "\\.php$",
"cmd": "${workspaceFolder}/vendor/bin/pint --dirty ${file}"
}
]
}
The command only runs on files with a .php extension, and thanks to --dirty only on the ones with uncommitted changes, so you are not burning resources reformatting the whole project on every save.
That is all the setup there is: save a file and Pint leaves it formatted. You notice it most in code review, where diffs start containing only real changes instead of whitespace noise.