Skip to content

Customizable sniff properties

Juliette edited this page Jun 29, 2018 · 56 revisions

Customizable sniff properties.

The behaviour of some sniffs can be changed by setting certain sniff properties in your ruleset. On this page you will find the properties used in the WPCS sniff library which are available for customization.

For more information about changing sniff behaviour by customizing your ruleset and how on how to pass different types of values via the ruleset, please read the PHPCS Annotated ruleset wiki page.

As of PHPCS 3.3.0, a new format is supported for passing array properties to PHPCS from a custom ruleset. This new format is fully supported by WPCS. For details, please see the PHPCS 3.3.0 release notes.

WPCS also uses a number of upstream PHPCS native sniffs. For a list of customizable sniff properties for these upstream sniffs, please see the PHPCS Customisable Sniff Properties wiki page.

Table of contents

Properties strongly recommended to be set

Internationalization: setting your text domain

WordPress Sniff Property name Property type Available since:
WP.I18n text_domain array 0.10.0

The WordPress.WP.I18n sniff can optionally verify if all I18n function calls contain a $text_domain argument and whether the value of the $text_domain argument is valid. To execute this check one or more text-domains which should be considered valid must be provided in the $text_domain property in your custom ruleset or via the command-line.

If this property is not set, these checks will be skipped.

<rule ref="WordPress.WP.I18n">
	<properties>
		<property name="text_domain" type="array" value="my-text-domain,tgmpa" />
	</properties>
</rule>

Setting text_domain from the command line (WPCS 0.11.0+)

This property can also be set from the command line.

To set the property from the command line, use --runtime-set text_domain and pass a comma delimited list without spaces.

phpcs -p . --standard=WordPress --runtime-set text_domain my-slug,default

Naming Conventions: prefix everything in the global namespace

WordPress Sniff Property name Property type Available since:
NamingConventions.PrefixAllGlobals prefixes array 0.12.0

Prefixing all functions, classes, interfaces, traits, variables, constants and hook names which are declared/defined in the global namespace is considered best practice to prevent naming collisions what with there being so many plugins and themes out there in the wider WordPress arena.

The WordPress.NamingConventions.PrefixAllGlobals sniff can verify that prefixes are used in all the appropriate places.

To execute this check one or more prefixes which should be considered valid must be provided via the $prefixes property in your custom ruleset or via the command-line.

If this property is not set, this sniff will not run.

<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
	<properties>
		<property name="prefixes" type="array" value="my_prefix,tgmpa" />
	</properties>
</rule>

Setting prefixes from the command line

This property can also be set from the command line.

To set the property from the command line, use --runtime-set prefixes and pass a comma delimited list without spaces.

phpcs -p . --standard=WordPress --runtime-set prefixes my_prefix,tgmpa

Minimum WP version to check for usage of deprecated functions, classes and function parameters

WordPress Sniff Property name Property type Available since:
WP.AlternativeFunctions minimum_supported_version string 1.0.0
WP.DeprecatedFunctions minimum_supported_version string 0.11.0
WP.DeprecatedClasses minimum_supported_version string 0.12.0
WP.DeprecatedParameters minimum_supported_version string 0.12.0

The WordPress.WP.DeprecatedFunctions, WordPress.WP.DeprecatedClasses and WordPress.WP.DeprecatedParameters sniffs check for usage of deprecated WordPress functions and function parameters.

For deprecations before the minimum_supported_version it will throw an error. For deprecations between the minimum_supported_version and the current release (inclusive), it will throw a warning.

For example: the function add_object_page() was deprecated in WP 4.5. If usage of this function is detected, the sniff will throw an error if the minimum_supported_version is 4.6 or higher. It will throw a warning if the minimum_supported_version is 4.5 or lower.

Along the same lines, the WordPress.WP.AlternativeFunctions sniff will recommend WP alternatives for native PHP functions and will take the minimum_supported_version into account to make sure that the WP alternative is available in that version.

By default, the value of the minimum_supported_version property is set to three versions before the currently released WP version (disregarding patch releases).

For example: at the time of writing, the latest released WP version is 4.8.1, so the default value of the minimum_supported_version property is currently 4.5.

