6

I'm trying to create a custom ruleset for a particular frameworks "guidelines". However, I want to be able to limit sniffs to only be relevant to a .php or .phtml filetype.

Is this possible within to have Sniffs to only use or ignore a defined filetype, or would I need to do this check within the sniffs process() method?

Adam Paterson
  • 412
  • 2
  • 11
  • In the configuration file, only process file extensions with the standards that you want to use. Will this accomplish what you want? Create your ruleset then run it against the .php or .phtml files from the command line. – Steven Scott May 21 '14 at 23:04

1 Answers1

5

You can specify exclude patterns using regular expressions inside a ruleset. By using a negative lookahead (or behind if you prefer) you can limit a specific sniff or error message to files that match the pattern.

This examples only runs the DoubleQuoteUsage sniff on .phtml files only:

<rule ref="Squiz.Strings.DoubleQuoteUsage">
  <exclude-pattern>*\.(?!phtml$)</exclude-pattern>
</rule>

But the current PHPCS releases use | as the delimiter for regular expressions, and escaping that character doesn't seem to work in PHP. I've just committed a change for this in the phpcs-fixer branch (the 2.x line of releases), allowing you to do this:

<rule ref="Squiz.Strings.DoubleQuoteUsage">
  <exclude-pattern>*\.(?!(php$|phtml$))</exclude-pattern>
</rule>

If you want to give that a go, you can clone the git repo, checkout the phpcs-fixer branch and run the code directly. Or you can require 2.0.*@dev via composer.

If not, you will need to do the filename check yourself in your sniff's process() method.

Greg Sherwood
  • 6,992
  • 2
  • 29
  • 24
  • Thanks for the reply Greg, that's brilliant. – Adam Paterson May 22 '14 at 06:32
  • The last line is the most precious one "**If not, you will need to do the filename check yourself in your sniff's process() method.**" – Alex Skrypnyk Jan 07 '16 at 03:04
  • Note that this will be natively possible in ruleset.xml files once version 3 is released (no release date, still awaiting an alpha release). The feature request is here: https://github.com/squizlabs/PHP_CodeSniffer/issues/656 – Greg Sherwood Jan 07 '16 at 06:41