I have finally been able to set up PHPCBF (automatic lint fixing) with PHP Coding Standards for the Mac.
It has been a long struggle of technical difficulties over different apps.
How to set up automatic PHPCBF
- Open VS Code
- Open the Command Palette CMD+Shift+P and search for Tasks: Open User Tasks. Hit Enter.
- Paste the following script and save the tasks.json file.
{
/**
* This task checks for the existence of './wordpress/wp-content/vendor/bin/phpcbf'
* if it exists it assigns the path to 'phpcbf_path' variable
* otherwise it will use the global 'phpcbf' by running 'which phpcbf'
* Then it will check for the existence of './wordpress/wp-content/.phpcs.xml.dist'
* if it exists it assigns the path to 'standard' variable
* otherwise it will use 'WordPress-VIP-Go' standard.
* Finally it will run '$phpcbf_path --standard=$standard -l ${file}'
*/
"version": "2.0.0",
"tasks": [
{
"label": "Run WordPress Coding Standards",
"type": "shell",
"command": "[ -f './wordpress/wp-content/vendor/bin/phpcbf' ] && phpcbf_path='./wordpress/wp-content/vendor/bin/phpcbf' || phpcbf_path=$(which phpcbf); standard='WordPress-Docs'; $phpcbf_path --standard=$standard -l ${file}; [ -f './wordpress/wp-content/vendor/bin/phpcbf' ] && phpcbf_path='./wordpress/wp-content/vendor/bin/phpcbf' || phpcbf_path=$(which phpcbf); standard='WordPress-Extra'; $phpcbf_path --standard=$standard -l ${file}; [ -f './wordpress/wp-content/vendor/bin/phpcbf' ] && phpcbf_path='./wordpress/wp-content/vendor/bin/phpcbf' || phpcbf_path=$(which phpcbf); [ -f './wordpress/wp-content/.phpcs.xml.dist' ] && standard='./wordpress/wp-content/.phpcs.xml.dist' || standard='WordPress-VIP-Go'; $phpcbf_path --standard=$standard -l ${file};",
// This task will only apply to '.php', '.js' files
"fileMatches": [
"**/*.php",
"**/*.js",
],
// This task will run on file save
"runOn": "onSave",
"problemMatcher": [],
"presentation": {
"reveal": "silent",
"close": true
}
}
]
}
- Install this VS Code extension: Trigger Task on Save
- Open your VSCode settings.json file
- Add the following to your configuration:
"editor.formatOnSave": true,
"triggerTaskOnSave.tasks": {
"Run WordPress Coding Standards": [
"**/*.php",
"**/*.js",
],
},
- Save the file changes.
Now, when you automatically save any PHP or JavaScript file, it will format it to the phpcs file in your workspace. But if that does not exist, then it will fallback to your machine’s phpcs.
The following PHP Coding Standards have been set for the file:
- WordPress-Docs
- WordPress-Extra
- WordPress-VIP-Go
You can modify the tasks.json file to use a different set of commands or standards.
Let me know your thoughts if you have any questions or feedback on this setup