<rule ref="WordPress.WP.DeprecatedFunctions">
	<properties>
		<property name="minimum_supported_version" value="4.0" />
	</properties>
</rule>

Setting minimum supported WP version for all sniffs in one go (WPCS 0.14.0+)

As this property becomes available to more and more sniffs and - in nearly all cases -, the same minimum supported WP version should be used for all sniffs using this property, the ability to set the minimum version via a configuration variable has been added to the sniff.

Important: The value passed to this configuration variable will take priority over the property value set for individual sniffs.

<config name="minimum_supported_wp_version" value="4.5"/>

Setting minimum supported WP version from the command line (WPCS 0.14.0+)

Setting the property in one go for all sniffs via a configuration variable can also be done from the command line.

To set the property from the command line, use --runtime-set minimum_supported_wp_version and pass the version number.

phpcs . --standard=WordPress --runtime-set minimum_supported_wp_version 4.5

Themes: allow filename exceptions

WordPress Sniff Property name Property type Default: Available since:
Files.FileName is_theme bool false 0.11.0

The WordPress PHP Coding Standards Handbook states:

Files should be named descriptively using lowercase letters. Hyphens should separate words.

While this is true for most files, there are some typical exceptions to this rule in the theme hierarchy, such as taxonomy-{custom_taxonomy}.php or archive-{post_type}.php.

By default, those exceptions will not be taken into account and will trigger an error.

If the project you're working on is a theme, you can set the is_theme property to true to allow theme hierarchy specific file name exceptions.

<rule ref="WordPress.Files.FileName">
	<properties>
		<property name="is_theme" value="true" />
	</properties>
</rule>

Custom Unit test classes

WordPress Sniff Property name Property type Available since:
Files.Filename custom_test_class_whitelist array 0.12.0
NamingConventions.PrefixAllGlobals custom_test_class_whitelist array 0.12.0
WP.GlobalVariablesOverride custom_test_class_whitelist array 0.11.0

Certain rules can be regarded as over-zealous when applied to unit tests as these files are not part of the code which will be executed via WordPress.

To that end, any classes which extend either PHPUnit_Framework_TestCase, PHPUnit\Framework\TestCase or WP_UnitTestCase are whitelisted for the purpose of those specific checks.

To be specific, at this moment exceptions are made for:

  • Global Variable overrides in test classes: Sometimes WordPress global variables will need to be overloaded in unit test situations. The sniff allows for this.
  • The class-based file name rule may conflict with your PHPUnit configuration, therefore test classes are exempt from this rule.
  • No need to prefix your test classes/functions etc defined in the global namespace. As these are not executed by WordPress, there is no risk of naming collisions.

In your WordPress application you may use a custom unit test base class.

The custom_test_class_whitelist property allows you to whitelist the names of additional test classes.

It is recommended that you use the same lists for all sniffs which support this property.

<rule ref="WordPress.WP.GlobalVariablesOverride">
	<properties>
		<property name="custom_test_class_whitelist" type="array" value="My_Plugin_TestCase,My_Other_Plugin_TestCase" />
	</properties>
</rule>

Optional properties

Excluding a group of checks

