Search code examples
phpcodesniffer

Does PHP CodeSniffer support rule-specific configuration like Rubcop?


With Rubocop I can override rules in a .rubocop.yml file like this:

AllCops:
  RunRailsCops: true

# Commonly used screens these days easily fit more than 80 characters.
Metrics/LineLength:
  Max: 120

# Too short methods lead to extraction of single-use methods, which can make
# the code easier to read (by naming things), but can also clutter the class
Metrics/MethodLength: 
  Max: 20

I gotta believe CodeSniffer supports something like this, but looking at their wiki page, I can't find anything about rules:

And the default config file doesn't seem to support it:


Solution

  • Yes, PHP_CodeSniffer lets you define your own coding standard using a ruleset.xml file. An annotated one is available here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset

    You can also name your file phpcs.xml to have PHPCS pick it up automatically and stop you needing to use --standard=/path/to/ruleset.xml for each run. Docs for that are here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file

    Many sniffs have properties that allow you to change their behaviour. You can see the list here: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties

    A good example is probably the line length one: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties#genericfileslinelength

    You might also want to check out the phpcs.xml file that PHPCS uses as a complete example: https://github.com/squizlabs/PHP_CodeSniffer/blob/master/phpcs.xml.dist

    How to fully construct the file is probably beyond the scope of this question, but you should be able to search around for constructing PHPCS rulesets to get more info. If not, ask more questions here :)