Setup PhpStorm's to reformat code based on phpcs (codesniffer-rules from Squizlabs)

442 views Asked by At

I've taken over a code base, where most of the code is following the codesniffer settings from squizlabs/PHP_CodeSniffer.

How do I setup PhpStorm to automatically reformat the code upon saving files; so I always follow those standards. Ideally I would only reformat files that I save (and not unchanged files).

I'm imagining that I'm looking for a 'Import code style from phpcs.xml.dist' or something like that. But I'm not sure.

I'm trying to avoid having going to through all the code styles line for line, figuring out if it should be if ( $blah ) { or if($blah){, and adjusting the values in Settings one setting at the time.

And bonus points, if one can point out how to do this is VSCode, while I'm at it (to help my colleagues).


Attempt 1: Read online ressources

Attempt 2: Read around 'Settings'

I went to 'Settings' >> 'Editor' >> 'Code Style' (and also >> 'PHP'). I found the 'Set from'-button, so I could set it to follow Symfony2's code style. But I'm not sure if that follows squidlabs conventions.

I also read around, to see if I could find a 'Generate code styles from code'.

Attempt 3: Generate code style from code

I know that it's a tall order, but I would have been cool, if I could have pointed PhpStorm to a couple of correctly formatted files - and then get PhpStorm to automatically generate the code style from those files. I couldn't find this.

I tried this by trying to copy some of the well-formatted code from the project into the editor in the settings-box, to see if a 'Adjust values based on example code'. But I couldn't find this.

1

There are 1 answers

0
Zeth On

I found the answer by carefully reading this post here: PHP_CodeSniffer.
There are several steps to it - and it's highly customizable:

  • Only 'flag' editted lines
  • Only 'flag' editted files
  • Which standards to use
  • Should it show it as a warning or an error.

Etc...

That combined with: The 'reformat on save' I found in 'Settings' >> 'Actions on save'.