WordPress Sniff Property name Property type Available since: Groups:
DB.RestrictedClasses exclude string 0.10.0 mysql
DB.RestrictedFunctions exclude string 0.10.0 mysql
DB.SlowDBQuery exclude string 0.3.0 slow_db_query
PHP.DevelopmentFunctions exclude string 0.11.0 error_log, prevent_path_disclosure
PHP.DiscouragedPHPFunctions exclude string 0.11.0 serialize, urlencode, runtime_configuration, system_calls, obfuscation
PHP.DontExtract exclude string 0.10.0 extract
PHP.POSIXFunctions exclude string 0.10.0 ereg, ereg_replace, split
PHP.RestrictedPHPFunctions exclude string 0.14.0 create_function
Security.SafeRedirect exclude string 1.0.0 wp_redirect
VIP.FileSystemWritesDisallow exclude string 0.11.0 file_ops, directory, chmod
VIP.OrderByRand exclude string 0.9.0 orderby
VIP.PostsPerPage exclude string 0.3.0 posts_per_page
VIP.RestrictedFunctions exclude string 0.3.0 switch_to_blog, file_get_contents, get_page_by_path, get_page_by_title, url_to_postid, attachment_url_to_postid, wp_remote_get, custom_role, cookies, user_meta, get_posts, term_exists, count_user_posts, wp_old_slug_redirect, get_adjacent_post, get_intermediate_image_sizes, wp_is_mobile, wpcom_vip_get_term_link (since 0.14.0), wpcom_vip_get_term_by (since 0.14.0), wpcom_vip_get_category_by_slug (since 0.14.0), wp_get_post_terms (since 0.12.0), get_term_link, get_term_by, get_category_by_slug (removed 0.14.0), wp_redirect (removed 1.0.0)
VIP.RestrictedVariables exclude string 0.3.0 user_meta, cache_constraints
VIP.SessionFunctionsUsage exclude string 0.11.0 session
WP.AlternativeFunctions exclude string 0.11.0 curl, parse_url, json_encode, file_get_contents, file_system_read
WP.DiscouragedFunctions exclude string 0.11.0 query_posts, wp_reset_query
WP.PostsPerPage exclude string 1.0.0 posts_per_page
WP.TimezoneChange exclude string 0.11.0 timezone_change
WP.DeprecatedFunctions exclude string 0.11.0 deprecated_functions The deprecated function checks can be disabled for each function individually by their sniff error code.
WP.DeprecatedClasses exclude string 0.12.0 deprecated_classes The deprecated classes checks can be disabled for each class individually by their sniff error code.
WP.DeprecatedParameters exclude string 0.12.0 wp_deprecated_parameters The deprecated function checks can be disabled for each function individually by their sniff error code.

There are a number of sniffs which use groups of functions, classes, variable names or array keys as the basis for their checks. The grouping is normally based on functionality.

For example: the error_log group in the WordPress.PHP.DevelopmentFunctions sniff, checks for a number of error handling related functions, such as error_log(), var_dump(), print_r(), debug_backtrace() and more.

One sniff can handle the checks for an unlimited number of groups. The groups currently handled by each sniff are listed in the table above.

The exclude property allows you to disable the checks for one or more groups, without disabling the sniff completely.

To find out which group a particular function belongs to, have a look at the source code of the sniff or run PHPCS with the -s option to see the error codes. A code will look like Standard.Category.Sniff.ErrorCode. The group name will be the first part of the errorCode.

The groups to be excluded should be provided as a comma-delimited string.

<!-- Exclude one group. -->
<rule ref="WordPress.VIP.OrderByRand">
	<properties>
		<property name="exclude" value="orderby" />
	</properties>
</rule>

<!-- Exclude several groups. -->
<rule ref="WordPress.VIP.RestrictedFunctions">
	<properties>
		<property name="exclude" value="switch_to_blog,wp_remote_get,cookies" />
	</properties>
</rule>

If you don't want to disable a complete group, but only want to disable the message for one particular check from a group, you can use the <exclude name="Standard.Category.Sniff.ErrorCode"> syntax in your ruleset.

Note: If a sniff using this property only supplies one group, excluding that group will effectively disable the sniff. Using the exclude property rather than disabling the complete sniff, however, future proofs your ruleset for when more groups would be added to the sniff in the future.

Existing exclusions

The WordPress rulesets contain a limited set of existing exclusions:

Ruleset Sniff Excluded groups
WordPress-VIP WordPress.PHP.DiscouragedPHPFunctions obfuscation
WordPress WordPress.PHP.DiscouragedPHPFunctions obfuscation

If you would set the exclude property for the WordPress.PHP.DiscouragedPHPFunctions sniff in your own ruleset and use either the WordPress-VIP or WordPress ruleset, it will overrule the existing exclusions.

To maintain the WPCS native exclusions, you will need to add these to the value you set in your ruleset.

<rule ref="WordPress" />
<rule ref="WordPress.PHP.DiscouragedFunctions">
	<properties>
		<property name="exclude" value="obfuscation" />
	</properties>
</rule>

Disregard class file name rules

WordPress Sniff Property name Property type Default: Available since:
Files.FileName strict_class_file_names bool true 0.11.0

The WordPress PHP Coding Standards Handbook states:

Class file names should be based on the class name with class- prepended and the underscores in the class name replaced with hyphens.

This rule applies to WP core, but you may want to deviate from it for personal projects.

