Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code PHP auto-formatting / beautify with Stroustrup style braces (K&R variant) and spaces in parentheses?

Help me Stack Overflow, you are my only hope.

I’d like to apply auto-formatting in VS Code to PHP files with the following rules:

  • Stroustrup style braces (K&R variant)
  • space before conditional
  • space after function
  • spaces in parentheses

Example in the screenshot.Stroustrup braces and spaces

I don't want to apply PSR-1 or PSR-2 or PSR-12 or CakePHP or WordPress standards.

I've struggled with:

  • VS code internal PHP formatter
  • phpfmt (which has been last updated in 2018 and archived on GitHub)
  • PHP Intelephense (which has little to do with formatting, as far as I can tell)

phpfmt is the closest, but super-buggy.

VS Code settings wise, I roll with:

  • "files.autoSave": "onFocusChange",
  • "editor.formatOnSave": true,

So I'd like to instantly beautify my PHP files, please.

Thank you for any ideas!

like image 876
Anatoly IVANOV Avatar asked Nov 16 '22 10:11

Anatoly IVANOV


1 Answers

I finally sat down and figured out how to achieve this. This is from an Ubuntu perspective, but I should think that it could be made to work on the other platforms as well.

I tested a bunch of linter/fixer extensions with no real progress until I ended up at this.

It was a bit involved to install a version of phpcs/phpcbf together with a ruleset that the extension could use, so I bundled it all up in a docker container (but everything can be done locally as well with composer of course).

I haven't been able to find rules that can enforce the two whitespace rules in OP (space before conditional and space after function), but there are a lot of customization possible, including writing your own sniffs (and I didn't look super hard to be honest). But the default ruleset/standard in the project linked above allows extra whitespace, so that is half the battle I feel.

For the other rules the following are the explicit parts needed, but please do check out there resources: 1 and 2 and enable "phpsab.snifferShowSources": true and "phpsab.debug": true when creating a custom ruleset.

  • Stroustrup style braces (K&R variant)
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie">
</rule>
<rule ref="Drupal.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis">
</rule>
  • spaces in parentheses
<rule ref="PSR2.ControlStructures.ControlStructureSpacing">
  <properties>
    <property name="requiredSpacesAfterOpen" value="1" />
    <property name="requiredSpacesBeforeClose" value="1" />
  </properties>
</rule>
like image 122
glaux Avatar answered Feb 01 '23 23:02

glaux