Categories
General

Include rules excluded by other standards for PHPCS

Developers should use code style rules, and PHPCS is a great tool for that. So how can you include rules that were excluded in inherited standards that extend Squiz, PEAR and PSR*?

I feel that I’m lucky that I work for a company and on projects that allow to control code style. In my opinion, having a unified code style might look like a bureaucracy but it greatly simplifies the reading of the code. And remember, we read the code 80% of the time.

So, as we as a team are working on WordPress plugins (WPForms and WP Mail SMTP, with 2+ with 1+ millions of active installs respectively) it’s logical that we inherit WordPress Coding Standards (WPCS).

WordPress Coding Standards structure

WPCS consists of one main WordPress ruleset, which implements own sniffs and imports 3 other rulesets: WordPress-Core, WordPress-Docs and WordPress-Extra. Those 3 are modifying certain rules bundled with phpcs tool (Squiz, Pear and PSR* family of rules).

Those WordPress-specific rules are tailored to WordPress core in lots of places, and that creates an issue. Some great rules are excluded in WordPress-Docs for example, and they are rather helpful: require a full stop . at the end of the phpdoc @param description, or the need to start that description with a capital letter. WordPress has in its source files some specific array descriptions, that violate those rules, and thus WP core contributors decided to exclude them. That’s the WP core use case, and it is helpful when you write the code for the WordPress core.

But here at WPForms, we have a bit different code style rules, and I decided to find a way how to change that behavior without removing the dependency of the WordPress-Docs ruleset. I needed to include some of those excluded rules, like Squiz.Commenting.FunctionComment.ParamCommentNotCapital.

Here’s how the inheritance looks:

WPForms > WordPress > WordPress-Docs > Squiz.*

Include PHPCS rules

It took me a while to understand, that when you exclude certain rules, you are actually setting its severity to 0. So checks are still run, they are just not displayed. You can read a bit more about severity here in the Annotated Ruleset wiki article.

After looking at the phpcs parser of those severity XML properties, I got the idea of how to include rules, that were excluded by WordPress Coding Standards (or any other standards):

<rule ref="Squiz.Commenting.FunctionComment.ParamCommentNotCapital">
    <severity>5</severity>
</rule>

You just raise the severity back to its default value (5) in your own ruleset.xml file. After that when you run
phpcs --standard=YourStandard .
the tool will start notifying you about code style violations, that were excluded in your parent ruleset, but re-enabled in your own ruleset.

Leave a Reply

Your email address will not be published. Required fields are marked *