This check is turned on by default. To turn it off, set the strict_class_file_names property to false.

<rule ref="WordPress.Files.FileName">
	<properties>
		<property name="strict_class_file_names" value="false" />
	</properties>
</rule>

Custom word delimiters in hook names

WordPress Sniff Property name Property type Available since:
NamingConventions.ValidHookName additionalWordDelimiters string 0.10.0

The WordPress PHP Coding Standards Handbook states:

Use lowercase letters in action and filter names. Separate words via underscores.

Words in hook names should only be separated by underscores _. However, historically, in WordPress Core dashes - were used as well. Similarly there are well-known WordPress plugins and themes which use a different word separator in hook names.

The WordPress.NamingConventions.ValidHookName sniff will - by default - only allow an underscore as a word separator. However, the additionalWordDelimiters property allows you to add one or more extra allowed word delimiters.

Each character passed to the property will be treated as an extra allowed word delimiter.

<!-- Add one extra word delimiter. -->
<rule ref="WordPress.NamingConventions.ValidHookName">
	<properties>
		<property name="additionalWordDelimiters" value="-"/>
	</properties>
</rule>

<!-- Add several extra word delimiters. -->
<rule ref="WordPress.NamingConventions.ValidHookName">
	<properties>
		<property name="additionalWordDelimiters" value="-/."/>
	</properties>
</rule>

Mixed case property name exceptions

WordPress Sniff Property name Property type Available since:
NamingConventions.ValidVariableName customPropertiesWhitelist (previously called customVariablesWhitelist) array 0.11.0 (0.10.0)

The WordPress PHP Coding Standards Handbook states:

Use lowercase letters in variable names.

Variable and class property names should be lowercase. The WordPress.NamingConventions.ValidVariableName sniff will take known exceptions, such as PHP reserved variables and WordPress core variables and properties which were inconsistently named, into account.

Still, if an application, for instance, uses external code modules and extends a PHP class from one of these modules which doesn't use snakecase property names, it may be unavoidable to use a certain mixed case class property.

This sniff property allows you to declare a whitelist of mixed case class property names used in your application. The mixed case property names on the whitelist will subsequently be disregarded by this sniff.

<rule ref="WordPress.NamingConventions.ValidVariableName">
	<properties>
		<property name="customPropertiesWhitelist" type="array" value="myMixedCasePropery,AnotherMixedCaseProperty" />
	</properties>
</rule>

CronInterval: minimum interval

WordPress Sniff Property name Property type Default: Available since:
WP.CronInterval min_interval int 900 0.14.0

The WordPress.WP.CronInterval sniff warns about cron schedules being added with a repeat frequency of less than 15 minutes (900 seconds).

The min_interval property allows for setting an arbitrary minimum interval value. The value has to be passed in seconds.

<rule ref="WordPress.WP.CronInterval">
	<properties>
		<property name="min_interval" value="1800"/>
	</properties>
</rule>

WP PostsPerPage: post limit

WordPress Sniff Property name Property type Default: Available since:
WP.PostsPerPage posts_per_page int 100 0.14.0

The WordPress.WP.PostsPerPage sniff warns about queries using a high pagination limit. By default "high" is interpreted as "more than 100 posts".

The posts_per_page property allows for setting an arbitrary limit.

<rule ref="WordPress.WP.PostsPerPage">
	<properties>
		<property name="posts_per_page" value="200"/>
	</properties>
</rule>

Custom database query caching functions

WordPress Sniff Property name Property type Available since:
DB.DirectDatabaseQuery customCacheGetFunctions array 0.6.0
DB.DirectDatabaseQuery customCacheSetFunctions array 0.6.0
DB.DirectDatabaseQuery customCacheDeleteFunctions array 0.6.0

The WordPress.DB.DirectDatabaseQuery sniff checks any queries made to the database use cachable WP functions to prevent unnecessarily querying the database multiple times for the same query.

Your application might have wrapper functions in place which handle the caching of database queries either via the WP native functions or via your own caching mechanism.

The above properties allow you to add the names of these functions to the list of functions which get/set/delete & cache database queries.

<rule ref="WordPress.DB.DirectDatabaseQuery">
	<properties>
		<property name="customCacheGetFunctions" type="array" value="prefix_get_from_db_and_cache,prefix_also_get_from_db_and_cache" />
		<property name="customCacheSetFunctions" type="array" value="prefix_get_from_db_and_cache" />
		<property name="customCacheDeleteFunctions" type="array" value="prefix_remove_from_db_cache" />
	</properties>
</rule>

Custom input sanitization functions

WordPress Sniff Property name Property type Available since:
Security.ValidatedSanitizedInput customSanitizingFunctions array 0.5.0
Security.ValidatedSanitizedInput customUnslashingSanitizingFunctions array 0.5.0
Security.NonceVerification customSanitizingFunctions array 0.11.0
Security.NonceVerification customUnslashingSanitizingFunctions array 0.11.0

The WordPress.Security.ValidatedSanitizedInput sniff checks that input variables ($_GET / $_POST) are unslashed and sanitized before use. The same checks are executed specifically for the nonce input variable in the WordPress.Security.NonceVerification sniff.

To do so, all safe PHP and WP core unslashing and sanitization functions are whitelisted.

Your application might have wrapper functions in place which handle the unslashing and sanitization of user input either via the WP native functions or via other means.

The above properties allow you to add the names of these functions to the whitelist of functions which unslash/sanitize user input.

It is recommended that you use the same function lists for both properties for all sniffs which support these properties.

<rule ref="WordPress.Security.ValidatedSanitizedInput">
	<properties>
		<property name="customSanitizingFunctions" type="array" value="prefix_sanitize_url,prefix_sanitize_postal_code" />
		<property name="customUnslashingSanitizingFunctions" type="array" value="prefix_sanitize_unslash_url" />
	</properties>
</rule>

<rule ref="WordPress.Security.NonceVerification">
	<properties>
		<property name="customSanitizingFunctions" type="array" value="prefix_sanitize_url,prefix_sanitize_postal_code" />
		<property name="customUnslashingSanitizingFunctions" type="array" value="prefix_sanitize_unslash_url" />
	</properties>
</rule>

Input validation scope

WordPress Sniff Property name Property type Default: Available since:
Security.ValidatedSanitizedInput check_validation_in_scope_only bool false 0.3.0

The WordPress.Security.ValidatedSanitizedInput sniff checks that input variables ($_GET / $_POST) are validated before use. "Validated" in this context means that it should be verified that the input variable exists via isset() or empty() before using it.

The check_validation_in_scope_only variable allows for tweaking of where the sniff looks for this validation.

// When `check_validation_in_scope_only` is `false`, this is considered valid:
if ( ! isset( $_GET['post_id'] ) ) {
	// Do stuff, like maybe return or exit (but could be anything)
}

foo( $_GET['post_id'] );

// When `check_validation_in_scope_only` is `true`, the above would be invalid.
// In that case, the variable will only be considered validated if used within
// the scope of the validating condition, like this:
if ( isset( $var ) ) {
	foo( $var );
}

By default, the property is set to false. You can change this in your ruleset to true if you want to limit the use of input variables to be within scoped validation conditions only.

<rule ref="WordPress.Security.ValidatedSanitizedInput">
	<properties>
		<property name="check_validation_in_scope_only" value="true" />
	</properties>
</rule>

XSS: Custom output escaping functions

WordPress Sniff Property name Property type Available since:
Security.EscapeOutput customEscapingFunctions (previously called customSanitizingFunctions) array 0.5.0 (0.3.0)
Security.EscapeOutput customAutoEscapedFunctions array 0.3.0

The WordPress.Security.EscapeOutput sniff checks that all output is escaped. To do so, all safe PHP and WP core functions which safely escape data are whitelisted.

Your application might have wrapper functions in place which handle the output escaping of data either via the WP native functions or via other means.

The above properties allow you to add the names of these functions to the whitelist of functions which either escape output (customEscapingFunctions) or the whitelist of functions which return pre-escaped data (customAutoEscapedFunctions).

<rule ref="WordPress.Security.EscapeOutput">
	<properties>
		<property name="customEscapingFunctions" type="array" value="prefix_escape_form_value,prefix_escape_form_id" />
		<property name="customAutoEscapedFunctions" type="array" value="prefix_get_escaped_value" />
	</properties>
</rule>

XSS: Custom printing functions

WordPress Sniff Property name Property type Available since:
Security.EscapeOutput customPrintingFunctions array 0.4.0

The WordPress.Security.EscapeOutput sniff checks that all output is escaped. To do so, the usage of all PHP and WP core functions and PHP language constructs which generate output - such as echo, print(), _e(), wp_die() - is checked.

Your application might have dedicated functions in place which generate output. If you want to enforce the WordPress.Security.EscapeOutput sniff for data passed to these functions, you will need to add them to the list of functions which will be checked.

To do so, pass the names of your custom printing functions to the sniff via your ruleset.

<rule ref="WordPress.Security.EscapeOutput">
	<properties>
		<property name="customPrintingFunctions" type="array" value="prefix_print_form_select_box,print_form_text_field" />
	</properties>
</rule>

CSRF: Custom nonce verification functions

WordPress Sniff Property name Property type Available since:
Security.NonceVerification customNonceVerificationFunctions array 0.5.0

The WordPress.Security.NonceVerification sniff checks that a nonce verification call is made before any - non-nonce - input variables ($_POST / $_FILE / $_GET / $_REQUEST) are used.

To do so, WP core functions which verify a nonce are whitelisted.

If you are unclear about why you should use nonces, please refer to the Codex.

Your application might have wrapper functions in place which handle the nonce verification either via the WP native functions or via other means.

The above property allows you to add the names of these functions to the whitelist of nonce verification functions.

<rule ref="WordPress.Security.NonceVerification">
	<properties>
		<property name="customNonceVerificationFunctions" type="array" value="prefix_verify_nonce" />
	</properties>
</rule>

Admin Bar visibility manipulations

WordPress Sniff Property name Property type Default: Available since:
VIP.AdminBarRemoval remove_only bool true 0.11.0

The WordPress.VIP.AdminBarRemoval sniff was crafted specifically for the WP VIP platform and strongly discourages the removal and hiding of the admin bar.

In some cases, like when reviewing a theme to be published on wordpress.org, you may want to be even stricter and not allow the visibility of the admin bar to be manipulated at all.

In that case, you can set the remove_only property to false for a stricter check.

<rule ref="WordPress.VIP.AdminBarRemoval">
	<properties>
		<property name="remove_only" value="false" />
	</properties>
</rule>

Arbitrary parentheses: amount of whitespace required

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ArbitraryParenthesesSpacing spacingInside int 1 0.14.0

The WordPress.WhiteSpace.ArbitraryParenthesesSpacing sniff verifies that all parentheses which don't belong to function (calls), arrays or languages constructs, have the correct amount of spacing on the inside of the parentheses.

By default, 1 space is expected on the inside of the parentheses.

This can be customized by passing a different value for the spacingInside property.

<rule ref="WordPress.WhiteSpace.ArbitraryParenthesesSpacing">
	<properties>
		<property name="spacingInside" value="0" />
	</properties>
</rule>

Arbitrary parentheses: allow for new lines

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ArbitraryParenthesesSpacing ignoreNewlines bool true 0.14.0

The WordPress.WhiteSpace.ArbitraryParenthesesSpacing sniff verifies that all parentheses which don't belong to function (calls), arrays or languages constructs, have the correct amount of spacing on the inside of the parentheses.

By default, a new line when found - instead of the correct spacing - will be allowed.

By setting the ignoreNewlines property to false, you can force the sniff to throw errors for this, as well as allow phpcbf to auto-fix it.

<rule ref="WordPress.WhiteSpace.ArbitraryParenthesesSpacing">
	<properties>
		<property name="ignoreNewlines" value="false" />
	</properties>
</rule>

Control structures: whitespace checking for closures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing spaces_before_closure_open_paren int -1 0.7.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check whether there is a space between the function keyword and the open parenthesis for closures.

This check is turned off by default.

To turn it on, set the spaces_before_closure_open_paren property to either 0 (space forbidden: function() {} ) or 1 (space required: function () {}).

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="spaces_before_closure_open_paren" value="0" />
	</properties>
</rule>

Control structures: blank lines at the start and end of control structures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing blank_line_check bool false 0.2.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check for stray blank lines at the start and end of control structures and to remove these with the fixer.

This check is turned off by default. To turn it on, set the blank_line_check property to true.

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="blank_line_check" value="true" />
	</properties>
</rule>

Control structures: blank lines after control structures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing blank_line_after_check bool true 0.3.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check for stray blank lines after control structures and to removed these with the fixer.

This check is turned on by default. To turn it off, set the blank_line_after_check property to false.

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="blank_line_after_check" value="false" />
	</properties>
</rule>

Control structures: space before colon in alternative syntax

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing space_before_colon string required 0.4.0

For control structures using alternative syntax - as often used in themes - the WordPress.WhiteSpace.ControlStructureSpacing sniff checks for a space between the condition and the colon.

// Good:
<php if ( isset( $foo ) ) : ?>
Foo!
<?php endif; ?>
// Bad:
<php if ( isset( $foo ) ): ?>
Foo!
<?php endif; ?>

This space is required by default.

You can change this requirement by setting the space_before_colon property. Allowed values: required, forbidden (space not allowed), optional (check is skipped).

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="space_before_colon" value="forbidden" />
	</properties>
</rule>

Precision alignment: exempt certain tokens

WordPress Sniff Property name Property type Available since:
WhiteSpace.PrecisionAlignment ignoreAlignmentTokens array 0.14.0

The WordPress.WhiteSpace.PrecisionAlignment sniff detects precision alignment, i.e. indentation to a position not equal to a tab-stop.

Precision alignment is rarely needed and discouraged for WordPress Core.

The ignoreAlignmentTokens property allows for providing a list of tokens for which (preceding) precision alignment should be ignored.

<rule ref="WordPress.WhiteSpace.PrecisionAlignment">
	<properties>
		<property name="ignoreAlignmentTokens" type="array" value="T_COMMENT,T_INLINE_HTML"/>
	</properties>
</rule>

Arrays: Forcing single item associative arrays to be multi-line

WordPress Sniff Property name Property type Default: Available since:
Arrays.ArrayDeclarationSpacing allow_single_item_single_line_associative_arrays bool true 0.14.0

Since WPCS 0.11.0, the WordPress.Arrays.ArrayDeclarationSpacing sniff contained a check that any associative array was multi-line. In August 2017, the WP Core handbook has been adjusted to only demand this for multi-item associative arrays and the sniff has been adjusted accordingly. This change is included in WPCS since version 0.14.0.

By setting the allow_single_item_single_line_associative_arrays property to false, the sniff will revert to its original behaviour and continue to demand multi-line formatting for all associative arrays, independently of the number of array items.

<rule ref="WordPress.Arrays.ArrayDeclarationSpacing">
	<properties>
		<property name="allow_single_item_single_line_associative_arrays" value="false" />
	</properties>
</rule>

Array alignment: allow for new lines

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment ignoreNewlines bool true 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

To avoid excessively long lines, sometimes the array assignment operator will be on a new line:

$array = array(
    'really_long_array_key'
        => 'an even longer value........................................................',
);

By default this style of array definition is allowed.

By setting the ignoreNewlines property to false, you can force the sniff to throw errors for this and to auto-fix this when running phpcbf.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="ignoreNewlines" value="false" />
	</properties>
</rule>

Array alignment: allow non-exact alignment

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment exact bool true 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

If the exact property is true (default), the alignment has to be exactly 1 space from the end of the widest index.

By setting the exact property to false, this behaviour can be made more lenient.

When set to false, the largest index key + 1 space is taken as a minimum and if a predominant number of items is already aligned at a position which is more than the minimum, this predominant alignment position is taken as the preferred alignment.

This allows for cleaner diffs as the array operators do not have to be realigned when the array item with the largest key is taken out.

Example:

/*
 * With `exact` set to `true`, this array would be fixed to align at the end
 * of `even_longer_key` + 1 space.
 * With `exact` set to `false`, the below would be accepted as a valid alignment.
 *
 * And with `exact` set to `false`, taking the `even_longer_key` array item
 * out of the array would not impact the alignment, while with `exact` set
 * to `true`, the assignment operators for the whole array would need
 * to be re-aligned.
 */
$array = array(
    'short_key'         => 'value',
    'longer_key'        => 'value',
    'even_longer_key'   => 'value',
);
<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="exact" value="false" />
	</properties>
</rule>

Array alignment: maximum column

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment maxColumn int 1000 0.14.0

Note: while the sniff default is 1000, the WordPress-Core setting for this property is 60!

As the WordPress-Core ruleset is included in the WordPress, WordPress-Extra and WordPress-VIP rulesets, this value of 60 will be inherited by these three rulesets.

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

When an array contains very long keys or has a lot or indentation/nesting, this alignment could make the lines even longer.

To avoid excessively long lines, the maximum position within a line at which an array assignment operator will be aligned is determined by the maxColumn property.

For example, if this value is set to 60, as it is for the WordPress-Core ruleset, it will:

  • if the expected column < 60, align at the expected column.
  • if the expected column >= 60, align at column 60.
  • for the outliers, i.e. the array indexes where the end position goes past column 60, it will not align the arrow, the sniff will just make sure there is only one space between the end of the array index and the double arrow.

N.B.: The maxColumn value is regarded as a hard value, i.e. includes indentation, so setting it very low is not a good idea.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="maxColumn" value="80" />
	</properties>
</rule>

Array alignment: dealing with multi-line items

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment alignMultilineItems string always 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

Sometimes, however, there may be complex nested arrays which makes alignment of the top-level array assignment operators awkward.

With this property, you can toggle whether or not to align the arrow operator for multi-line array items, such as array items with another array as the value.

Note: Whether or not an item is regarded as multi-line is based on the value of the item, not the key.

Valid values for the property are:

  • always: Default. Align all arrays items regardless of single/multi-line.

  • never: Never align array items which span multiple lines.

    This will enforce one space between the array index and the double arrow operator for multi-line array items, independently of the alignment of the rest of the array items.

    Multi-line items where the arrow is already aligned with the "expected" alignment, however, will be left alone.

  • operator + number : Only align the operator for multi-line arrays items if the percentage of multi-line items passes the comparison.

    • As it is a percentage, the number has to be between 0 and 100.
    • Supported operators: <, <=, >, >=, ==, =, !=, <>
    • The percentage is calculated against all array items (with and without assignment operator).
    • The (new) expected alignment will be calculated based only on the items being aligned.
    • Multi-line items where the arrow is already aligned with the (new) "expected" alignment, however, will be left alone.

    Examples:

    • Setting this to !=100 or <100 means that alignment will be enforced, unless all array items are multi-line.

      This is probably the most commonly desired situation.

    • Setting this to =100 means that alignment will only be enforced, if all array items are multi-line.

    • Setting this to <50 means that the majority of array items need to be single line before alignment is enforced for multi-line items in the array.

    • Setting this to =0 is useless as in that case there are no multi-line items in the array anyway.

This setting will respect the ignoreNewlines and maxColumnn settings.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="alignMultilineItems" value="!=100" />
	</properties>
</rule>

Optional, but discouraged properties

Internationalization: check for translators comments

WordPress Sniff Property name Property type Default: Available since:
WP.I18n check_translator_comments bool true 0.11.0

Allows to turn off checking for translators comments for text strings containing placeholders.

<rule ref="WordPress.WP.I18n">
	<properties>
		<property name="check_translator_comments" value="false" />
	</properties>
</rule>

Note: Alternatively, you can achieve the same effect by using the following syntax in your custom ruleset:

<rule ref="WordPress">
	<exclude name="WordPress.WP.I18n.TranslatorsCommentWrongStyle" />
	<exclude name="WordPress.WP.I18n.MissingTranslatorsComment" />
</rule>

Error type for file system writes

WordPress Sniff Property name Property type Default: Available since:
VIP.FileSystemWritesDisallow error bool true 0.3.0

The sniff which checks for the use of functions writing to the file system will by default throw an error if use of one of the functions is detected.

The behaviour can be changed to throw a warning instead using the error property.

<rule ref="WordPress.VIP.FileSystemWritesDisallow">
	<properties>
		<property name="error" value="false" />
	</properties>
</rule>

Note: This property should be considered deprecated. You can achieve the same effect by using the following syntax in your custom ruleset:

<rule ref="WordPress.VIP.FileSystemWritesDisallow.IndividualFunctionErrorCode">
	<type>warning</type>
</rule>