All notable changes to this project will be documented in this file.
This projects adheres to Semantic Versioning and Keep a CHANGELOG.
No documentation available about unreleased changes as of yet.
3.1.0 - 2024-03-25
- WordPress-Core ruleset: now includes the
Universal.PHP.LowercasePHPTagsniff. - WordPress-Extra ruleset: now includes the
Generic.CodeAnalysis.RequireExplicitBooleanOperatorPrecedenceand theUniversal.CodeAnalysis.NoDoubleNegativesniffs. - The
sanitize_locale_name()function to the list of known "escaping" functions. Props @Chouby - The
sanitize_locale_name()function to the list of known "sanitize & unslash" functions. Props @Chouby
- The minimum required
PHP_CodeSnifferversion to 3.9.0 (was 3.7.2). - The minimum required
PHPCSUtilsversion to 1.0.10 (was 1.0.8). - The minimum required
PHPCSExtraversion to 1.2.1 (was 1.1.0). Please ensure you runcomposer update wp-coding-standards/wpcs --with-dependenciesto benefit from these updates. - Core ruleset: the spacing after the
usekeyword for closureusestatements will now consistently be checked. Props @westonruter for reporting. - The default value for
minimum_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to6.2. WordPress.NamingConventions.PrefixAllGlobalshas been updated to recognize pluggable functions introduced in WP 6.4 and 6.5.WordPress.NamingConventions.ValidPostTypeSlughas been updated to recognize reserved post types introduced in WP 6.4 and 6.5.WordPress.WP.ClassNameCasehas been updated to recognize classes introduced in WP 6.4 and 6.5.WordPress.WP.DeprecatedClassesnow detects classes deprecated in WordPress up to WP 6.5.WordPress.WP.DeprecatedFunctionsnow detects functions deprecated in WordPress up to WP 6.5.- The
IsUnitTestTraitwill now recognize classes which extend the new WP CoreWP_Font_Face_UnitTestCaseclass as test classes. - The test suite can now run on PHPUnit 4.x - 9.x (was 4.x - 7.x), which should make contributing more straight forward.
- Various housekeeping, includes a contribution from @rodrigoprimo.
WordPress.WP.PostsPerPagecould potentially result in anInternal.Exceptionwhen encountering a query string which doesn't include the value forposts_per_pagein the query string. Props @anomiex for reporting.
3.0.1 - 2023-09-14
- In WordPressCS 3.0.0, the functionality of the
WordPress.Security.EscapeOutputsniff was updated to report unescaped message parameters passed to exceptions created inthrowstatements. This specific violation now has a separate error code:ExceptionNotEscaped. This will allow users to ignore or exclude that specific error code. Props @anomiex. The error code(s) for other escaping issues flagged by the sniff remain unchanged.
- Updated the CI workflow to test the example ruleset for issues.
- Funding files and updates in the Readme about funding the project.
- Fixed a sniff name in the
phpcs.xml.dist.samplefile (case-sensitive sniff name). Props @dawidurbanski.
3.0.0 - 2023-08-21
At long last... WordPressCS 3.0.0 is here.
This is an important release which makes significant changes to improve the accuracy, performance, stability and maintainability of all sniffs, as well as making WordPressCS much better at handling modern PHP.
WordPressCS 3.0.0 contains breaking changes, both for people using ignore annotations, people maintaining custom rulesets, as well as for sniff developers who maintain a custom PHPCS standard based on WordPressCS.
If you are an end-user or maintain a custom WordPressCS based ruleset, please start by reading the Upgrade Guide to WordPressCS 3.0.0 for end-users which lists the most important changes and contains a step by step guide for upgrading.
If you are a maintainer of an external standard based on WordPressCS and any of your custom sniffs are based on or extend WordPressCS sniffs, please read the Upgrade Guide to WordPressCS 3.0.0 for Developers.
In all cases, please read the complete changelog carefully before you upgrade.
- Dependencies on the following packages: PHPCSUtils, PHPCSExtra and the Composer PHPCS plugin.
- A best effort has been made to add support for the new PHP syntaxes/features to all WordPressCS native sniffs and utility functions (or to verify/improve existing support).
While support in external sniffs used by WordPressCS has not be exhaustively verified, a lot of work has been done to try and add support for new PHP syntaxes to those as well.
WordPressCS native sniffs and utilities have received fixes for the following syntaxes:
- PHP 7.2
- Keyed lists.
- PHP 7.3
- Flexible heredoc/nowdoc (providing the PHPCS scan is run on PHP 7.3 or higher).
- Trailing commas in function calls.
- PHP 7.4
- Arrow functions.
- Array unpacking in array expressions.
- Numeric literals with underscores.
- Typed properties.
- Null coalesce equals operator.
- PHP 8.0
- Nullsafe object operators.
- Match expressions.
- Named arguments in function calls.
- Attributes.
- Union types // including supporting the
falseandnulltypes. - Constructor property promotion.
$object::class- Throw as an expression.
- PHP 8.1
- Enumerations.
- Explicit octal notation.
- Final class constants
- First class callables.
- Intersection types.
- PHP 8.2
- Constants in traits.
- PHP 7.2
- New
WordPress.CodeAnalysis.AssignmentInTernaryConditionsniff to theWordPress-Coreruleset which partially replaces the removedWordPress.CodeAnalysis.AssignmentInConditionsniff. - New
WordPress.WhiteSpace.ObjectOperatorSpacingsniff which replaces the use of theSquiz.WhiteSpace.ObjectOperatorSpacingsniff in theWordPress-Coreruleset. - New
WordPress.WP.ClassNameCasesniff to theWordPress-Coreruleset, to check that any class name references to WP native classes and classes from external dependencies use the case of the class as per the class declaration. - New
WordPress.WP.Capabilitiessniff to theWordPress-Extraruleset. This sniff checks that valid capabilities are used, not roles or user levels. Props, amongst others, to @grappler and @khacoder. Custom capabilities can be added to the sniff via acustom_capabilitiesruleset property. The sniff also supports theminimum_wp_versionproperty to allow the sniff to accurately determine how the use of deprecated capabilities should be flagged. - The
WordPress.WP.CapitalPDangitsniff contains a new check to verify the correct spelling ofWordPressin namespace names. - The
WordPress.WP.I18nsniff contains a newEmptyTextDomainerror code for an empty text string being passed as the text domain, which overrules the default value of the parameter and renders a text untranslatable. - The
WordPress.DB.PreparedSQLPlaceholderssniff has been expanded with additional checks for the correct use of the%iplaceholder, which was introduced in WP 6.2. Props @craigfrancis. The sniff now also supports theminimum_wp_versionruleset property to determine whether the%iplaceholder can be used. WordPress-Core: the following additional sniffs (or select error codes from these sniffs) have been added to the ruleset:Generic.CodeAnalysis.AssignmentInCondition,Generic.CodeAnalysis.EmptyPHPStatement(replaces the WordPressCS native sniff),Generic.VersionControl.GitMergeConflict,Generic.WhiteSpace.IncrementDecrementSpacing,Generic.WhiteSpace.LanguageConstructSpacing,Generic.WhiteSpace.SpreadOperatorSpacingAfter,PSR2.Classes.ClassDeclaration,PSR2.Methods.FunctionClosingBrace,PSR12.Classes.ClassInstantiation,PSR12.Files.FileHeader(select error codes only),PSR12.Functions.NullableTypeDeclaration,PSR12.Functions.ReturnTypeDeclaration,PSR12.Traits.UseDeclaration,Squiz.Functions.MultiLineFunctionDeclaration(replaces part of theWordPress.WhiteSpace.ControlStructureSpacingsniff),Modernize.FunctionCalls.Dirname,NormalizedArrays.Arrays.ArrayBraceSpacing(replaces part of theWordPress.Arrays.ArrayDeclarationSpacingsniff),NormalizedArrays.Arrays.CommaAfterLast(replaces the WordPressCS native sniff),Universal.Classes.ModifierKeywordOrder,Universal.Classes.RequireAnonClassParentheses,Universal.Constants.LowercaseClassResolutionKeyword,Universal.Constants.ModifierKeywordOrder,Universal.Constants.UppercaseMagicConstants,Universal.Namespaces.DisallowCurlyBraceSyntax,Universal.Namespaces.DisallowDeclarationWithoutName,Universal.Namespaces.OneDeclarationPerFile,Universal.NamingConventions.NoReservedKeywordParameterNames,Universal.Operators.DisallowShortTernary(replaces the WordPressCS native sniff),Universal.Operators.DisallowStandalonePostIncrementDecrement,Universal.Operators.StrictComparisons(replaces the WordPressCS native sniff),Universal.Operators.TypeSeparatorSpacing,Universal.UseStatements.DisallowMixedGroupUse,Universal.UseStatements.KeywordSpacing,Universal.UseStatements.LowercaseFunctionConst,Universal.UseStatements.NoLeadingBackslash,Universal.UseStatements.NoUselessAliases,Universal.WhiteSpace.CommaSpacing,Universal.WhiteSpace.DisallowInlineTabs(replaces the WordPressCS native sniff),Universal.WhiteSpace.PrecisionAlignment(replaces the WordPressCS native sniff),Universal.WhiteSpace.AnonClassKeywordSpacing.WordPress-Extra: the following additional sniffs have been added to the ruleset:Generic.CodeAnalysis.UnusedFunctionParameter,Universal.Arrays.DuplicateArrayKey,Universal.CodeAnalysis.ConstructorDestructorReturn,Universal.CodeAnalysis.ForeachUniqueAssignment,Universal.CodeAnalysis.NoEchoSprintf,Universal.CodeAnalysis.StaticInFinalClass,Universal.ControlStructures.DisallowLonelyIf,Universal.Files.SeparateFunctionsFromOO.WordPress.Utils.I18nTextDomainFixer: theload_script_textdomain()function to the functions the sniff looks for.WordPress.WP.AlternativeFunctions: the following PHP native functions have been added to the sniff and will now be flagged when used:unlink()(in a newunlinkgroup) ,rename()(in a newrenamegroup),chgrp(),chmod(),chown(),is_writable()is_writeable(),mkdir(),rmdir(),touch(),fputs()(in the existingfile_system_operationsgroup, which was previously namedfile_system_read). Props @sandeshjangam and @JDGrimes.- The
PHPUnit_Adapter_TestCaseclass to the list of "known test (case) classes". - The
antispambot()function to the list of known "formatting" functions. - The
esc_xml()andwp_kses_one_attr()functions to the list of known "escaping" functions. - The
wp_timezone_choice()andwp_readonly()functions to the list of known "auto escaping" functions. - The
sanitize_url()andwp_kses_one_attr()functions to the list of known "sanitizing" functions. - Metrics for blank lines at the start/end of a control structure body to the
WordPress.WhiteSpace.ControlStructureSpacingsniff. These can be displayed using--report=infowhen theblank_line_checkproperty has been set totrue. - End-user documentation to the following new and pre-existing sniffs:
WordPress.DateTime.RestrictedFunctions,WordPress.NamingConventions.PrefixAllGlobals(props @Ipstenu),WordPress.PHP.StrictInArray(props @marconmartins),WordPress.PHP.YodaConditions(props @Ipstenu),WordPress.WhiteSpace.ControlStructureSpacing(props @ckanitz),WordPress.WhiteSpace.ObjectOperatorSpacing,WordPress.WhiteSpace.OperatorSpacing(props @ckanitz),WordPress.WP.CapitalPDangit(props @NielsdeBlaauw),WordPress.WP.Capabilities,WordPress.WP.ClassNameCase,WordPress.WP.EnqueueResourceParameters(props @NielsdeBlaauw). This documentation can be exposed via thePHP_CodeSniffer--generator=...command-line argument. Note: all sniffs which have been added from PHPCSExtra (Universal, Modernize, NormalizedArrays sniffs) are also fully documented.
- New Helper classes:
ArrayWalkingFunctionsHelperConstantsHelper*ContextHelper*DeprecationHelper*FormattingFunctionsHelperListHelper*RulesetPropertyHelper*SnakeCaseHelper*UnslashingFunctionsHelperValidationHelperVariableHelper*WPGlobalVariablesHelperWPHookHelper
- New Helper traits:
EscapingFunctionsTraitIsUnitTestTraitMinimumWPVersionTraitPrintingFunctionsTraitSanitizationHelperTrait*WPDBTrait
These classes and traits mostly contain pre-existing functionality moved from the Sniff class.
The classes marked with an * are considered internal and do not have any promise of future backward compatibility.
More information is available in the Upgrade Guide to WordPressCS 3.0.0 for Developers.
- As of this version, installation via Composer is the only supported manner of installation. Installing in a different manner (git clone/PEAR/PHAR) is still possible, but no longer supported.
- The minimum required
PHP_CodeSnifferversion to 3.7.2 (was 3.3.1). - Composer: the package will now identify itself as a static analysis tool.
- The PHP
filter,libxmlandXMLReaderextensions are now explicitly required. It is recommended to also have theMbstringandiconvextensions enabled for the most accurate results. - The release branch has been renamed from
mastertomain. - The following sniffs have been moved from
WordPress-ExtratoWordPress-Core: theGeneric.Files.OneObjectStructurePerFile(also changed fromwarningtoerror),Generic.PHP.BacktickOperator,PEAR.Files.IncludingFile,PSR2.Classes.PropertyDeclaration,PSR2.Methods.MethodDeclaration,Squiz.Scope.MethodScope,Squiz.WhiteSpace.ScopeKeywordSpacingsniffs. Props, amongst others, to @desrosj. WordPress-Core: TheGeneric.Arrays.DisallowShortArraySyntaxsniff has been replaced by theUniversal.Arrays.DisallowShortArraySyntaxsniff. The new sniff will recognize short lists correctly and ignore them.WordPress-Core: TheGeneric.Files.EndFileNewlinesniff has been replaced by the more comprehensivePSR2.Files.EndFileNewlinesniff.- A number of sniffs support setting the minimum WP version for the code being scanned.
This could be done in two different ways:
- By setting the
minimum_supported_versionproperty for each sniff from a ruleset. - By passing
--runtime-set minimum_supported_wp_version #.#on the command line. The names of the property and the CLI setting have now been aligned to both useminimum_wp_versionas the name. Both ways of passing the value are still supported.
- By setting the
WordPress.NamingConventions.PrefixAllGlobals: thecustom_test_class_whitelistproperty has been renamed tocustom_test_classes.WordPress.NamingConventions.ValidVariableName: thecustomPropertiesWhitelistproperty has been renamed toallowed_custom_properties.WordPress.PHP.NoSilencedErrors: thecustom_whitelistproperty has been renamed tocustomAllowedFunctionsList.WordPress.PHP.NoSilencedErrors: theuse_default_whitelistproperty has been renamed tousePHPFunctionsList.WordPress.WP.GlobalVariablesOverride: thecustom_test_class_whitelistproperty has been renamed tocustom_test_classes.- Sniffs are now able to handle fully qualified names for custom test classes provided via a
custom_test_classes(previouslycustom_test_class_whitelist) ruleset property. - The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to6.0. WordPress.NamingConventions.PrefixAllGlobalsnow takes new pluggable constants into account as introduced in WordPress up to WP 6.3.WordPress.NamingConventions.ValidPostTypeSlugnow takes new reserved post types into account as introduced in WordPress up to WP 6.3.WordPress.WP.DeprecatedClassesnow detects classes deprecated in WordPress up to WP 6.3.WordPress.WP.DeprecatedFunctionsnow detects functions deprecated in WordPress up to WP 6.3.WordPress.WP.DeprecatedParametersnow detects parameters deprecated in WordPress up to WP 6.3.WordPress.WP.DeprecatedParameterValuesnow detects parameter values deprecated in WordPress up to WP 6.3.WordPress.Utils.I18nTextDomainFixer: the lists of recognized plugin and theme header tags has been updated based on the current information in the plugin and theme handbooks.WordPress.WP.AlternativeFunctions: the "group" namefile_system_read, which can be used with theexcludeproperty, has been renamed tofile_system_operations. This also means that the error codes for individual functions flagged via that group have changed fromWordPress.WP.AlternativeFunctions.file_system_read_*toWordPress.WP.AlternativeFunctions.file_system_operations_*.WordPress.WP.CapitalPDangit: theMisspellederror code has been split into two error codes -MisspelledInTextandMisspelledInComment- to allow for more modular exclusions/selectively turning off the auto-fixer for the sniff.WordPress.WP.I18nno longer throws both theMissingSingularPlaceholderand theMismatchedPlaceholdersfor the same code, as the errors have an overlap.WordPress-Core: previously only the spacing around commas in arrays, function declarations and function calls was checked. Now, the spacing around commas will be checked in all contexts.WordPress.Arrays.ArrayKeySpacingRestrictions: a newSpacesBetweenBracketserror code has been introduced for the spacing between square brackets for array assignments without key. Previously, this would throw aNoSpacesAroundArrayKeyserror with an unclear error message.WordPress.Files.FileNamenow recognizes more word separators, meaning that files using other word separators than underscores will now be flagged for not using hyphenation.WordPress.Files.FileNamenow checks if a file contains a test class and if so, will bow out. This change was made to prevent issues with PHPUnit 9.1+, which strongly prefers PSR4-style file names. Whether something is test class or not is based on a pre-defined list of "known" test case classes which can be extended and, optionally, a list of user provided test case classes provided via setting thecustom_test_classesproperty in a custom ruleset or the complete test directory can be excluded via a custom ruleset.WordPress.NamingConventions.PrefixAllGlobalsnow allows for pluggable functions and classes, which should not be prefixed when "plugged".WordPress.PHP.NoSilencedErrors: the metric, which displays in theinforeport, has been renamed from "whitelisted function call" to "silencing allowed function call".WordPress.Security.EscapeOutputnow flags the use ofget_search_query( false )when generating output (as thefalseturns off the escaping).WordPress.Security.EscapeOutputnow also examines parameters passed for exception creation inthrowstatements and expressions for correct escaping.WordPress.Security.ValidatedSanitizedInputnow examines all superglobal (except for$GLOBALS). Previously, the$_SESSIONand$_ENVsuperglobals would not be flagged as needing validation/sanitization.WordPress.WP.I18nnow recognizes the new PHP 8.0+handHtype specifiers.WordPress.WP.PostsPerPagehas improved recognition for numbers prefixed with a unary operator and non-decimal numbers.WordPress.DB.PreparedSQLwill identify more precisely the code which is problematic.WordPress.DB.PreparedSQLPlaceholderswill identify more precisely the code which is problematic.WordPress.DB.SlowDBQuerywill identify more precisely the code which is problematic.WordPress.Security.PluginMenuSlug: the error will now be thrown more precisely on the code which triggered the error. Depending on code layout, this may mean that an error will now be thrown on a different line.WordPress.WP.DiscouragedConstants: the error will now be thrown more precisely on the code which triggered the error. Depending on code layout, this may mean that an error will now be thrown on a different line.WordPress.WP.EnqueuedResourceParameters: the error will now be thrown more precisely on the code which triggered the error. Depending on code layout, this may mean that an error will now be thrown on a different line.WordPress.WP.I18n: the errors will now be thrown more precisely on the code which triggered the error. Depending on code layout, this may mean that an error will now be thrown on a different line.WordPress.WP.PostsPerPagewill identify more precisely the code which is problematic.WordPress.PHP.TypeCasts.UnsetFoundhas been changed from awarningto anerroras the(unset)cast is no longer available in PHP 8.0 and higher.WordPress.WP.EnqueuedResourceParameters.MissingVersionhas been changed from anerrorto awarning.WordPress.Arrays.ArrayKeySpacingRestrictions: improved the clarity of the error messages for theTooMuchSpaceBeforeKeyandTooMuchSpaceAfterKeyerror codes.WordPress.CodeAnalysis.EscapedNotTranslated: improved the clarity of the error message.WordPress.PHP.IniSet: improved the clarity of the error messages for the sniff.WordPress.PHP.PregQuoteDelimiter: improved the clarity of the error message for theMissingerror code.WordPress.PHP.RestrictedFunctions: improved the clarity of the error messages for the sniff.WordPress.PHP.RestrictedPHPFunctions: improved the error message for thecreate_function_create_functionerror code.WordPress.PHP.TypeCast: improved the clarity of the error message for theUnsetFounderror code. It will no longer advise assigningnull.WordPress.Security.SafeRedirect: improved the clarity of the error message. (very minor)WordPress.Security.ValidatedSanitizedInput: improved the clarity of the error messages for theMissingUnslasherror code.WordPress.WhiteSpace.CastStructureSpacing: improved the clarity of the error message for theNoSpaceBeforeOpenParenthesiserror code.WordPress.WP.I18n: improved the clarity of the error messages for the sniff.WordPress.WP.I18n: the error messages will now use the correct parameter name.- The error messages for the
WordPress.CodeAnalysis.EscapedNotTranslated,WordPress.NamingConventions.PrefixAllGlobals,WordPress.NamingConventions.ValidPostTypeSlug,WordPress.PHP.IniSet, and theWordPress.PHP.NoSilencedErrorssniff will now display the code sample found without comments and extranuous whitespace. - Various updates to the README, the example ruleset and other documentation. Props, amongst others, to @Luc45, @slaFFik.
- Continuous Integration checks are now run via GitHub Actions. Props @desrosj.
- Various other CI/QA improvements.
- Code coverage will now be monitored via CodeCov.
- All sniffs are now also being tested against PHP 8.0, 8.1, 8.2 and 8.3 for consistent sniff results.
- All non-abstract classes in WordPressCS are now
finalwith the exception of the following four classes which are known to be extended by external PHPCS standards build on top of WordPressCS:WordPress.NamingConventions.ValidHookName,WordPress.Security.EscapeOutput,WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput. - Most remaining utility properties and methods, previously contained in the
WordPressCS\WordPress\Sniffclass, have been moved to dedicated Helper classes and traits or, in some cases, to the sniff class using them. As this change is only relevant for extenders, the full details of these moves are not included in this changelog, but can be found in the Developers Upgrade Guide to WordPressCS 3.0.0 - A few customizable
publicproperties, which were used by multiple sniffs, have been moved from*Sniffclasses to traits. Again, the full details of these moves are not included in this changelog, but can be found in the Developers Upgrade Guide to WordPressCS 3.0.0 - A number of non-public properties in sniffs have been renamed. As this change is only relevant for extenders, the full details of these renames are not included in this changelog, but can be found in the Developers Upgrade Guide to WordPressCS 3.0.0
AbstractFunctionRestrictionsSniff: Thewhitelistkey in the$groupsarray property has been renamed toallow.- The
WordPress.NamingConventions.ValidFunctionNamesniff no longer extends the similar PHPCS nativePEARsniff.
- Support for the deprecated, old-style WordPressCS native ignore annotations. Use the PHPCS native selective ignore annotations instead.
- The following WordPressCS native sniffs have been removed:
- The
WordPress.Arrays.CommaAfterArrayItemsniff (replaced by theNormalizedArrays.Arrays.CommaAfterLastand theUniversal.WhiteSpace.CommaSpacingsniffs). - The
WordPress.Classes.ClassInstantiationsniff (replaced by thePSR12.Classes.ClassInstantiation,Universal.Classes.RequireAnonClassParenthesesandUniversal.WhiteSpace.AnonClassKeywordSpacingsniffs). - The
WordPress.CodeAnalysis.AssignmentInConditionsniff (replaced by theGeneric.CodeAnalysis.AssignmentInConditionand theWordPress.CodeAnalysis.AssignmentInTernaryConditionsniffs). - The
WordPress.CodeAnalysis.EmptyStatementsniff (replaced by theGeneric.CodeAnalysis.EmptyPHPStatementsniff). - The
WordPress.PHP.DisallowShortTernarysniff (replaced by theUniversal.Operators.DisallowShortTernarysniff). - The
WordPress.PHP.StrictComparisonssniff (replaced by theUniversal.Operators.StrictComparisonssniff). - The
WordPress.WhiteSpace.DisallowInlineTabssniff (replaced by theUniversal.WhiteSpace.DisallowInlineTabssniff). - The
WordPress.WhiteSpace.PrecisionAlignmentsniff (replaced by theUniversal.WhiteSpace.PrecisionAlignmentsniff). - The
WordPress.WP.TimezoneChangesniff (replaced by theWordPress.DateTime.RestrictedFunctionssniff). This sniff was previously already deprecated.
- The
WordPress-Extra: TheSquiz.WhiteSpace.LanguageConstructSpacingsniff (replaced by the added, more comprehensiveGeneric.WhiteSpace.LanguageConstructSpacingsniff in theWordPress-Coreruleset).WordPress.Arrays.ArrayDeclarationSpacing: array brace spacing checks (replaced by theNormalizedArrays.Arrays.ArrayBraceSpacingsniff).WordPress.WhiteSpace.ControlStructureSpacing: checks for the spacing for function declarations (replaced by theSquiz.Functions.MultiLineFunctionDeclarationsniff). Includes removal of thespaces_before_closure_open_parenproperty for this sniff.WordPress.WP.I18n: thecheck_translator_commentsproperty. Exclude theWordPress.WP.I18n.MissingTranslatorsCommentand theWordPress.WP.I18n.TranslatorsCommentWrongStyleerror codes instead.- WordPressCS will no longer check for assigning the return value of an object instantiation by reference.
This is a PHP parse error since PHP 7.0. Use the
PHPCompatibilityWPstandard to check for PHP cross-version compatibility issues. - The check for object instantiations will no longer check JavaScript files.
- The
WordPress.Arrays.ArrayKeySpacingRestrictions.MissingBracketClosererror code as sniffs should not report on parse errors. - The
WordPress.CodeAnalysis.AssignmentIn[Ternary]Condition.NonVariableAssignmentFounderror code as sniffs should not report on parse errors. - The
Block_Supported_Styles_Testclass will no longer incorrectly be recognized as an extendable test case class.
AbstractArrayAssignmentRestrictionsSniff: support for the optional'callback'key in the array returned bygetGroups().WordPressCS\WordPress\PHPCSHelperclass (use thePHPCSUtils\BackCompat\Helperclass instead).WordPressCS\WordPress\Sniff::addMessage()method (use thePHPCSUtils\Utils\MessageHelper::addMessage()method instead).WordPressCS\WordPress\Sniff::addFixableMessage()method (use thePHPCSUtils\Utils\MessageHelper::addFixableMessage()method instead).WordPressCS\WordPress\Sniff::determine_namespace()method (use thePHPCSUtils\Utils\Namespaces::determineNamespace()method instead).WordPressCS\WordPress\Sniff::does_function_call_have_parameters()method (use thePHPCSUtils\Utils\PassedParameters::hasParameters()method instead).WordPressCS\WordPress\Sniff::find_array_open_close()method (use thePHPCSUtils\Utils\Arrays::getOpenClose()method instead).WordPressCS\WordPress\Sniff::find_list_open_close()method (use thePHPCSUtils\Utils\Lists::getOpenClose()method instead).WordPressCS\WordPress\Sniff::get_declared_namespace_name()method (use thePHPCSUtils\Utils\Namespaces::getDeclaredName()method instead).WordPressCS\WordPress\Sniff::get_function_call_parameter_count()method (use thePHPCSUtils\Utils\PassedParameters::getParameterCount()method instead).WordPressCS\WordPress\Sniff::get_function_call_parameters()method (use thePHPCSUtils\Utils\PassedParameters::getParameters()method instead).WordPressCS\WordPress\Sniff::get_function_call_parameter()method (use thePHPCSUtils\Utils\PassedParameters::getParameter()method instead).WordPressCS\WordPress\Sniff::get_interpolated_variables()method (use thePHPCSUtils\Utils\TextStrings::getEmbeds()method instead).WordPressCS\WordPress\Sniff::get_last_ptr_on_line()method (no replacement available at this time).WordPressCS\WordPress\Sniff::get_use_type()method (use thePHPCSUtils\Utils\UseStatements::getType()method instead).WordPressCS\WordPress\Sniff::has_whitelist_comment()method (no replacement).WordPressCS\WordPress\Sniff::$hookFunctionsproperty (no replacement available at this time).WordPressCS\WordPress\Sniff::init()method (no replacement).WordPressCS\WordPress\Sniff::is_class_constant()method (use thePHPCSUtils\Utils\Scopes::isOOConstant()method instead).WordPressCS\WordPress\Sniff::is_class_property()method (use thePHPCSUtils\Utils\Scopes::isOOProperty()method instead).WordPressCS\WordPress\Sniff::is_foreach_as()method (use thePHPCSUtils\Utils\Context::inForeachCondition()method instead).WordPressCS\WordPress\Sniff::is_short_list()method (depending on your needs, use thePHPCSUtils\Utils\Lists::isShortList()or thePHPCSUtils\Utils\Arrays::isShortArray()method instead).WordPressCS\WordPress\Sniff::is_token_in_test_method()method (no replacement available at this time).WordPressCS\WordPress\Sniff::REGEX_COMPLEX_VARSconstant (use the PHPCSUtilsPHPCSUtils\Utils\TextStrings::stripEmbeds()andPHPCSUtils\Utils\TextStrings::getEmbeds()methods instead).WordPressCS\WordPress\Sniff::string_to_errorcode()method (use thePHPCSUtils\Utils\MessageHelper::stringToErrorcode()method instead).WordPressCS\WordPress\Sniff::strip_interpolated_variables()method (use thePHPCSUtils\Utils\TextStrings::stripEmbeds()method instead).WordPressCS\WordPress\Sniff::strip_quotes()method (use thePHPCSUtils\Utils\TextStrings::stripQuotes()method instead).WordPressCS\WordPress\Sniff::valid_direct_scope()method (use thePHPCSUtils\Utils\Scopes::validDirectScope()method instead).- Unused dev-only files in the (now removed)
bindirectory.
- All sniffs which, in one way or another, check whether code represents a short list or a short array will now do so more accurately. This fixes various false positives and false negatives.
- Sniffs supporting the
minimum_wp_versionproperty (previouslyminimum_supported_version) will no longer throw a "passing null to non-nullable" deprecation notice on PHP 8.1+. WordPress.WhiteSpace.ControlStructureSpacingno longer throws aTypeErroron PHP 8.0+.WordPress.NamingConventions.PrefixAllGlobalsno longer throws a "passing null to non-nullable" deprecation notice on PHP 8.1+.WordPress.WP.I18nno longer throws a "passing null to non-nullable" deprecation notice on PHP 8.1+.VariableHelper::is_comparison()(previouslySniff::is_comparison()): fixed risk of undefined array key notice when scanning code containing parse errors.AbstractArrayAssignmentRestrictionsSniffcould previously get confused when it encountered comments in unexpected places. This fix has a positive impact on all sniffs which are based on this abstract (2 sniffs).AbstractArrayAssignmentRestrictionsSniffno longer examines numeric string keys as PHP treats those as integer keys, which were never intended as the target of this abstract. This fix has a positive impact on all sniffs which are based on this abstract (2 sniffs).AbstractArrayAssignmentRestrictionsSniffin case of duplicate entries, the sniff will now only examine the last value, as that's the value PHP will see. This fix has a positive impact on all sniffs which are based on this abstract (2 sniffs).AbstractArrayAssignmentRestrictionsSniffnow determines the assigned value with higher accuracy. This fix has a positive impact on all sniffs which are based on this abstract (2 sniffs).AbstractClassRestrictionsSniffnow treats thenamespacekeyword when used as an operator case-insensitively. This fix has a positive impact on all sniffs which are based on this abstract (3 sniffs).AbstractClassRestrictionsSniffnow treats the hierarchy keywords (self,parent,static) case-insensitively. This fix has a positive impact on all sniffs which are based on this abstract (3 sniffs).AbstractClassRestrictionsSniffnow limits itself correctly when trying to find a class name before a::. This fix has a positive impact on all sniffs which are based on this abstract (3 sniffs).AbstractClassRestrictionsSniff: false negatives on class instantiation statements ending on a PHP close tag. This fix has a positive impact on all sniffs which are based on this abstract (3 sniffs).AbstractClassRestrictionsSniff: false negatives on class instantiation statements combined with method chaining. This fix has a positive impact on all sniffs which are based on this abstract (3 sniffs).AbstractFunctionRestrictionsSniff: false positives on function declarations when the function returns by reference. This fix has a positive impact on all sniffs which are based on this abstract (nearly half of the WordPressCS sniffs).AbstractFunctionRestrictionsSniff: false positives on instantiation of a class with the same name as a targeted function. This fix has a positive impact on all sniffs which are based on this abstract (nearly half of the WordPressCS sniffs).AbstractFunctionRestrictionsSniffnow respects that function names in PHP are case-insensitive in more places. This fix has a positive impact on all sniffs which are based on this abstract (nearly half of the WordPressCS sniffs).- Various utility methods in Helper classes/traits have received fixes to correctly treat function and class names as case-insensitive. These fixes have a positive impact on all sniffs using these methods.
- Version comparisons done by sniffs supporting the
minimum_wp_versionproperty (previouslyminimum_supported_version) will now be more precise. WordPress.Arrays.ArrayIndentationnow ignores indentation issues for array items which are not the first thing on a line. This fixes a potential fixer conflict.WordPress.Arrays.ArrayKeySpacingRestrictions: signed positive integer keys will now be treated the same as signed negative integer keys.WordPress.Arrays.ArrayKeySpacingRestrictions: keys consisting of calculations will now be recognized more accurately.WordPress.Arrays.ArrayKeySpacingRestrictions.NoSpacesAroundArrayKeys: now has better protection in case of a fixer conflict.WordPress.Classes.ClassInstantiationcould create parse errors when fixing a class instantiation using variable variables. This has been fixed by replacing the sniff with thePSR12.Classes.ClassInstantiationsniff (and some others).WordPress.DB.DirectDatabaseQuerycould previously get confused when it encountered comments in unexpected places.WordPress.DB.DirectDatabaseQuerynow respects that function (method) names in PHP are case-insensitive.WordPress.DB.DirectDatabaseQuerynow only looks at the current statement to find a method call to the$wpdbobject.WordPress.DB.DirectDatabaseQueryno longer warns aboutTRUNCATEqueries as those cannot be cached and need a direct database query.WordPress.DB.PreparedSQLcould previously get confused when it encountered comments in unexpected places.WordPress.DB.PreparedSQLnow respects that function names in PHP are case-insensitive.WordPress.DB.PreparedSQLimproved recognition of interpolated variables and expressions in the$textargument. This fixes both some false negatives as well as some false positives.WordPress.DB.PreparedSQLstricter recognition of the$wpdbvariable in double quoted query strings.WordPress.DB.PreparedSQLfalse positive for floating point numbers concatenated into an SQL query.WordPress.DB.PreparedSQLPlaceholderscould previously get confused when it encountered comments in unexpected places.WordPress.DB.PreparedSQLPlaceholdersnow respects that function names in PHP are case-insensitive.WordPress.DB.PreparedSQLPlaceholdersstricter recognition of the$wpdbvariable in double quotes query strings.WordPress.DB.PreparedSQLPlaceholdersfalse positive when a fully qualified function call is encountered in animplode( ', ', array_fill(...))pattern.WordPress.Files.FileNameno longer presumes a three character file extension.WordPress.NamingConventions.PrefixAllGlobalscould previously get confused when it encountered comments in unexpected places in function calls which were being examined.WordPress.NamingConventions.PrefixAllGlobalsnow respects that function names in PHP are case-insensitive when checking whether a function declaration is polyfilling a PHP native function.WordPress.NamingConventions.PrefixAllGlobalsimproved false positive prevention for variable assignments via keyed lists.WordPress.NamingConventions.PrefixAllGlobalsnow only looks at the current statement when determining which variables were imported via aglobalstatement. This prevents both false positives as well as false negatives.WordPress.NamingConventions.PrefixAllGlobalsno longer gets confused overglobalstatements in nested clsure/function declarations.WordPress.NamingConventions.ValidFunctionNamenow also checks the names of (global) functions when the declaration is nested within an OO method.WordPress.NamingConventions.ValidFunctionNameno longer throws false positives for triple underscore methods.WordPress.NamingConventions.ValidFunctionNamethe suggested replacement names in the error message no longer remove underscores from a name in case of leading or trailing underscores, or multiple underscores in the middle of a name.WordPress.NamingConventions.ValidFunctionNamethe determination whether a name is insnake_caseis now more accurate and has improved handling of non-ascii characters.WordPress.NamingConventions.ValidFunctionNamenow correctly recognizes a PHP4-style constructor when the class and the constructor method name contains non-ascii characters.WordPress.NamingConventions.ValidHookNameno longer throws false positives when the hook name is generated via a function call and that function is passed string literals as parameters.WordPress.NamingConventions.ValidHookNamenow ignores parameters in a variable function call (like a call to a closure).WordPress.NamingConventions.ValidPostTypeSlugno longer throws false positives for interpolated text strings with complex embedded variables/expressions.WordPress.NamingConventions.ValidVariableNamethe suggested replacement names in the error message will no longer remove underscores from a name in case of leading or trailing underscores, or multiple underscores in the middle of a name.WordPress.NamingConventions.ValidVariableNamethe determination whether a name is insnake_caseis now more accurate and has improved handling of non-ascii characters.WordPress.NamingConventions.ValidVariableNamenow examines all variables and variables in expressions in a text string containing interpolation.WordPress.NamingConventions.ValidVariableNamenow has improved recognition of variables in complex embedded variables/expressions in interpolated text strings.WordPress.PHP.IniSetno longer gets confused over comments in the code when determining whether the ini value is an allowed one.WordPress.PHP.NoSilencedErrorsno longer throws an error when error silencing is encountered for function calls to the PHP nativelibxml_disable_entity_loader()andimagecreatefromwebp()methods.WordPress.PHP.StrictInArrayno longer gets confused over comments in the code when determining whether the$strictparameter is used.WordPress.Security.EscapeOutputno longer throws a false positive on function calls where the parameters need escaping, when no parameters are being passed.WordPress.Security.EscapeOutputno longer throws a false positive when a fully qualified function call to the\basename()function is encountered within a call to_deprecated_file().WordPress.Security.EscapeOutputcould previously get confused when it encountered comments in the$fileparameter for_deprecated_file().WordPress.Security.EscapeOutputnow ignores significantly more operators which should yield more accurate results.WordPress.Security.EscapeOutputnow respects that function names in PHP are case-insensitive when checking whether a printing function is being used.WordPress.Security.EscapeOutputno longer throws anInternal.Exceptionwhen it encounters a constant or property mirroring the name of one of the printing functions being targeted, nor will it throw false positives for those.WordPress.Security.EscapeOutputno longer incorrectly handles method calls or calls to namespaced functions mirroring the name of one of the printing functions being targeted.WordPress.Security.EscapeOutputnow ignoresexit/diestatements without a status being passed, preventing false positives on code after the statement.WordPress.Security.EscapeOutputnow has improved recognition thatprintcan also be used as an expression, not only as a statement.WordPress.Security.EscapeOutputnow has much, much, much more accurate handling of code involving ternary expressions and should now correctly ignore the ternary condition in all long ternaries being examined.WordPress.Security.EscapeOutputno longer disregards the ternary condition in a short ternary.WordPress.Security.EscapeOutputno longer skips over a constant or property mirroring the name of one of the (auto-)escaping/formatting functions being targeted.WordPress.Security.EscapeOutputno longer throws false positives for*::class, which will always evaluate to a plain string.WordPress.Security.EscapeOutputno longer throws false positives on output generating keywords encountered in an inline expression.WordPress.Security.EscapeOutputno longer throws false positives on parameters passed to_e()or_ex(), which won't be used in the output.WordPress.Security.EscapeOutputno longer throws false positives on heredocs not using interpolation.WordPress.Security.NonceVerificationnow respects that function names in PHP are case-insensitive when checking whether an array comparison function is being used.WordPress.Security.NonceVerificationnow also checks for nonce verification when the$_FILESsuperglobal is being used.WordPress.Security.NonceVerificationnow ignores properties named after superglobals.WordPress.Security.NonceVerificationnow ignores list assignments to superglobals.WordPress.Security.NonceVerificationnow ignores superglobals being unset.WordPress.Security.ValidatedSanitizedInputnow respects that function names in PHP are case-insensitive when checking whether an array comparison function is being used.WordPress.Security.ValidatedSanitizedInputnow respects that function names in PHP are case-insensitive when checking whether a variable is being validated using[array_]key_exists().WordPress.Security.ValidatedSanitizedInputimproved recognition of interpolated variables and expression in the text strings. This fixes some false negatives.WordPress.Security.ValidatedSanitizedInputno longer incorrectly regards anunset()as variable validation.WordPress.Security.ValidatedSanitizedInputno longer incorrectly regards validation in a nested scope as validation which applies to the superglobal being examined.WordPress.WP.AlternativeFunctionscould previously get confused when it encountered comments in unexpected places.WordPress.WP.AlternativeFunctionsnow correctly takes theminimum_wp_versioninto account when determining whether a call toparse_url()could switch over to usingwp_parse_url().WordPress.WP.CapitalPDangitnow skips (keyed) list assignments to prevent false positives.WordPress.WP.CapitalPDangitnow always skips all array keys, not just plain text array keys.WordPress.WP.CronIntervalno longer throws aChangeDetectedwarning for interval calculations wrapped in parentheses, but for which the value for the interval is otherwise known.WordPress.WP.CronIntervalno longer throws aChangeDetectedwarning for interval calculations using fully qualified WP native time constants, but for which the value for the interval is otherwise known.WordPress.WP.DeprecatedParametersno longer throws a false positive for function calls tocomments_number()using the fourth parameter (which was deprecated, but has been repurposed since WP 5.4).WordPress.WP.DeprecatedParametersnow looks for the correct parameter in calls to theunregister_setting()function.WordPress.WP.DeprecatedParametersnow lists the correct WP version for the deprecation of the third parameter in function calls toget_user_option().WordPress.WP.DiscouragedConstantscould previously get confused when it encountered comments in unexpected places.WordPress.WP.EnqueuedResourcesnow recognizes enqueuing in a multi-line text string correctly.WordPress.WP.EnqueuedResourceParameterscould previously get confused when it encountered comments in unexpected places.WordPress.WP.GlobalVariablesOverrideimproved false positive prevention for variable assignments via keyed lists.WordPress.WP.GlobalVariablesOverridenow only looks at the current statement when determining which variables were imported via aglobalstatement. This prevents both false positives as well as false negatives.WordPress.WP.I18nimproved recognition of interpolated variables and expression in the$textargument. This fixes some false negatives.WordPress.WP.I18nno longer potentially creates parse errors when auto-fixing anUnorderedPlaceholders*error involving a multi-line text string.WordPress.WP.I18nno longer throws false positives for compound parameters starting with a text string, which were previously checked as if the parameter only consisted of a text string.WordPress.WP.PostsPerPagenow determines the end of statement with more precision and will no longer throw a false positive for function calls on PHP 8.0+.
2.3.0 - 2020-05-14
- The
WordPress.WP.I18nsniff contains a new check for translatable text strings which are wrapped in HTML tags, like<h1>Translate me</h1>. Those tags should be moved out of the translatable string. Note: Translatable strings wrapped in<a href..>tags where the URL is intended to be localized will not trigger this check.
- The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to5.1. - The
WordPress.WP.DeprecatedFunctionssniff will now detect functions deprecated in WP 5.4. - Improved grammar of an error message in the
WordPress.WP.DiscouragedFunctionssniff. - CI: The codebase is now - preliminary - being tested against the PHPCS 4.x development branch.
- All function call detection sniffs: fixed a bug where constants with the same name as one of the targeted functions could inadvertently be recognized as if they were a called function.
WordPress.DB.PreparedSQL: fixed a bug where the sniff would trigger on the namespace separator character\\.WordPress.Security.EscapeOutput: fixed a bug with the variable replacement in one of the error messages.
2.2.1 - 2020-02-04
- Metrics to the
WordPress.Arrays.CommaAfterArrayItemsniff. These can be displayed using--report=info. - The
sanitize_hex_color()and thesanitize_hex_color_no_hash()functions to theescapingFunctionslist used by theWordPress.Security.EscapeOutputsniff.
- The recommended version of the suggested Composer PHPCS plugin is now
^0.6.
WordPress.PHP.NoSilencedErrors: depending on the custom properties set, the metrics would be different.WordPress.WhiteSpace.ControlStructureSpacing: fixed undefined index notice for closures withuse.WordPress.WP.GlobalVariablesOverride: fixed undefined offset notice when thetreat_files_as_scopedproperty would be set totrue.WordPress.WP.I18n: fixed a Trying to access array offset on value of type null error when the sniff was run on PHP 7.4 and would encounter a translation function expecting singular and plural texts for which one of these arguments was missing.
2.2.0 - 2019-11-11
Note: The repository has moved. The new URL is https://github.com/WordPress/WordPress-Coding-Standards.
The move does not affect the package name for Packagist. This remains the same: wp-coding-standards/wpcs.
- New
WordPress.DateTime.CurrentTimeTimestampsniff to theWordPress-Coreruleset, which checks against the use of the WP nativecurrent_time()function to retrieve a timestamp as this won't be a real timestamp. Includes an auto-fixer. - New
WordPress.DateTime.RestrictedFunctionssniff to theWordPress-Coreruleset, which checks for the use of certain date/time related functions. Initially this sniff forbids the use of the PHP nativedate_default_timezone_set()anddate()functions. - New
WordPress.PHP.DisallowShortTernarysniff to theWordPress-Coreruleset, which, as the name implies, disallows the use of short ternaries. - New
WordPress.CodeAnalysis.EscapedNotTranslatedsniff to theWordPress-Extraruleset which will warn when a text string is escaped for output, but not being translated, while the arguments passed to the function call give the impression that translation is intended. - New
WordPress.NamingConventions.ValidPostTypeSlugsniff to theWordPress-Extraruleset which will examine calls toregister_post_type()and throw errors when an invalid post type slug is used. Generic.Arrays.DisallowShortArraySyntaxto theWordPress-Coreruleset.WordPress.NamingConventions.PrefixAllGlobals: thePHPprefix has been added to the prefix blacklist as it is reserved by PHP itself.- The
wp_sanitize_redirect()function to thesanitizingFunctionslist used by theWordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInputandWordPress.Security.EscapeOutputsniffs. - The
sanitize_key()and thehighlight_string()functions to theescapingFunctionslist used by theWordPress.Security.EscapeOutputsniff. - The
RECOVERY_MODE_COOKIEconstant to the list of WP Core constants which may be defined by plugins and themes and therefore don't need to be prefixed (WordPress.NamingConventions.PrefixAllGlobals). $content_width,$plugin,$mu_pluginand$network_pluginto the list of WP globals which is used by both theWordPress.Variables.GlobalVariablesand theWordPress.NamingConventions.PrefixAllGlobalssniffs.Sniff::is_short_list()utility method to determine whether a short array open/close token actually represents a PHP 7.1+ short list.Sniff::find_list_open_close()utility method to find the opener and closer forlist()constructs, including short lists.Sniff::get_list_variables()utility method which will retrieve an array with the token pointers to the variables which are being assigned to in alist()construct. Includes support for short lists.Sniff::is_function_deprecated()static utility method to determine whether a declared function has been marked as deprecated in the function DocBlock.- End-user documentation to the following existing sniffs:
WordPress.Arrays.ArrayIndentation,WordPress.Arrays.ArrayKeySpacingRestrictions,WordPress.Arrays.MultipleStatementAlignment,WordPress.Classes.ClassInstantiation,WordPress.NamingConventions.ValidHookName,WordPress.PHP.IniSet,WordPress.Security.SafeRedirect,WordPress.WhiteSpace.CastStructureSpacing,WordPress.WhiteSpace.DisallowInlineTabs,WordPress.WhiteSpace.PrecisionAlignment,WordPress.WP.CronInterval,WordPress.WP.DeprecatedClasses,WordPress.WP.DeprecatedFunctions,WordPress.WP.DeprecatedParameters,WordPress.WP.DeprecatedParameterValues,WordPress.WP.EnqueuedResources,WordPress.WP.PostsPerPage. This documentation can be exposed via thePHP_CodeSniffer--generator=...command-line argument.
- The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to5.0. - The
WordPress.Arrays.ArrayKeySpacingRestrictionssniff has two new error codes:TooMuchSpaceBeforeKeyandTooMuchSpaceAfterKey. Both auto-fixable. The sniff will now check that there is exactly one space on the inside of the square brackets around the array key for non-string, non-numeric array keys. Previously, it only checked that there was whitespace, not how much whitespace. WordPress.Arrays.ArrayKeySpacingRestrictions: the fixers have been made more efficient and less fixer-conflict prone.WordPress.NamingConventions.PrefixAllGlobals: plugin/theme prefixes should be at least three characters long. A newShortPrefixPassederror has been added for when the prefix passed does not comply with this rule.WordPress.WhiteSpace.CastStructureSpacingnow allows for no whitespace before a cast when the cast is preceded by the spread...operator. This pre-empts a fixer conflict for when the spacing around the spread operator will start to get checked.- The
WordPress.WP.DeprecatedClassessniff will now detect classes deprecated in WP 4.9 and WP 5.3. - The
WordPress.WP.DeprecatedFunctionssniff will now detect functions deprecated in WP 5.3. WordPress.NamingConventions.ValidHookNamenow has "cleaner" error messages and higher precision for the line on which an error is thrown.WordPress.Security.EscapeOutput: if an error refers to array access via a variable, the array index key will now be included in the error message.- The processing of the
WordPressruleset byPHP_CodeSnifferwill now be faster. - Various minor code tweaks and clean up.
- Various minor documentation fixes.
- Documentation: updated the repo URL in all relevant places.
- The
WordPress.WP.TimezoneChangesniff. Use theWordPress.DateTime.RestrictedFunctionsinstead. The deprecated sniff will be removed in WPCS 3.0.0.
- All sniffs in the
WordPress.Arrayscategory will no longer treat short lists as if they were a short array. - The
WordPress.NamingConventions.ValidFunctionNameand theWordPress.NamingConventions.PrefixAllGlobalssniff will now ignore functions marked as@deprecated. - Both the
WordPress.NamingConventions.PrefixAllGlobalssniff as well as theWordPress.WP.GlobalVariablesOverridesniff have been updated to recognize variables being declared via (long/short)list()constructs and handle them correctly. - Both the
WordPress.NamingConventions.PrefixAllGlobalssniff as well as theWordPress.WP.GlobalVariablesOverridesniff will now take a limited list of WP global variables which are intended to be overwritten by plugins/themes into account. Initially this list contains the$content_widthand the$wp_cockneyreplacevariables. WordPress.NamingConventions.ValidHookName: will no longer examine a string array access index key as if it were a part of the hook name.WordPress.Security.EscapeOutput: will no longer trigger on the typicalbasename( __FILE__ )pattern if found as the first parameter passed to a call to_deprecated_file().WordPress.WP.CapitalPDangit: now allows for the.testTLD in URLs.- WPCS is now fully compatible with PHP 7.4.
Note:
PHP_CodeSnifferitself is only compatible with PHP 7.4 from PHPCS 3.5.0 onwards.
2.1.1 - 2019-05-21
- The
WordPress.WP.CapitalPDangitwill now ignore misspelled instances ofWordPresswithin constant declarations. This covers both constants declared usingdefined()as well as constants declared using theconstkeyword. - The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to4.9.
paginate_comments_links()from the list of auto-escaped functionsSniff::$autoEscapedFunctions. This affects theWordPress.Security.EscapeOutputsniff.
- The
$current_blogand$tag_IDvariables have been added to the list of WordPress global variables. This fixes some false positives from theWordPress.NamingConventions.PrefixAllGlobalsand theWordPress.WP.GlobalVariablesOverridesniffs. - The generic
TestCaseclass name has been added to the$test_class_whitelist. This fixes some false positives from theWordPress.NamingConventions.FileName,WordPress.NamingConventions.PrefixAllGlobalsand theWordPress.WP.GlobalVariablesOverridesniffs. - The
WordPress.NamingConventions.ValidVariableNamesniff will now correctly recognize$tag_IDas a WordPress native, mixed-case variable. - The
WordPress.Security.NonceVerificationsniff will now correctly recognize nonce verification within a nested closure or anonymous class.
2.1.0 - 2019-04-08
- New
WordPress.PHP.IniSetsniff to theWordPress-Extraruleset. This sniff will detect calls toini_set()andini_alter()and warn against their use as changing configuration values at runtime leads to an unpredictable runtime environment, which can result in conflicts between core/plugins/themes.- The sniff will not throw notices about a very limited set of "safe" ini directives.
- For a number of ini directives for which there are alternative, non-conflicting ways to achieve the same available, the sniff will throw an
errorand advise using the alternative.
doubleval(),count()andsizeof()toSniff::$unslashingSanitizingFunctionsproperty. Whilecount()and its aliassizeof(), don't actually unslash or sanitize, the output of these functions is safe to use without unslashing or sanitizing. This affects theWordPress.Security.ValidatedSanitizedInputand theWordPress.Security.NonceVerificationsniffs.- The new WP 5.1
WP_UnitTestCase_Baseclass to theSniff::$test_class_whitelistproperty. - New
Sniff::get_array_access_keys()utility method to retrieve all array keys for a variable using multi-level array access. - New
Sniff::is_class_object_call(),Sniff::is_token_namespaced()utility methods. These should help make the checking of whether or not a function call is a global function, method call or a namespaced function call more consistent. This also implements allowing for the namespace keyword being used as an operator. - New
Sniff::is_in_function_call()utility method to facilitate checking whether a token is (part of) a parameter passed to a specific (set of) function(s). - New
Sniff::is_in_type_test()utility method to determine if a variable is being type tested, along with aSniff::$typeTestFunctionsproperty containing the names of the functions this applies to. - New
Sniff::is_in_array_comparison()utility method to determine if a variable is (part of) a parameter in an array-value comparison, along with aSniff::$arrayCompareFunctionsproperty containing the names of the relevant functions. - New
Sniff::$arrayWalkingFunctionsproperty containing the names of array functions which apply a callback to the array, but don't change the array by reference. - New
Sniff::$unslashingFunctionsproperty containing the names of functions which unslash data passed to them and return the unslashed result.
- Moved the
WordPress.PHP.StrictComparisons,WordPress.PHP.StrictInArrayand theWordPress.CodeAnalysis.AssignmentInConditionsniff from theWordPress-Extrato theWordPress-Coreruleset. - The
Squiz.Commenting.InlineComment.SpacingAftererror is no longer included in theWordPress-Docsruleset. - The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to4.8. - The
WordPress.WP.DeprecatedFunctionssniff will now detect functions deprecated in WP 5.1. - The
WordPress.Security.NonceVerificationsniff now allows for variable type testing, comparisons, unslashing and sanitization before the nonce check. A nonce check within the same scope, however, is still required. - The
WordPress.Security.ValidatedSanitizedInputsniff now allows for using a superglobal in an array-value comparison without sanitization, same as when the superglobal is used in a scalar value comparison. WordPress.NamingConventions.PrefixAllGlobals: some of the error messages have been made more explicit.- The error messages for the
WordPress.Security.ValidatedSanitizedInputsniff will now contain information on the index keys accessed. - The error message for the
WordPress.Security.ValidatedSanitizedInput.InputNotValidatedhas been reworded to make it more obvious what the actual issue being reported is. - The error message for the
WordPress.Security.ValidatedSanitizedInput.MissingUnslashhas been reworded. - The
Sniff::is_comparison()method now has a new$include_coalesceparameter to allow for toggling whether the null coalesce operator should be seen as a comparison operator. Defaults totrue. - All sniffs are now also being tested against PHP 7.4 (unstable) for consistent sniff results.
- The recommended version of the suggested Composer PHPCS plugin is now
^0.5.0. - Various minor code tweaks and clean up.
ini_setandini_alterfrom the list of functions detected by theWordPress.PHP.DiscouragedFunctionssniff. These are now covered via the newWordPress.PHP.IniSetsniff.in_array()andarray_key_exists()from the list ofSniff::$sanitizingFunctions. These are now handled differently.
-
The
WordPress.NamingConventions.PrefixAllGlobalssniff would underreport when global functions would be autoloaded via a Composer autoloadfilesconfiguration. -
The
WordPress.Security.EscapeOutputsniff will now recognizemap_deep()for escaping the values in an array via a callback to an output escaping function. This should prevent false positives. -
The
WordPress.Security.NonceVerificationsniff will no longer inadvertently allow for a variable to be sanitized without a nonce check within the same scope. -
The
WordPress.Security.ValidatedSanitizedInputsniff will no longer throw errors when a variable is only being type tested. -
The
WordPress.Security.ValidatedSanitizedInputsniff will now correctly recognize the null coalesce (PHP 7.0) and null coalesce equal (PHP 7.4) operators and will now throw errors for missing unslashing and sanitization where relevant. -
The
WordPress.WP.AlternativeFunctionssniff will no longer recommend using the WP_FileSystem when PHP native input streams, likephp://input, or the PHP input stream constants are being read or written to. -
The
WordPress.WP.AlternativeFunctionssniff will no longer report on usage of thecurl_version()function. -
The
WordPress.WP.CronIntervalsniff now has improved function recognition which should lower the chance of false positives. -
The
WordPress.WP.EnqueuedResourcessniff will no longer throw false positives for inline jQuery code trying to access a stylesheet link tag. -
Various bugfixes for the
Sniff::has_nonce_check()method:- The method will no longer incorrectly identify methods/namespaced functions mirroring the name of WP native nonce verification functions as if they were the global functions. This will prevent some false negatives.
- The method will now skip over nested closed scopes, such as closures and anonymous classes. This should prevent some false negatives for nonce verification being done while not in the correct scope.
These fixes affect the
WordPress.Security.NonceVerificationsniff. -
The
Sniff::is_in_isset_or_empty()method now also checks for usage ofarray_key_exist()andkey_exists()and will regard these as correct ways to validate a variable. This should prevent false positives for theWordPress.Security.ValidatedSanitizedInputand theWordPress.Security.NonceVerificationsniffs. -
Various bugfixes for the
Sniff::is_sanitized()method:- The method presumed the WordPress coding style regarding code layout, which could lead to false positives.
- The method will no longer incorrectly identify methods/namespaced functions mirroring the name of WP/PHP native unslashing/sanitization functions as if they were the global functions. This will prevent some false negatives.
- The method will now recognize
map_deep()for sanitizing an array via a callback to a sanitization function. This should prevent false positives. - The method will now recognize
stripslashes_deep()andstripslashes_from_strings_only()as valid unslashing functions. This should prevent false positives. All these fixes affect both theWordPress.Security.ValidatedSanitizedInputand theWordPress.Security.NonceVerificationsniff.
-
Various bugfixes for the
Sniff::is_validated()method:- The method did not verify correctly whether a variable being validated was the same variable as later used which could lead to false negatives.
- The method did not verify correctly whether a variable being validated had the same array index keys as the variable as later used which could lead to both false negatives as well as false positives.
- The method now also checks for usage of
array_key_exist()andkey_exists()and will regard these as correct ways to validate a variable. This should prevent some false positives. - The methods will now recognize the null coalesce and the null coalesce equal operators as ways to validate a variable. This prevents some false positives.
The results from the
WordPress.Security.ValidatedSanitizedInputsniff should be more accurate because of these fixes.
-
A potential "Undefined index" notice from the
Sniff::is_assignment()method.
2.0.0 - 2019-01-16
WordPressCS 2.0.0 contains breaking changes, both for people using custom rulesets as well as for sniff developers who maintain a custom PHPCS standard based on WordPressCS.
Support for PHP_CodeSniffer 2.x has been dropped, the new minimum PHP_CodeSniffer version is 3.3.1.
Also, all previously deprecated sniffs, properties and methods have been removed.
Please read the complete changelog carefully before you upgrade.
If you are a maintainer of an external standard based on WordPressCS and any of your custom sniffs are based on or extend WPCS sniffs, please read the Developers Upgrade Guide to WordPressCS 2.0.0.
WordPress-Extra: Reverted back to including theSquiz.WhiteSpace.LanguageConstructSpacingsniff instead of the newGeneric.WhiteSpace.LanguageConstructSpacingsniff as the new sniff is not (yet) available when the PEAR install of PHPCS is used.
For a full list of changes from the 1.2.1 version, please review the following changelog:
2.0.0-RC1 - 2018-12-31
This is the first release candidate for WordPressCS 2.0.0. WordPressCS 2.0.0 contains breaking changes, both for people using custom rulesets as well as for sniff developers who maintain a custom PHPCS standard based on WordPressCS.
Support for PHP_CodeSniffer 2.x has been dropped, the new minimum PHP_CodeSniffer version is 3.3.1.
Also, all previously deprecated sniffs, properties and methods have been removed.
Please read the complete changelog carefully before you upgrade.
If you are a maintainer of an external standard based on WordPressCS and any of your custom sniffs are based on or extend WPCS sniffs, please read the Developers Upgrade Guide to WordPressCS 2.0.0.
Generic.PHP.DiscourageGoto,Generic.PHP.LowerCaseType,Generic.WhiteSpace.ArbitraryParenthesesSpacingandPSR12.Keywords.ShortFormTypeKeywordsto theWordPress-Coreruleset.- Checking the spacing around the
instanceofoperator to theWordPress.WhiteSpace.OperatorSpacingsniff.
- The minimum required
PHP_CodeSnifferversion to 3.3.1 (was 2.9.0). - The namespace used by WordPressCS has been changed from
WordPresstoWordPressCS\WordPress. This was not possible whilePHP_CodeSniffer2.x was still supported, but WordPressCS, as a good Open Source citizen, does not want to occupy theWordPressnamespace and is releasing its use of it now this is viable. - The
WordPress.DB.PreparedSQLsniff used the same error code for two different errors. TheNotPreparederror code remains, however an additionalInterpolatedNotPreparederror code has been added for the second error. If you are referencing the old error code in a ruleset XML file or in inline annotations, you may need to update it. - The
WordPress.NamingConventions.PrefixAllGlobalssniff used the same error code for some errors as well as warnings. TheNonPrefixedConstantFounderror code remains for the related error, but the warning will now use the newVariableConstantNameFounderror code. TheNonPrefixedHooknameFounderror code remains for the related error, but the warning will now use the newDynamicHooknameFounderror code. If you are referencing the old error codes in a ruleset XML file or in inline annotations, you may need to update these to use the new codes instead. WordPress.NamingConventions.ValidVariableName: the error messages and error codes used by this sniff have been changed for improved usability and consistency.- The error messages will now show a suggestion for a valid alternative name for the variable.
- The
NotSnakeCaseMemberVarerror code has been renamed toUsedPropertyNotSnakeCase. - The
NotSnakeCaseerror code has been renamed toVariableNotSnakeCase. - The
MemberNotSnakeCaseerror code has been renamed toPropertyNotSnakeCase. - The
StringNotSnakeCaseerror code has been renamed toInterpolatedVariableNotSnakeCase. If you are referencing the old error codes in a ruleset XML file or in inline annotations, you may need to update these to use the new codes instead.
- The
WordPress.Security.NonceVerificationsniff used the same error code for both an error as well as a warning. The old error codeNoNonceVerificationis no longer used. Theerrornow uses theMissingerror code, while thewarningnow uses theRecommendederror code. If you are referencing the old error code in a ruleset XML file or in inline annotations, please update these to use the new codes instead. - The
WordPress.WP.DiscouragedConstantssniff used to have two error codesUsageFoundandDeclarationFound. These error codes will now be prefixed by the name of the constant found to allow for more fine-grained excluding/ignoring of warnings generated by this sniff. If you are referencing the old error codes in a ruleset XML file or in inline annotations, you may need to update these to use the new codes instead. - The
WordPress.WP.GlobalVariablesOverride.OverrideProhibitederror code has been replaced by theWordPress.WP.GlobalVariablesOverride.Prohibitederror code. If you are referencing the old error code in a ruleset XML file or in inline annotations, you may need to update it. WordPress-Extra: Replaced the inclusion of theGeneric.Files.OneClassPerFile,Generic.Files.OneInterfacePerFileand theGeneric.Files.OneTraitPerFilesniffs with the newGeneric.Files.OneObjectStructurePerFilesniff.WordPress-Extra: Replaced the inclusion of theSquiz.WhiteSpace.LanguageConstructSpacingsniff with the newGeneric.WhiteSpace.LanguageConstructSpacingsniff.WordPress-Extra: Replaced the inclusion of theSquiz.Scope.MemberVarScopesniff with the more comprehensivePSR2.Classes.PropertyDeclarationsniff.WordPress.NamingConventions.ValidFunctionName: Added a unit test confirming support for interfaces extending multiple interfaces.WordPress.NamingConventions.ValidVariableName: Added unit tests confirming support for multi-variable/property declarations.- The
get_name_suggestion()method has been moved from theWordPress.NamingConventions.ValidFunctionNamesniff to the baseSniffclass, renamed toget_snake_case_name_suggestion()and made static. - The rulesets are now validated against the
PHP_CodeSnifferXSD schema. - Updated the custom ruleset example to use the recommended ruleset syntax for
PHP_CodeSniffer3.3.1+, including using the new array property format which is now supported. - Dev: The command to run the unit tests has changed. Please see the updated instructions in the CONTRIBUTING.md file.
The
bin/pre-commitexample git hook has been updated to match. Additionally arun-testsscript has been added to thecomposer.jsonfile for your convenience. To facilitate this, PHPUnit has been added torequire-dev, even though it is strictly speaking a dependency of PHPCS, not of WPCS. - Dev: The Composer PHPCS plugin has been added to
require-dev. - Various code tweaks and clean up.
- User facing documentation, including the wiki, as well as inline documentation has been updated for all the changes contained in WordPressCS 2.0 and other recommended best practices for
PHP_CodeSniffer3.3.1+.
- The use of the WordPressCS native whitelist comments, which were introduced in WPCS 0.4.0, have been deprecated and support will be removed in WPCS 3.0.0.
The WordPressCS native whitelist comments will continue to work for now, but a deprecation warning will be thrown when they are encountered.
You are encouraged to upgrade our whitelist comment to use the PHPCS native selective ignore annotations as introduced in
PHP_CodeSniffer3.2.0, as soon as possible.
- Support for PHP 5.3. PHP 5.4 is the minimum requirement for
PHP_CodeSniffer3.x. Includes removing any and all workarounds which were in place to still support PHP 5.3. - Support for
PHP_CodeSniffer< 3.3.1. Includes removing any and all workarounds which were in place for supporting olderPHP_CodeSnifferversions. - The
WordPress-VIPstandard which was deprecated since WordPressCS 1.0.0. For checking a theme/plugin for hosting on the WordPress.com VIP platform, please use the Automattic VIP coding standards instead. - Support for array properties set in a custom ruleset without the
type="array"attribute. Support for this was deprecated in WPCS 1.0.0. If in doubt about how properties should be set in your custom ruleset, please refer to the Customizable sniff properties wiki page which contains XML code examples for setting each and every WPCS native sniff property. As the minimumPHP_CodeSnifferversion is now 3.3.1, you can now also use the new format for setting array properties, so this would be a great moment to review and update your custom ruleset. Note: the ability to set select properties from the command-line as comma-delimited strings is not affected by this change. - The following sniffs have been removed outright without deprecation.
If you are referencing these sniffs in a ruleset XML file or in inline annotations, please update these to reference the replacement sniffs instead.
WordPress.Functions.FunctionCallSignatureNoParams- superseded by a bug fix in the upstreamPEAR.Functions.FunctionCallSignaturesniff.WordPress.PHP.DiscourageGoto- replaced by the same sniff which is now available upstream:Generic.PHP.DiscourageGoto.WordPress.WhiteSpace.SemicolonSpacing- superseded by a bug fix in the upstreamSquiz.WhiteSpace.SemicolonSpacingsniff.WordPress.WhiteSpace.ArbitraryParenthesesSpacing- replaced by the same sniff which is now available upstream:Generic.WhiteSpace.ArbitraryParenthesesSpacing.
- The following "base" sniffs which were previously already deprecated and turned into abstract base classes, have been removed:
WordPress.Arrays.ArrayAssignmentRestrictions- use theAbstractArrayAssignmentRestrictionsSniffclass instead.WordPress.Functions.FunctionRestrictions- use theAbstractFunctionRestrictionsSniffclass instead.WordPress.Variables.VariableRestrictionswithout replacement.
- The following sniffs which were previously deprecated, have been removed:
WordPress.Arrays.ArrayDeclaration- use the other sniffs in theWordPress.Arrayscategory instead.WordPress.CSRF.NonceVerification- useWordPress.Security.NonceVerificationinstead.WordPress.Functions.DontExtract- useWordPress.PHP.DontExtractinstead.WordPress.Variables.GlobalVariables- useWordPress.WP.GlobalVariablesOverrideinstead.WordPress.VIP.CronInterval- useWordPress.WP.CronIntervalinstead.WordPress.VIP.DirectDatabaseQuery- useWordPress.DB.DirectDatabaseQueryinstead.WordPress.VIP.PluginMenuSlug- useWordPress.Security.PluginMenuSluginstead.WordPress.VIP.SlowDBQuery- useWordPress.DB.SlowDBQueryinstead.WordPress.VIP.TimezoneChange- useWordPress.WP.TimezoneChangeinstead.WordPress.VIP.ValidatedSanitizedInput- useWordPress.Security.ValidatedSanitizedInputinstead.WordPress.WP.PreparedSQL- useWordPress.DB.PreparedSQLinstead.WordPress.XSS.EscapeOutput- useWordPress.Security.EscapeOutputinstead.WordPress.PHP.DiscouragedFunctionswithout direct replacement. The checks previously contained in this sniff were moved to separate sniffs in WPCS 0.11.0.WordPress.Variables.VariableRestrictionswithout replacement.WordPress.VIP.AdminBarRemovalwithout replacement.WordPress.VIP.FileSystemWritesDisallowwithout replacement.WordPress.VIP.OrderByRandwithout replacement.WordPress.VIP.PostsPerPagewithout replacement. Part of the previous functionality was split off in WPCS 1.0.0 to theWordPress.WP.PostsPerPagesniff.WordPress.VIP.RestrictedFunctionswithout replacement.WordPress.VIP.RestrictedVariableswithout replacement.WordPress.VIP.SessionFunctionsUsagewithout replacement.WordPress.VIP.SessionVariableUsagewithout replacement.WordPress.VIP.SuperGlobalInputUsagewithout replacement.
- The
WordPress.DB.SlowDBQuery.DeprecatedWhitelistFlagFounderror code which is superseded by the blanket deprecation warning for using the now deprecated WPCS native whitelist comments. - The
WordPress.PHP.TypeCasts.NonLowercaseFounderror code which has been replaced by the upstreamGeneric.PHP.LowerCaseTypesniff. - The
WordPress.PHP.TypeCasts.LongBoolFoundandWordPress.PHP.TypeCasts.LongIntFounderror codes which has been replaced by the new upstreamPSR12.Keywords.ShortFormTypeKeywordssniff. - The
WordPress.Security.EscapeOutput.OutputNotEscapedShortEchoerror code which was only ever used if WPCS was run on PHP 5.3 with theshort_open_tagini directive set tooff. - The following sniff categories which were previously deprecated, have been removed, though select categories may be reinstated in the future:
CSRFFunctionsVariablesVIPXSS
WordPress.NamingConventions.ValidVariableName: ThecustomVariableWhitelistproperty, which had been deprecated since WordPressCS 0.11.0. Use thecustomPropertiesWhitelistproperty instead.WordPress.Security.EscapeOutput: ThecustomSanitizingFunctionsproperty, which had been deprecated since WordPressCS 0.5.0. Use thecustomEscapingFunctionsproperty instead.WordPress.Security.NonceVerification: TheerrorForSuperGlobalsandwarnForSuperGlobalsproperties, which had been deprecated since WordPressCS 0.12.0.- The
vip_powered_wpcomfunction from theSniff::$autoEscapedFunctionslist which is used by theWordPress.Security.EscapeOutputsniff. - The
AbstractVariableRestrictionsSniffclass, which was deprecated since WordPressCS 1.0.0. - The
Sniff::has_html_open_tag()utility method, which was deprecated since WordPressCS 1.0.0. - The internal
$php_reserved_varsproperty from theWordPress.NamingConventions.ValidVariableNamesniff in favor of using a PHPCS native property which is now available. - The class aliases and WPCS native autoloader used for PHPCS cross-version support.
- The unit test framework workarounds for PHPCS cross-version unit testing.
- Support for the
@codingStandardsChangeSettingannotation, which is generally only used in unit tests. - The old generic GitHub issue template which was replaced by more specific issue templates in WPCS 1.2.0.
- Support for PHP 7.3.
PHP_CodeSniffer< 3.3.1 was not fully compatible with PHP 7.3. Now the minimum required PHPCS has been upped toPHP_CodeSniffer3.3.1, WordPressCS will run on PHP 7.3 without issue. WordPress.Arrays.ArrayDeclarationSpacing: improved fixing of the placement of array items following an array item with a trailing multi-line comment.WordPress.NamingConventions.ValidFunctionName: the sniff will no longer throw false positives nor duplicate errors for methods declared in nested anonymous classes. The error message has also been improved for methods in anonymous classes.WordPress.NamingConventions.ValidFunctionName: the sniff will no longer throw false positives for PHP 4-style class constructors/destructors where the name of the constructor/destructor method did not use the same case as the class name.
1.2.1 - 2018-12-18
Note: This will be the last release supporting PHP_CodeSniffer 2.x.
- The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to4.7. - The
WordPress.NamingConventions.PrefixAllGlobalssniff will now report the error for hook names and constant names declared withdefine()on the line containing the parameter for the hook/constant name. Previously, it would report the error on the line containing the function call. - Various minor housekeeping fixes to inline documentation, rulesets, code.
comment_author_email_link(),comment_author_email(),comment_author_IP(),comment_author_link(),comment_author_rss(),comment_author_url_link(),comment_author_url(),comment_author(),comment_date(),comment_excerpt(),comment_form_title(),comment_form(),comment_id_fields(),comment_ID(),comment_reply_link(),comment_text_rss(),comment_text(),comment_time(),comment_type(),comments_link(),comments_number(),comments_popup_link(),comments_popup_script(),comments_rss_link(),delete_get_calendar_cache(),edit_bookmark_link(),edit_comment_link(),edit_post_link(),edit_tag_link(),get_footer(),get_header(),get_sidebar(),get_the_title(),next_comments_link(),next_image_link(),next_post_link(),next_posts_link(),permalink_anchor(),posts_nav_link(),previous_comments_link(),previous_image_link(),previous_post_link(),previous_posts_link(),sticky_class(),the_attachment_link(),the_author_link(),the_author_meta(),the_author_posts_link(),the_author_posts(),the_category_rss(),the_category(),the_content_rss(),the_content(),the_date_xml(),the_excerpt_rss(),the_excerpt(),the_feed_link(),the_ID(),the_meta(),the_modified_author(),the_modified_date(),the_modified_time(),the_permalink(),the_post_thumbnail(),the_search_query(),the_shortlink(),the_tags(),the_taxonomies(),the_terms(),the_time(),the_title_rss(),the_title(),wp_enqueue_script(),wp_meta(),wp_shortlink_header()andwp_shortlink_wp_head()from the list of auto-escaped functionsSniff::$autoEscapedFunctions. This affects theWordPress.Security.EscapeOutputsniff.
- The
WordPress.WhiteSpace.PrecisionAlignmentsniff would loose the value of a custom setignoreAlignmentTokensproperty when scanning more than one file.
1.2.0 - 2018-11-12
- New
WordPress.PHP.TypeCastssniff to theWordPress-Coreruleset. This new sniff checks that PHP type casts are:- lowercase;
- short form, i.e.
(bool)not(boolean); - normalized, i.e.
(float)not(real). Additionally, the new sniff discourages the use of the(unset)and(binary)type casts.
- New
WordPress.Utils.I18nTextDomainFixersniff which can compehensively replace/addtext-domains in a plugin or theme. Important notes:- This sniff is disabled by default and intended as a utility tool.
- The sniff will fix the text domains in all I18n function calls as well as in a plugin/theme
Text Domain:header. - Passing the following properties will activate the sniff:
old_text_domain: an array with one or more (old) text domains which need to be replaced;new_text_domain: the correct (new) text domain as a string.
- The
WordPress.NamingConventions.PrefixAllGlobalssniff will now also verify that namespace names use a valid prefix.- The sniff allows for underscores and (other) non-word characters in a passed prefix to be converted to namespace separators when used in a namespace name.
In other words, if a prefix of
my_pluginis passed as a value to theprefixesproperty, a namespace name of bothMy\Pluginas well asMy_Plugin\\, will be accepted automatically. - Passing a prefix property value containing namespace separators will now also be allowed and will no longer trigger a warning.
- The sniff allows for underscores and (other) non-word characters in a passed prefix to be converted to namespace separators when used in a namespace name.
In other words, if a prefix of
WordPressto the prefix blacklist for theWordPress.NamingConventions.PrefixAllGlobalssniff. While the prefix cannot beWordPress, a prefix can still start with or containWordPress.- Additional unit tests covering a change in the tokenizer which will be included in the upcoming
PHP_CodeSniffer3.4.0 release. - A variety of issue templates for use on GitHub.
- The
Sniff::valid_direct_scope()method will now return the$stackPtrto the valid scope if a valid direct scope has been detected. Previously, it would returntrue. - Minor hardening and efficiency improvements to the
WordPress.NamingConventions.PrefixAllGlobalssniff. - The inline documentation of the
WordPress-Coreruleset has been updated to be in line again with the handbook. - The inline links to documentation about the VIP requirements have been updated.
- Updated the custom ruleset example to recommend using
PHPCompatibilityWPrather thanPHPCompatibility. - All sniffs are now also being tested against PHP 7.3 for consistent sniff results.
Note: PHP 7.3 is only supported in combination with PHPCS 3.3.1 or higher as
PHP_CodeSnifferitself has an incompatibility in earlier versions. - Minor grammar fixes in text strings and documentation.
- Minor consistency improvement for the unit test case files.
- Minor tweaks to the
composer.jsonfile. - Updated the PHPCompatibility
devdependency.
- The
WordPress.WhiteSpace.CastStructureSpacing.NoSpaceAfterCloseParenthesiserror code as an error for the same issue was already being thrown by an included upstream sniff.
- The
WordPress.CodeAnalysis.EmptyStatementwould throw a false positive for an empty condition in afor()statement. - The
Sniff::is_class_property()method could, in certain circumstances, incorrectly recognize parameters in a method declaration as class properties. It would also, incorrectly, fail to recognize class properties when the object they are declared in, was nested in parentheses. This affected, amongst others, theGlobalVariablesOverridesniff. - The
Sniff::get_declared_namespace_name()method could get confused over whitespace and comments within a namespace name, which could lead to incorrect results (mostly underreporting). This affected, amongst others, theGlobalVariablesOverridesniff. The return value of the method will now no longer contain any whitespace or comments encountered. - The
Sniff::has_whitelist_comment()method would sometimes incorrectly regard// phpcs:setcomments as whitelist comments.
1.1.0 - 2018-09-10
- New
WordPress.PHP.NoSilencedErrorssniff. This sniff replaces theGeneric.PHP.NoSilencedErrorssniff which was previously used and included in theWordPress-Coreruleset. The WordPress specific version of the sniff differs from the PHPCS version in that it:- Allows the error control operator
@if it precedes a function call to a limited list of PHP functions for which no amount of error checking can prevent a PHP warning from being thrown. - Allows for a used-defined list of (additional) function names to be passed to the sniff via the
custom_whitelistproperty in a custom ruleset, for which - if the error control operator is detected in front of a function call to one of the functions in this whitelist - no warnings will be thrown. - Displays a brief snippet of code in the
warningmessage text to show the context in which the error control operator is being used. The length of the snippet (in tokens) can be customized via thecontext_lengthproperty. - Contains a public
use_default_whitelistproperty which can be set from a custom ruleset which regulates whether or not the standard whitelist of PHP functions should be used by the sniff. The user-defined whitelist will always be respected. By default, this property is set totruefor theWordPress-Coreruleset and tofalsefor theWordPress-Extraruleset (which is stricter regarding these kind of best practices).
- Allows the error control operator
- Metrics to the
WordPress.NamingConventions.PrefixAllGlobalssniff to aid people in determining the most commonly used prefix in a legacy project. For an example of how to use this feature, please see the detailed explanation in the pull request.
- The
PEAR.Functions.FunctionCallSignaturesniff, which is part of theWordPress-Coreruleset, used to allow multiple function call parameters per line in multi-line function calls. This will no longer be allowed. As of this release, if a function call is multi-line, each parameter should start on a new line and anerrorwill be thrown if the code being analyzed does not comply with that rule. The sniff behavior for single-line function calls is not affected by this change. - Moved the
WordPress.CodeAnalysis.EmptyStatementsniff from theWordPress-Extrato theWordPress-Coreruleset. - Moved the
Squiz.PHP.CommentedOutCodesniff from theWordPress-Docsto theWordPress-Extraruleset and lowered the threshold for determining whether or not a comment is commented out code from 45% to 40%. - The
WordPress.NamingConventions.PrefixAllGlobalssniff now has improved support for recognizing whether or not (non-prefixed) globals are declared in the context of unit tests. - The
is_foreach_as()method has been moved from theGlobalVariablesOverrideSniffclass to the WordPressSniffbase class. - The
Sniff::is_token_in_test_method()utility method now has improved support for recognizing test methods in anonymous classes. - Minor efficiency improvement to the
Sniff::is_safe_casted()method. - CI: Minor tweaks to the Travis script.
- CI: Improved Composer scripts for use by WPCS developers.
- Dev: Removed IDE specific files from
.gitignore. - Readme: Improved the documentation about the project history and the badge display.
- The
WordPress.Security.ValidatedSanitizedInputsniff will now recognize array keys in superglobals independently of the string quote-style used for the array key. - The
WordPress.WhiteSpace.PrecisionAlignmentsniff will no longer throw false positives for DocBlocks for JavaScript functions within inline HTML. WordPress.WP.DeprecatedClasses: The error codes for this sniff were unstable as they were based on the code being analyzed instead of on fixed values.- Various bugfixes for the
WordPress.WP.GlobalVariablesOverridesniff:- Previously, the sniff only checked variables in the global namespace when a
globalstatement would be encountered. As of now, all variable assignments in the global namespace will be checked. - Nested functions/closures/classes which don't import the global variable will now be skipped over when encountered within another function, preventing false positives.
- Parameters in function declarations will no longer throw false positives.
- The error message for assignments to a subkey of the
$GLOBALSsuperglobal has been improved. - Various efficiency improvements.
- Previously, the sniff only checked variables in the global namespace when a
- The
Sniff::is_in_isset_or_empty()method presumed the WordPress coding style regarding code layout, which could lead to incorrect results (mostly underreporting). This affected, amongst others, theWordPress.Security.ValidatedSanitizedInputsniff. - Broken links in the inline developer documentation.
1.0.0 - 2018-07-25
If you use the WordPress Coding Standards with a custom ruleset, please be aware that a number of sniffs have been moved between categories and that the old sniff names have been deprecated. If you selectively include any of these sniffs in your custom ruleset or set custom property values for these sniffs, your custom ruleset will need to be updated.
The WordPress-VIP ruleset has also been deprecated. If you used that ruleset to check your theme/plugin for hosting on the WordPress.com VIP platform, please use the Automattic VIP coding standards instead.
If you used that ruleset for any other reason, you should probably use the WordPress-Extra or WordPress ruleset instead.
These and some related changes have been annotated in detail in the Deprecated section of this changelog.
Please read the complete changelog carefully before you upgrade.
If you are a maintainer of an external standard based on WPCS and any of your custom sniffs are based on or extend WPCS sniffs, the same applies.
WordPress.PHP.PregQuoteDelimitersniff to theWordPress-Extraruleset to warn about calls topreg_quote()which don't pass the$delimiterparameter.WordPress.Security.SafeRedirectsniff to theWordPress-Extraruleset to warn about potential open redirect vulnerabilities.WordPress.WP.DeprecatedParameterValuessniff to theWordPress-Extraruleset to detect deprecated parameter values being passed to select functions.WordPress.WP.EnqueuedResourceParameterssniff to theWordPress-Extraruleset to detect:- Calls to the script/style register/enqueue functions which don't pass a
$versionfor the script/style, which can cause issues with browser caching; and/or - Calls to the register/enqueue script functions which don't pass the
$in_footerparameter, which causes scripts - by default - to be loaded in the HTML header in a layout rendering blocking manner.
- Calls to the script/style register/enqueue functions which don't pass a
- Detection of calls to
strip_tags()and various PHP native..rand()functions to theWordPress.WP.AlternativeFunctionssniff. readonly()to the list of auto-escaped functionsSniff::$autoEscapedFunctions. This affects theWordPress.Security.EscapeOutputsniff.- The
WordPress.Security.PluginMenuSlug,WordPress.WP.CronInterval,WordPress.WP.PostsPerPageandWordPress.WP.TimezoneChangesniffs are now included in theWordPress-Extraruleset. Previously, they were already included in theWordPressandWordPress-VIPrulesets. - New utility method
Sniff::is_use_of_global_constant(). - A rationale to the package suggestion made via
composer.json. - CI: Validation of the
composer.jsonfile on each build. - A wiki page with instructions on how to set up WordPressCS to run with Eclipse on XAMPP.
- Readme: A link to an external resource with more examples for setting up PHPCS for CI.
- Readme: A badge-based quick overview of the project.
- The
WordPressruleset no longer includes theWordPress-VIPruleset, nor does it include any of the (deprecated)VIPsniffs anymore. - The following sniffs have been moved to a new category:
CronIntervalfrom theVIPcategory to theWPcategory.DirectDatabaseQueryfrom theVIPcategory to theDBcategory.DontExtractfrom theFunctionscategory to thePHPcategory.EscapeOutputfrom theXSScategory to theSecuritycategory.GlobalVariablesfrom theVariablescategory to theWPcategory.NonceVerificationfrom theCSRFcategory to theSecuritycategory.PluginMenuSlugfrom theVIPcategory to theSecuritycategory.PreparedSQLfrom theWPcategory to theDBcategory.SlowDBQueryfrom theVIPcategory to theDBcategory.TimezoneChangefrom theVIPcategory to theWPcategory.ValidatedSanitizedInputfrom theVIPcategory to theSecuritycategory.
- The
WordPress.VIP.PostsPerPagesniff has been split into two distinct sniffs:WordPress.WP.PostsPerPagewhich will check for the use of a high pagination limit and will throw awarningwhen this is encountered. For theVIPruleset, the error level remainserror.WordPress.VIP.PostsPerPagewhich will check for disabling of pagination.
- The default value for
minimum_supported_wp_version, as used by a number of sniffs detecting usage of deprecated WP features, has been updated to4.6. - The
WordPress.WP.AlternativeFunctionssniff will now only throw a warning if/when the recommended alternative function is available in the minimum supported WP version of a project. In addition to this, certain alternatives are only valid alternatives in certain circumstances, like when the WP version only supports the first parameter of the PHP function it is trying to replace. This will now be taken into account for:wp_strip_all_tags()is only a valid alternative for the PHP nativestrip_tags()when the second parameter$allowed_tagshas not been passed.wp_parse_url()only added support for the second parameter$componentof the PHP nativeparse_url()function in WP 4.7.0.
- The
WordPress.WP.DeprecatedFunctionssniff will now detect functions deprecated in WP 4.9. - The
WordPress.WP.GlobalVariablesOverridesniff will now display the name of the variable being overridden in the error message. - The
WordPress.WP.I18nsniff now extends theAbstractFunctionRestrictionSniff. - Assignments in conditions in ternaries as detected by the
WordPress.CodeAnalysis.AssignmentInConditionsniff will now be reported under a separate error codeFoundInTernaryCondition. - The default error level for the notices from the
WordPress.DB.DirectDatabaseQuerysniff has been lowered fromerrortowarning. For theVIPruleset, the error level remainserror. - The default error level for the notices from the
WordPress.Security.PluginMenuSlugsniff has been lowered fromerrortowarning. For theVIPruleset, the error level remainserror. - The default error level for the notices from the
WordPress.WP.CronIntervalsniff has been lowered fromerrortowarning. For theVIPruleset, the error level remainserror. - The
Sniff::get_function_call_parameters()utility method now has improved handling of closures when passed as function call parameters. - Rulesets: a number of error codes were previously silenced by explicitly
exclude-ing them. Now, they will be silenced by setting theseverityto0which makes it more easily discoverable for maintainers of custom rulesets how to enable these error codes again. - Various performance optimizations which should most notably make a difference when running WPCS on PHP 7.
- References to the WordPress.com VIP platform have been clarified.
- Unit Tests: custom properties set in unit test files are reset after use.
- Various improvements to the ruleset used by the WPCS project itself and minor code clean up related to this.
- CI: Each change will now also be tested against the lowest supported PHPCS 3 version.
- CI: Each change will now also be checked for PHP cross-version compatibility.
- CI: The rulesets will now also be tested on each change to ensure no unexpected messages are thrown.
- CI: Minor changes to the script to make the build testing faster.
- Updated the custom ruleset example for the changes contained in this release and to reflect current best practices regarding the PHPCompatibility standard.
- The instructions on how to set up WPCS for various IDEs have been moved from the
READMEto the wiki. - Updated output examples in
README.mdandCONTRIBUTING.mdand other minor changes to these files. - Updated references to the PHPCompatibility standard to reflect its new location and recommend using PHPCompatibilityWP.
- The
WordPress-VIPruleset has been deprecated. For checking a theme/plugin for hosting on the WordPress.com VIP platform, please use the Automattic VIP coding standards instead. If you used theWordPress-VIPruleset for any other reason, you should probably use theWordPress-ExtraorWordPressruleset instead. - The following sniffs have been deprecated and will be removed in WPCS 2.0.0:
WordPress.CSRF.NonceVerification- useWordPress.Security.NonceVerificationinstead.WordPress.Functions.DontExtract- useWordPress.PHP.DontExtractinstead.WordPress.Variables.GlobalVariables- useWordPress.WP.GlobalVariablesOverrideinstead.WordPress.VIP.CronInterval- useWordPress.WP.CronIntervalinstead.WordPress.VIP.DirectDatabaseQuery- useWordPress.DB.DirectDatabaseQueryinstead.WordPress.VIP.PluginMenuSlug- useWordPress.Security.PluginMenuSluginstead.WordPress.VIP.SlowDBQuery- useWordPress.DB.SlowDBQueryinstead.WordPress.VIP.TimezoneChange- useWordPress.WP.TimezoneChangeinstead.WordPress.VIP.ValidatedSanitizedInput- useWordPress.Security.ValidatedSanitizedInputinstead.WordPress.WP.PreparedSQL- useWordPress.DB.PreparedSQLinstead.WordPress.XSS.EscapeOutput- useWordPress.Security.EscapeOutputinstead.WordPress.VIP.AdminBarRemovalwithout replacement.WordPress.VIP.FileSystemWritesDisallowwithout replacement.WordPress.VIP.OrderByRandwithout replacement.WordPress.VIP.RestrictedFunctionswithout replacement.WordPress.VIP.RestrictedVariableswithout replacement.WordPress.VIP.SessionFunctionsUsagewithout replacement.WordPress.VIP.SessionVariableUsagewithout replacement.WordPress.VIP.SuperGlobalInputUsagewithout replacement.
- The following sniff categories have been deprecated and will be removed in WPCS 2.0.0:
CSRFVariablesXSS
- The
posts_per_pageproperty in theWordPress.VIP.PostsPerPagesniff has been deprecated as the related functionality has been moved to theWordPress.WP.PostsPerPagesniff. See WP PostsPerPage: post limit for more information about this property. - The
excludeproperty which is available to most sniffs which extend theAbstractArrayAssignmentRestrictions,AbstractFunctionRestrictionsandAbstractVariableRestrictionsclasses or any of their children, used to be astringproperty and expected a comma-delimited list of groups to exclude. The type of the property has now been changed toarray. Custom rulesets which pass this property need to be adjusted to reflect this change. Support for passing the property as a comma-delimited string has been deprecated and will be removed in WPCS 2.0.0. See Excluding a group of checks for more information about the sniffs affected by this change. - The
AbstractVariableRestrictionsSniffclass has been deprecated as all sniffs depending on this class have been deprecated. Unless a new sniff is created in the near future which uses this class, the abstract class will be removed in WPCS 2.0.0. - The
Sniff::has_html_open_tag()utility method has been deprecated as it is now only used by deprecated sniffs. The method will be removed in WPCS 2.0.0.
cancel_comment_reply_link(),get_bookmark(),get_comment_date(),get_comment_time(),get_template_part(),has_post_thumbnail(),is_attachment(),post_password_required()andwp_attachment_is_image()from the list of auto-escaped functionsSniff::$autoEscapedFunctions. This affects theWordPress.Security.EscapeOutputsniff.- WPCS no longer explicitly supports HHVM and builds are no longer tested against HHVM. For now, running WPCS on HHVM to test PHP code may still work for a little while, but HHVM has announced they are dropping PHP support.
- Compatibility with PHP 7.3. A change in PHP 7.3 was causing the
WordPress.DB.RestrictedClasses,WordPress.DB.RestrictedFunctionsand theWordPress.WP.AlternativeFunctionssniffs to fail to correctly detect issues. - Compatibility with the latest releases from PHP_CodeSniffer.
PHPCS 3.2.0 introduced new annotations which can be used inline to selectively disable/ignore certain sniffs.
Note: The initial implementation of the new annotations was buggy. If you intend to start using these new style annotations, you are strongly advised to use PHPCS 3.3.0 or higher.
For more information about these annotations, please refer to the PHPCS Wiki.
- The WPCS native whitelist comments can now be combined with the new style PHPCS whitelist annotations in the
-- for reasonspart of the annotation. WordPress.Arrays.ArrayDeclarationSpacing: the fixer will now handle the new style annotations correctly.WordPress.Arrays.CommaAfterArrayItem: prevent a fixer loop when new style annotations are encountered.WordPress.Files.FileName: respect the new style annotations if these would selectively disable this sniff.WordPress.WhiteSpace.ControlStructureSpacing: handle the new style annotations correctly for the "blank line at the start/end of control structure" checks and prevent a fixer conflict when the new style annotations are encountered.WordPress.WhiteSpace.PrecisionAlignment: allow for checking of for precision alignment on lines containing new style annotations whenphpcsis run with--ignore-annotations.
- The WPCS native whitelist comments can now be combined with the new style PHPCS whitelist annotations in the
- The
Sniff::is_test_class()method now has improved recognition of namespaced test classes. This positively affects theWordPress.Files.FileName,WordPress.NamingConventions.PrefixAllGlobalsandWordPress.WP.GlobalVariablesOverridesniffs, which each allow for test classes to (partially) not comply with the rules these sniffs check for. This fixes the following bugs:- Namespaced classes where the classname was one of the whitelisted global classes would incorrectly be recognized as a test class, even though they were not the same class.
This also happened if a namespaced class
extended one of the whitelisted global classes. - A namespaced custom test class where the name was split between the namespace declaration and the extended class declaration was not correctly recognized as the whitelisted test class.
- A namespaced test class which extended another class using a FQCN prefixed with a
\\would not be correctly recognized. - The
custom_test_class_whitelistproperty which is available for each of these sniffs expects to be passed a Fully Qualified Class Name. FQCNs prefixed with a global namespace indicator will now be correctly handled.
- Namespaced classes where the classname was one of the whitelisted global classes would incorrectly be recognized as a test class, even though they were not the same class.
This also happened if a namespaced class
- The determination of whether a
T_STRINGis a function call or not has been improved in theAbstractFunctionRestrictionsclass. This improvement benefits all sniffs which extend this abstract and any of its children (> 10 sniffs) and fixes the following false positives:- Class declarations will no longer be confused with function calls.
- Use statement alias declarations will no longer be confused with function calls.
- Various bugs in the
WordPress.Arrays.ArrayIndentationsniff:- The sniff will no longer throw false positives or try to fix multi-line text strings where the closing quote is on a line by itself.
- The sniff would go into a fixer loop when it encountered a multi-line trailing comment after an array item.
- The
WordPress.CodeAnalysis.AssignmentInConditionwas throwing false positives for ternaries in nested, but unrelated, parentheses. - The
WordPress.CodeAnalysis.EmptyStatementandWordPress.Files.FileNamesniffs underreported as they did not take PHP short open echo tags into account. - Various bugs in the
WordPress.NamingConventions.PrefixAllGlobalssniff:- Parameters in a closure declaration were incorrectly being regarded as global variables.
- Non-prefixed variables created by a
foreach()construct in the global namespace were previously not detected. - Non-prefixed globals found in namespaced test classes should be ignored by the sniff, but were not.
- Definition of non-prefixed global WP constants which are intended to be overruled, should not trigger an error from this sniff.
- The sniff presumed the WP naming conventions for PHP constructs, while it should check for the construct being prefixed regardless of whether camelCase, PascalCase, snake_case or other naming conventions are used.
- The sniff presumed the WP naming conventions for prefixes used in hook names. The sniff will now be more tolerant when non-conventional word separators are used in prefixes for hooks.
- The
WordPress.NamingConventions.ValidFunctionNamesniff no longer "hides" one message behind another. The sniff will now correctly throw a message about function names not being insnake_case, even when theFunctionDoubleUnderscoreorMethodDoubleUnderscoreerror codes have been excluded. - The
WordPress.PHP.StrictInArraysniff will no longer throw an error whenin_array,array_searchorarray_keysare used in a fileusestatement. - Various bugs in the
WordPress.Security.EscapeOutputsniff:- A limited list of native PHP constants which are safe to use, such as
PHP_EOL, has been added. When any of these constants are encountered, the sniff will no longer demand output escaping for them. - The sniff was underreporting issues with variables passed to
trigger_error(). - While reporting an issue, sometimes the wrong error message was used. The sniff logic has been adjusted to prevent this.
- The sniff will now correctly ignore the open and close brackets of short arrays.
- The sniff would throw false positives when
echo,print,exitordiewere encountered as constants, function or class names. While it may not be a good idea to use PHP keywords in such a way, it is allowed, so the sniff should handle this correctly.
- A limited list of native PHP constants which are safe to use, such as
- The
WordPress.WhiteSpace.ControlStructureSpacingsniff would inadvertently throw an error for the spacing around the colon for a return type in a function declaration. - The
WordPress.WP.AlternativeFunctionssniff used to flag all function calls tofile_get_contents()twice, suggesting to usewp_remote_get()- which is only applicable for remote URLs - and theWP_FileSystemAPI - which is not needed when just reading local files. These messages contradicted each other. The sniff will now try to determine whether the file requested is local or remote and will only throw awarningsuggesting to usewp_remote_get(), if a remote URL is being requested or when it could not be determined if the requested file is local or remote. - The expected default value for
wp_upload_bits()in theWordPress.WP.DeprecatedParameterssniff. - The
WordPress.WP.GlobalVariablesOverridesniff previously did not detect variables created by aforeach()construct which would override WP global variables. - Various bugs in the
WordPress.WP.I18nsniff:- The sniff will no longer throw false positives for calls to methods carrying the same name as any of the global WP functions being targeted and has improved handling of parse errors and live coding.
- A numeric
0would throw a false positive for "no translatable content found".
- The fixer in the
WordPress.WhiteSpace.ControlStructureSpacingsniff will no longer inadvertently remove return type declarations. - Various bugs in the
WordPress.WhiteSpace.PrecisionAlignmentsniff:- Inline HTML before the first PHP open tag was not being examined.
- Files which only contained short open echo tags for PHP were not being examined.
- The last line of inline HTML in a file was not being examined.
- Some best practice sniffs presumed the WordPress coding style regarding code layout, which could lead to incorrect results (mostly underreporting).
The following sniffs have received fixes related to this:
WordPress.DB.PreparedSQLWordPress.NamingConventions.ValidVariableNameWordPress.WP.CronIntervalWordPress.WP.I18n
- Various minor fixes based on visual inspection and Scrutinizer analysis feedback.
- Typo in the instructions contained in
CONTRIBUTING.md. - Broken link in the
README.mdfile.
0.14.1 - 2018-02-15
- The
WordPress.NamingConventions.PrefixAllGlobalssniff contained a bug which could inadvertently trigger class autoloading of the project being sniffed and by extension could cause fatal errors during the PHPCS run.
0.14.0 - 2017-11-01
WordPress.Arrays.MultipleStatementAlignmentsniff to theWordPress-Coreruleset which will align the array assignment operator for multi-item, multi-line associative arrays. This new sniff offers four custom properties to customize its behavior:ignoreNewlines,exact,maxColumnandalignMultilineItems.WordPress.DB.PreparedSQLPlaceholderssniff to theWordPress-Coreruleset which will analyze the placeholders passed to$wpdb->prepare()for their validity, check whether queries usingIN ()andLIKEstatements are created correctly and will check whether a correct number of replacements are passed. This sniff should help detect queries which are impacted by the security fixes to$wpdb->prepare()which shipped with WP 4.8.2 and 4.8.3. The sniff also adds a new "PreparedSQLPlaceholders replacement count" whitelist comment for pertinent replacement count vs placeholder mismatches. Please consider carefully whether something could be a bug when you are tempted to use the whitelist comment and if so, report it.WordPress.PHP.DiscourageGotosniff to theWordPress-Coreruleset.WordPress.PHP.RestrictedFunctionssniff to theWordPress-Coreruleset which initially forbids the use ofcreate_function(). This was previous only discouraged under certain circumstances.WordPress.WhiteSpace.ArbitraryParenthesesSpacingsniff to theWordPress-Coreruleset which checks the spacing on the inside of arbitrary parentheses.WordPress.WhiteSpace.PrecisionAlignmentsniff to theWordPress-Coreruleset which will throw a warning when precision alignment is detected in PHP, JS and CSS files.WordPress.WhiteSpace.SemicolonSpacingsniff to theWordPress-Coreruleset which will throw a (fixable) error when whitespace is found before a semi-colon, except for when the semi-colon denotes an emptyfor()condition.WordPress.CodeAnalysis.AssignmentInConditionsniff to theWordPress-Extraruleset.WordPress.WP.DiscouragedConstantssniff to theWordPress-ExtraandWordPress-VIPrulesets to detect usage of deprecated WordPress constants, such asSTYLESHEETPATHandHEADER_IMAGE.- Ability to pass the
minimum_supported_versionto use for theDeprecatedFunctions,DeprecatedClassesandDeprecatedParameterssniff in one go. You can pass aminimum_supported_wp_versionruntime variable for this from the command line or pass it using aconfigdirective in a custom ruleset. Generic.Formatting.MultipleStatementAlignment- customized to have amaxPaddingof40-,Generic.Functions.FunctionCallArgumentSpacingandSquiz.WhiteSpace.ObjectOperatorSpacingto theWordPress-Coreruleset.Squiz.Scope.MethodScope,Squiz.Scope.MemberVarScope,Squiz.WhiteSpace.ScopeKeywordSpacing,PSR2.Methods.MethodDeclaration,Generic.Files.OneClassPerFile,Generic.Files.OneInterfacePerFile,Generic.Files.OneTraitPerFile,PEAR.Files.IncludingFile,Squiz.WhiteSpace.LanguageConstructSpacing,PSR2.Namespaces.NamespaceDeclarationto theWordPress-Extraruleset.- The
is_class_constant(),is_class_propertyandvalid_direct_scope()utility methods to theWordPress\Sniffclass.
- When passing an array property via a custom ruleset to PHP_CodeSniffer, spaces around the key/value are taken as intentional and parsed as part of the array key/value. In practice, this leads to confusion and WPCS does not expect any values which could be preceded/followed by a space, so for the WordPress Coding Standard native array properties, like
customAutoEscapedFunction,text_domain,prefixes, WPCS will now trim whitespace from the keys/values received before use. - The WPCS native whitelist comments used to only work when they were put on the end of the line of the code they applied to. As of now, they will also be recognized when they are be put at the end of the statement they apply to.
- The
WordPress.Arrays.ArrayDeclarationSpacingsniff used to enforce all associative arrays to be multi-line. The handbook has been updated to only require this for multi-item associative arrays and the sniff has been updated accordingly. The original behavior can still be enforced by setting the newallow_single_item_single_line_associative_arraysproperty tofalsein a custom ruleset. - The
WordPress.NamingConventions.PrefixAllGlobalssniff will now allow for a limited list of WP core hooks which are intended to be called by plugins and themes. - The
WordPress.PHP.DiscouragedFunctionssniff used to includecreate_function. This check has been moved to the newWordPress.PHP.RestrictedFunctionssniff. - The
WordPress.PHP.StrictInArraysniff now has a separate error codeFoundNonStrictFalsefor when the$strictparameter has been set tofalse. This allows for excluding the warnings for that particular situation, which will normally be intentional, via a custom ruleset. - The
WordPress.VIP.CronIntervalsniff now allows for customizing the minimum allowed cron interval by setting a property in a custom ruleset. - The
WordPress.VIP.RestrictedFunctionssniff used to prohibit the use of certain WP native functions, recommending the use ofwpcom_vip_get_term_link(),wpcom_vip_get_term_by()andwpcom_vip_get_category_by_slug()instead, as the WP native functions were not being cached. As the results of the relevant WP native functions are cached as of WP 4.8, the advice has now been reversed i.e. use the WP native functions instead ofwpcom...functions. - The
WordPress.VIP.PostsPerPagesniff now allows for customizing thepost_per_pagelimit for which the sniff will trigger by setting a property in a custom ruleset. - The
WordPress.WP.I18nsniff will now allow and actively encourage omitting the text domain in I18n function calls if the text domain passed via thetext_domainproperty isdefault, i.e. the domain used by Core. Whendefaultis one of several text domains passed via thetext_domainproperty, the error thrown when the domain is missing has been downgraded to awarning. - The
WordPress.XSS.EscapeOutputsniff now has a separate error codeOutputNotEscapedShortEchoand the error message texts have been updated. - Moved
Squiz.PHP.Evalfrom theWordPress-ExtraandWordPress-VIPto theWordPress-Coreruleset. - Removed two sniffs from the
WordPress-VIPruleset which were already included via theWordPress-Coreruleset. - The unit test suite is now compatible with PHPCS 3.1.0+ and PHPUnit 6.x.
- Some tidying up of the unit test case files.
- All sniffs are now also being tested against PHP 7.2 for consistent sniff results.
- An attempt is made to detect potential fixer conflicts early via a special build test.
- Various minor documentation fixes.
- Improved the Atom setup instructions in the Readme.
- Updated the unit testing information in Contributing.
- Updated the custom ruleset example for the changes contained in this release and to make it more explicit what is recommended versus example code.
- The minimum recommended version for the suggested
DealerDirect/phpcodesniffer-composer-installerComposer plugin has gone up to0.4.3. This patch version fixes support for PHP 5.3.
- The
WordPress.Arrays.ArrayIndentationsniff did not correctly handle array items with multi-line strings as a value. - The
WordPress.Arrays.ArrayIndentationsniff did not correctly handle array items directly after an array item with a trailing comment. - The
WordPress.Classes.ClassInstantiationsniff will now correctly handle detection when usingnew $array['key']ornew $array[0]. - The
WordPress.NamingConventions.PrefixAllGlobalssniff did not allow for arbitrary word separators in hook names. - The
WordPress.NamingConventions.PrefixAllGlobalssniff did not correctly recognize namespaced constants as prefixed. - The
WordPress.PHP.StrictInArraysniff would erroneously trigger if thetruefor$strictwas passed in uppercase. - The
WordPress.PHP.YodaConditionssniff could get confused over complex ternaries containing assignments. This has been remedied. - The
WordPress.WP.PreparedSQLsniff would erroneously throw errors about comments found within a DB function call. - The
WordPress.WP.PreparedSQLsniff would erroneously throw errors about(int),(float)and(bool)casts and would also flag the subsequent variable which had been safe casted. - The
WordPress.XSS.EscapeOutputsniff would erroneously trigger when using a fully qualified function call - including the global namespace\indicator - to one of the escaping functions. - The lists of WP global variables and WP mixed case variables have been synchronized, which fixes some false positives.
0.13.1 - 2017-08-07
- Fatal error when using PHPCS 3.x with the
installed_pathsconfig variable set via the ruleset.
0.13.0 - 2017-08-03
- Support for PHP_CodeSniffer 3.0.2+. The minimum required PHPCS version (2.9.0) stays the same.
- Support for the PHPCS 3
--ignore-annotationscommand line option. If you pass this option, both PHPCS native@ignore ...annotations as well as the WPCS specific whitelist flags will be ignored.
- The minimum required PHP version is now 5.3 when used in combination with PHPCS 2.x and PHP 5.4 when used in combination with PHPCS 3.x.
- The way the unit tests can be run is now slightly different for PHPCS 2.x versus 3.x. For more details, please refer to the updated information in the Contributing Guidelines.
- Release archives will no longer contain the unit tests and other typical development files. You can still get these by using Composer with
--prefer-sourceor by checking out a git clone of the repository. - Various textual improvements to the Readme.
- Various textual improvements to the Contributing Guidelines.
- Minor internal changes.
- The
WordPress.Arrays.ArrayDeclarationsniff has been deprecated. The last remaining checks this sniff contained have been moved to theWordPress.Arrays.ArrayDeclarationSpacingsniff. - Work-arounds which were in place to support PHP 5.2.
- A minor bug where the auto-fixer could accidentally remove a comment near an array opener.
0.12.0 - 2017-07-21
- A default file encoding setting to the
WordPress-Coreruleset. All files sniffed will now be regarded asutf-8by default. WordPress.Arrays.ArrayIndentationsniff to theWordPress-Coreruleset to verify - and auto-fix - the indentation of array items and the array closer for multi-line arrays. This replaces the (partial) indentation fixing contained within theWordPress.Array.ArrayDeclarationSpacingsniff.WordPress.Arrays.CommaAfterArrayItemsniff to theWordPress-Coreruleset to enforce that each array item is followed by a comma - except for the last item in a single-line array - and checks the spacing around the comma. This replaces (and improves) the checks which were previously included in theWordPress.Arrays.ArrayDeclarationsniff which were causing incorrect fixes and fixer conflicts.WordPress.Functions.FunctionCallSignatureNoParamssniff to theWordPress-Coreruleset to verify that function calls without parameters do not have any whitespace between the parentheses.WordPress.WhiteSpace.DisallowInlineTabsto theWordPress-Coreruleset to verify - and auto-fix - that spaces are used for mid-line alignment.WordPress.WP.CapitalPDangitsniff to theWordPress-Coreruleset to - where relevant - verify thatWordPressis spelled correctly. For misspellings in text strings and comment text, the sniff can auto-fix violations.Squiz.Classes.SelfMemberReferencewhitespace related checks to theWordPress-Coreruleset and the additional check for usingselfrather than a FQN to theWordPress-Extraruleset.Squiz.PHP.EmbeddedPhpsniff to theWordPress-Coreruleset to check PHP code embedded within HTML blocks.PSR2.ControlStructures.SwitchDeclarationto theWordPress-Coreruleset to check for the correct layout ofswitchcontrol structures.WordPress.Classes.ClassInstantiationsniff to theWordPress-Extraruleset to detect - and auto-fix - missing parentheses on object instantiation and superfluous whitespace in PHP and JS files. The sniff will also detectnewbeing assigned by reference.WordPress.CodeAnalysis.EmptyStatementsniff to theWordPress-Extraruleset to detect - and auto-fix - superfluous semi-colons and empty PHP open-close tag combinations.WordPress.NamingConventions.PrefixAllGlobalssniff to theWordPress-Extraruleset to verify that all functions, classes, interfaces, traits, variables, constants and hook names which are declared/defined in the global namespace are prefixed with one of the prefixes provided via a custom property or via the command line. To activate this sniff, one or more allowed prefixes should be provided to the sniff. This can be done using a custom ruleset or via the command line. PHP superglobals and WP global variables are exempt from variable name prefixing. Deprecated hook names will also be disregarded when non-prefixed. Back-fills for known native PHP functionality is also accounted for. For verified exceptions, unprefixed code can be whitelisted. Code in unit test files is automatically exempt from this sniff.WordPress.WP.DeprecatedClassessniff to theWordPress-Extraruleset to detect usage of deprecated WordPress classes.WordPress.WP.DeprecatedParameterssniff to theWordPress-Extraruleset to detect deprecated parameters being passed to WordPress functions with a value other than the expected default.- The
sanitize_textarea_field()function to thesanitizingFunctionslist used by theWordPress.CSRF.NonceVerification,WordPress.VIP.ValidatedSanitizedInputandWordPress.XSS.EscapeOutputsniffs. - The
find_array_open_closer()utility method to theWordPress_Sniffclass. - Information about setting
installed_pathsusing a custom ruleset to the Readme. - Additional support links to the
composer.jsonfile. - Support for Composer PHPCS plugins which sort out the
installed_pathssetting. - Linting and code-style check of the XML ruleset files provided by WPCS.
- The minimum required PHP_CodeSniffer version to 2.9.0 (was 2.8.1). Take note: PHPCS 3.x is not (yet) supported. The next release is expected to fix that.
- Improved support for detecting issues in code using heredoc and/or nowdoc syntax.
- Improved sniff efficiency, precision and performance for a number of sniffs.
- Updated a few sniffs to take advantage of new features and fixes which are included in PHP_CodeSniffer 2.9.0.
WordPress.Files.Filename: The "file name mirrors the class name prefixed with 'class'" check for PHP files containing a class will no longer be applied to typical unit test classes, i.e. for classes which extendWP_UnitTestCase,PHPUnit_Framework_TestCaseandPHPUnit\Framework\TestCase. Additional test case base classes can be passed to the sniff using the newcustom_test_class_whitelistproperty.- The
WordPress.Files.FileNamesniff allows now for more theme-specific template hierarchy based file name exceptions. - The whitelist flag for the
WordPress.VIP.SlowQuerysniff wastax_querywhich was unintuitive. This has now been changed toslow queryto be in line with other whitelist flags. - The
WordPress.WhiteSpace.OperatorSpacingsniff will now ignore operator spacing withindeclare()statements. - The
WordPress.WhiteSpace.OperatorSpacingsniff now extends the upstreamSquiz.WhiteSpace.OperatorSpacingsniff for improved results and will now also examine the spacing around ternary operators and logical (&&,||) operators. - The
WordPress.WP.DeprecatedFunctionssniff will now detect functions deprecated in WP 4.7 and 4.8. Additionally, a number of other deprecated functions which were previously not being detected have been added to the sniff and for a number of functions the "alternative" for the deprecated function has been added/improved. - The
WordPress.XSS.EscapeOutputsniff will now also detect unescaped output when the short open echo tags<?=are used. - Updated the list of WP globals which is used by both the
WordPress.Variables.GlobalVariablesand theWordPress.NamingConventions.PrefixAllGlobalssniffs. - Updated the information on using a custom ruleset and associated naming conventions in the Readme.
- Updated the custom ruleset example to provide a better starting point and renamed the file to follow current PHPCS best practices.
- Various inline documentation improvements.
- Updated the link to the PHPStorm documentation in the Readme.
- Various textual improvements to the Readme.
- Minor improvements to the build script.
Squiz.Commenting.LongConditionClosingCommentsniff from theWordPress-Coreruleset. This rule has been removed from the WP Coding Standards handbook.- The exclusion of the
Squiz.ControlStructures.ControlSignature.NewlineAfterOpenBraceerror from theWordPress-Coreruleset. - The exclusion of the
PEAR.Functions.FunctionCallSignature.ContentAfterOpenBracketandPEAR.Functions.FunctionCallSignature.CloseBracketLineerror from theWordPress-Coreruleset when used in combination with the fixer, i.e.phpcbf. The exclusions remain in place forphpcsruns. wp_get_post_terms(),wp_get_post_categories(),wp_get_post_tags()andwp_get_object_terms()from theWordPress.VIP.RestrictedFunctionssniff as these functions are now cached natively since WP 4.7.
- The
WordPress.Array.ArrayDeclarationSpacingcould be overeager when fixing associative arrays to be multi-line. Non-associative single-line arrays which contained a nested associative array would also be auto-fixed by the sniff, while only the nested associated array should be fixed. - The
WordPress.Files.FileNamesniff did not play nice with IDEs passing a filename to PHPCS via--stdin-path=. - The
WordPress.Files.FileNamesniff was being triggered on code passed viastdinwhere there is no file name to examine. - The
WordPress.PHP.YodaConditionssniff would give a false positive for the result of a condition being assigned to a variable. - The
WordPress.VIP.RestrictedVariablessniff was potentially underreporting issues when the variables being restricted were a combination of variables, object properties and array members. - The auto-fixer in the
WordPress.WhiteSpace.ControlStructureSpacingsniff which deals with "blank line after control structure" issues could cause comments at the end of control structures to be removed. - The
WordPress.WP.DeprecatedFunctionssniff was reporting the wrong WP version for the deprecation of a number of functions. - The
WordPress.WP.EnqueuedResourcessniff would potentially underreport issues in certain circumstances. - The
WordPress.XSS.EscapeOutputsniff will no now longer report issues when it encounters a__DIR__,(unset)cast or a floating point number, and will correctly disregard more arithmetic operators when deciding whether to report an issue or not. - The whitelisting of errors using flags was sometimes a bit too eager and could accidentally whitelist code which was not intended to be whitelisted.
- Various (potential)
Undefined variable,Undefined indexandUndefined offsetnotices. - Grammar in one of the
WordPress.WP.I18nerror messages.
0.11.0 - 2017-03-20
If you use the WordPress Coding Standards with a custom ruleset, please be aware that some of the checks have been moved between sniffs and that the naming of a number of error codes has changed. If you exclude some sniffs or error codes, you may have to update your custom ruleset to be compatible with WPCS 0.11.0.
Additionally, to make it easier for you to customize your ruleset, two new wiki pages have been published with information on the properties you can adjust from your ruleset:
For more detailed information about the changed sniff names and error codes, please refer to PR #633 and PR #814.
If you maintain or develop sniffs based upon the WordPress Coding Standards, most notably, if you use methods and properties from the WordPress_Sniff class, extend one of the abstract sniff classes WPCS provides or extend other sniffs from WPCS to use their properties, please be aware that this release contains significant changes which will, more likely than not, affect your sniffs.
Please read this changelog carefully to understand how this will affect you. For more detailed information on the most significant changes, please refer to PR #795, PR #833 and PR #841. You are also encouraged to check the file history of any WPCS classes you extend.
WordPress.WP.DeprecatedFunctionssniff to theWordPress-Extraruleset to check for usage of deprecated WP version and show errors/warnings depending on aminimum_supported_versionwhich can be passed to the sniff from a custom ruleset. The default value for theminimum_supported_versionproperty is three versions before the current WP version.WordPress.WP.I18n: ability to check for missing translators comments when a I18n function call contains translatable text strings containing placeholders. This check will also verify that the translators comment is correctly placed in the code and uses the correct comment type for optimal compatibility with the various tools available to create.potfiles.WordPress.WP.I18n: ability to pass thetext_domainto check for from the command line.WordPress.Arrays.ArrayDeclarationSpacing: check + fixer for single line associative arrays. The handbook states that these should always be multi-line.WordPress.Files.FileName: verification that files containing a class reflect this in the file name as per the core guidelines. This particular check can be disabled in a custom ruleset by setting the newstrict_class_file_namesproperty.WordPress.Files.FileName: verification that files in/wp-includes/containing template tags - annotated with@subpackage Templatein the file header - use the-templatesuffix.WordPress.Files.FileName:is_themeproperty which can be set in a custom ruleset. This property can be used to indicate that the project being checked is a theme and will allow for a predefined theme hierarchy based set of exceptions to the file name rules.WordPress.VIP.AdminBarRemoval: check for hiding the admin bar using CSS.WordPress.VIP.AdminBarRemoval: customizableremove_onlyproperty to toggle whether to error of all manipulation of the visibility of the admin bar or to execute more thorough checking for removal only.WordPress.WhiteSpace.ControlStructureSpacing: support for checking the whitespace intry/catchconstructs.WordPress.WhiteSpace.ControlStructureSpacing: check that the space after the open parenthesis and before the closing parenthesis of control structures and functions is exactly one space. Includes auto-fixer.WordPress.WhiteSpace.CastStructureSpacing: ability to automatically fix errors thrown by the sniff.WordPress.VIP.SessionFunctionsUsage: detection of thesession_abort(),session_create_id(),session_gc()andsession_reset()functions.WordPress.CSRF.NonceVerification: ability to pass custom sanitization functions to the sniff.- The
get_the_ID()function to theautoEscapedFunctionslist used by theWordPress.XSS.EscapeOutputsniff. - The
wp_strip_all_tags(),sanitize_hex_color_no_hash()andsanitize_hex_color()functions to thesanitizingFunctionslist used by theWordPress.CSRF.NonceVerification,WordPress.VIP.ValidatedSanitizedInputandWordPress.XSS.EscapeOutputsniffs. - The
floatval()function to theescapingFunctions,sanitizingFunctions,unslashingSanitizingFunctions,SQLEscapingFunctionslists used by theWordPress.CSRF.NonceVerification,WordPress.VIP.ValidatedSanitizedInput,WordPress.XSS.EscapeOutputandWordPress.WP.PreparedSQLsniffs. - The table name based
clean_*_cache()functions to thecacheDeleteFunctionslist used by theWordPress.VIP.DirectDatabaseQuerysniff. - Abstract
AbstractFunctionParameterparent class to allow for examining parameters passed in function calls. - A number of utility functions to the
WordPress_Sniffclass:strip_quotes(),addMessage(),addFixableMessage(),string_to_errorcode(),does_function_call_have_parameters(),get_function_call_parameter_count(),get_function_call_parameters(),get_function_call_parameter(),has_html_open_tag(). Squiz.Commenting.LongConditionClosingComment,Squiz.WhiteSpace.CastSpacing,Generic.Formatting.DisallowMultipleStatementsto theWordPress-Coreruleset.Squiz.PHP.NonExecutableCode,Squiz.Operators.IncrementDecrementUsage,Squiz.Operators.ValidLogicalOperators,Squiz.Functions.FunctionDuplicateArgument,Generic.PHP.BacktickOperator,Squiz.PHP.DisallowSizeFunctionsInLoopsto theWordPress-Extraruleset.- Numerous additional unit tests covering the correct handling of properties overruled via a custom ruleset by various sniffs.
- Instructions on how to use WPCS with Visual Studio to the Readme.
- Section on how to use WPCS with CI Tools to the Readme, initially covering integration with Travis CI.
- Section on considerations when writing sniffs for WPCS to
Contributing.md.
- The minimum required PHP version to 5.2 (was 5.1).
- The minimum required PHP_CodeSniffer version to 2.8.1 (was 2.6).
- Improved support for detecting issues in code using closures (anonymous functions), short array syntax and anonymous classes.
- Improved sniff efficiency and performance for a number of sniffs.
- The discouraged/restricted functions sniffs have been reorganized and made more modular.
- The new
WordPress.PHP.DevelopmentFunctionssniff now contains the checks related to PHP functions typically used during development which are discouraged in production code. - The new
WordPress.PHP.DiscouragedPHPFunctionssniff now contains checks related to various PHP functions, use of which is discouraged for various reasons. - The new
WordPress.WP.AlternativeFunctionssniff contains the checks related to PHP functions for which WP offers an alternative which should be used instead. - The new
WordPress.WP.DiscouragedFunctionssniff contains checks related to various WP functions, use of which is discouraged for various reasons. - A number of checks contained in the
WordPress.VIP.RestrictedFunctionssniff have been moved to other sniffs. - The
WordPress.PHP.DiscouragedFunctionssniff has been deprecated and is no longer used. The checks which were previously contained herein have been moved to other sniffs. - The reorganized sniffs also detect a number of additional functions which were previously ignored by these sniffs. For more detail, please refer to the summary of the PR and to PR #759.
- The new
- The error codes for these sniffs as well as for
WordPress.DB.RestrictedClasses,WordPress.DB.RestrictedFunctions,WordPress.Functions.DontExtract,WordPress.PHP.POSIXFunctionsand a number of theVIPsniffs have changed. They were previously based on function group names and will now be based on function group name in combination with the identified function name. Complete function groups can still be silenced by using theexcludeproperty in a custom ruleset. WordPress.NamingConventions.ValidVariableName: ThecustomVariablesWhitelistproperty which could be passed from the ruleset has been renamed tocustomPropertiesWhitelistas it is only usable to whitelist class properties.WordPress.WP.I18n: now allows for an array of text domain names to be passed to thetext_domainproperty from a custom ruleset.WordPress.WhiteSpace.CastStructureSpacing: the error level for the checks in this sniff has been raised fromwarningtoerror.WordPress.Variables.GlobalVariables: will no longer throw errors if the global variable override is done from within a test method. Whether something is considered a "test method" is based on whether the method is in a class which extends a predefined set of known unit test classes. This list can be enhanced by setting thecustom_test_class_whitelistproperty in your ruleset.- The
WordPress.Arrays.ArrayDeclarationsniff has been split into two sniffs:WordPress.Arrays.ArrayDeclarationandWordPress.Arrays.ArrayDeclarationSpacingfor better compatibility with PHPCS upstream. - The
WordPress.Arrays.ArrayDeclarationsniff has been synced with the PHPCS upstream version to get the benefit of some bug fixes and improvements which had been made upstream since the sniff was originally copied over. - The
WordPress.VIP.FileSystemWritesDisallow,WordPress.VIP.TimezoneChangeandWordPress.VIP.SessionFunctionsUsagesniffs now extend theWordPress_AbstractFunctionRestrictionsSniff. - Property handling of custom properties set via a custom ruleset where the property is expected to be set in array format (
type="array") has been made more lenient and will now also handle properties passed as a comma delimited lists correctly. This affects all customizable properties which expect array format. - Moved
Squiz.PHP.DisallowMultipleAssignmentsfrom theWordPress-Extrato theWordPress-Coreruleset. - Replaced the
WordPress.Classes.ValidClassName,WordPress.PHP.DisallowAlternativePHPTagsand theWordPress.Classes.ClassOpeningStatementsniffs with the existingPEAR.NamingConventions.ValidClassNameand the new upstreamGeneric.PHP.DisallowAlternativePHPTagsandGeneric.Classes.OpeningBraceSameLinesniffs in theWordPress-Coreruleset. - Use the upstream
Squiz.PHP.Evalsniff for detecting the use ofeval()instead of a WPCS native implementation. - Made the
Generic.WhiteSpace.ScopeIndentsniff in theWordPress-Coreruleset more lenient to allow for different indentation in inline HTML, heredoc and nowdoc structures. - Made the
Generic.Strings.UnnecessaryStringConcatsniff in theWordPress-Extraruleset more lenient to allow for multi-line string concatenation. - All sniffs are now also being tested against PHP 7.1 for consistent sniff results.
- The requirements for running the sniffs have been made more explicit in the readme.
- Updated composer installation instructions in the readme.
- Updated information about the rulesets in the readme and moved the information up to make it easier to find.
- Improved the information about running the unit tests in
Contributing.md. - Improved the inline documentation of the rulesets.
- Various other code quality and code consistency improvements under the hood, including refactoring of some of the abstract sniff classes, closer coupling of the child classes to the
WordPress_Sniffparent class and changes to the visibility and staticness of properties for a large number of sniffs.
- Warnings thrown by individual sniffs about parse errors they encounter. This is left up to the
Generic.PHP.Syntaxsniff which is included in theWordPress-Extraruleset. - The
post_class()function from theautoEscapedFunctionslist used by theWordPress.XSS.EscapeOutputsniff. - The
Generic.Files.LowercasedFilenamesniff from theWordPress-Coreruleset in favor of the improvedWordPress.Files.FileNamesniff to prevent duplicate messages being thrown. - Some temporary work-arounds for changes which were pulled and merged into PHPCS upstream.
WordPress.Variables.GlobalVariables: All known bugs have been fixed. If you'd previously disabled the sniff in your custom ruleset because of these bugs, it should be fine to re-enable it now.- Assignments to global variables using other assignment operators than the
=operator were not detected. - If a
global ...;statement was detected, the whole file would be checked for the variables which were made global, not just the code after the global statement. - If a
global ...;statement was detected, the whole file would be checked for the variables which were made global, including code contained within a function/closure/class scope where there is no access to the global variable. - If a
global ...;statement was detected within a function call or closure, the whole file would be checked for the variables which were made global, not just the code within the function or closure. - If a
global ...;statement was detected and an assignment was made to a static class variable using the same name as one of the variables made global, an error would incorrectly be thrown. - An override of a protected global via
$GLOBALSin combination with simple string concatenation obfuscation was not being detected.
- Assignments to global variables using other assignment operators than the
WordPress.WP.I18n: all reported bugs have been fixed.- A superfluous
UnorderedPlaceholderserror was being thrown when%%(a literal % sign) was encountered in a string. - The sniff would sometimes erroneously trigger errors when a literal
%was found in a translatable string without placeholders. - Not all type of placeholders were being recognized.
- No warning was being thrown when encountering a mix of ordered and unordered placeholders.
- The fixer for unordered placeholders was erroneously replacing all placeholders as if they were the first one.
- The fixer for unordered placeholders could cause faulty replacements in double quoted strings.
- Compatibility with PHP nightly / PHP 7.2.
- A superfluous
WordPress.WhiteSpace.ControlStructureSpacing: synced in fixes from the upstream version.- The fixer would bork on control structures which contained only a single empty line.
- The sniff did not check the spacing used for
do {} while ()control structures. - Conditional function declarations could cause an infinite loop when using the fixer.
WordPress.VIP.PluginMenuSlug: the sniff would potentially incorrectly process method calls and namespaced functions with the same function name as the targeted WordPress native functions.WordPress.VIP.CronInterval: the native WP time constants were not recognized leading to false positives.WordPress.VIP.CronInterval: the finding of the referenced function declaration has been made more accurate.WordPress.PHP.YodaConditions: minor clarification of the error message.WordPress.NamingConventions.ValidVariableName: now allows for a predefined list of known mixed case global variables coming from WordPress itself reducing false positives.- The
unslashingSanitizingFunctionslist was not consistently taken into account when verifying whether a variable was sanitized for theWordPress.VIP.ValidatedSanitizedInputandWordPress.CSRF.NonceVerificationsniffs. - The passing of properties via the ruleset was buggy for a number of sniffs - most notably those sniffs using custom properties in array format - and could lead to unintended bleed-through between sniffs.
- Various (potential)
Undefined variable,Undefined indexandUndefined offsetnotices. - An issue with placeholder replacement not taking place in some error messages.
- A (potential) issue which could play up when sniffs examined text strings which contained quotes.
0.10.0 - 2016-08-29
WordPress.WP.I18nsniff to theWordPress-Coreruleset to flag dynamic translatable strings and text domains.WordPress.PHP.DisallowAlternativePHPTagssniff to theWordPress-Coreruleset to flag - and fix - ASP and<script>PHP open tags.WordPress.Classes.ClassOpeningStatementsniff to theWordPress-Coreruleset to flag - and fix - class opening brace placement.WordPress.NamingConventions.ValidHookNamesniff to theWordPress-Coreruleset to flag filter and action hooks which don't comply with the guideline of lowercase letters and underscores. For maintaining backward-compatibility of hook names anadditionalWordDelimitersproperty can be added via a custom ruleset.WordPress.Functions.DontExtractsniff to theWordPress-Coreruleset to flag usage of theextract()function.WordPress.PHP.POSIXFunctionssniff to theWordPress-Coreruleset to flag usage of regex functions from the POSIX PHP extension which was deprecated since PHP 5.3 and removed in PHP 7.WordPress.DB.RestrictedFunctionsandWordPress.DB.RestrictedClassessniffs to theWordPress-Coreruleset to flag usage of direct database calls using PHP functions and classes rather than the WP functions for the same.- Abstract
AbstractClassRestrictionsparent class to allow for easier sniffing for usage of specific classes. Squiz.Strings.ConcatenationSpacing,PSR2.ControlStructures.ElseIfDeclaration,PSR2.Files.ClosingTag,Generic.NamingConventions.UpperCaseConstantNameto theWordPress-Coreruleset.- Ability to add arbitrary variables to the whitelist via a custom ruleset property for the
WordPress.NamingConventions.ValidVariableNamesniff. - Ability to use a whitelist comment for tax queries for the
WordPress.VIP.SlowDBQuerysniff. - Instructions on how to use WPCS with Atom and SublimeLinter to the Readme.
- Reference to the wiki to the Readme.
- Recommendation to also use the PHPCompatibility ruleset to the Readme.
- The minimum required PHP_CodeSniffer version to 2.6.0.
- Moved the
WordPress.WP.PreparedSQLsniff fromWordPress-ExtratoWordPress-Core. WordPress.PHP.StrictInArraywill now also flag non-strict usage ofarray_keys()andarray_search().- Added
_deprecated_constructor()and_deprecated_hook()to the list of printing functions. - Added numerous additional functions to sniff for to the
WordPress.VIP.RestrictedFunctionssniff as per the VIP guidelines. - Upped the
posts_per_pagelimit from 50 to 100 inWordPress.VIP.PostsPerPagesniff as per the VIP guidelines. - Added
cat_IDto the whitelisted exceptions for theWordPress.NamingConventions.ValidVariableNamesniff. - Added
__debugInfoto the magic method whitelist for class methods starting with double underscore in theWordPress.NamingConventions.ValidFunctionNamesniff. - An error will now also be thrown for non-magic functions using a double underscore prefix -
WordPress.NamingConventions.ValidFunctionNamesniff. - The
WordPress.Arrays.ArrayAssignmentRestrictions,WordPress.Functions.FunctionRestrictions,WordPress.Variables.VariableRestrictionssniffs weren't in actual fact sniffs, but parent classes for child sniffs. These have now all been turned into proper abstract parent classes and moved to the mainWordPressdirectory. - The array provided to
AbstractFunctionRestrictionscan now take awhitelistkey to whitelist select functions when blocking a group of functions by function prefix. - Updated installation instructions in the readme.
- The
WordPress-Coreruleset is now ordered according to the handbook - The WPCS code base itself now complies with the WordPress-Core, -Extra and -Docs coding standards.
- Various other code quality and code consistency improvements under the hood.
Squiz.Functions.FunctionDeclarationArgumentSpacing.SpacingBeforeClosefrom theWordPress-Corestandard (was causing duplicate messages for the same issue).Squiz.Commenting.FunctionComment.ScalarTypeHintMissing,Squiz.Commenting.InlineComment.NotCapitalfrom theWordPress-Docsstandard.- Removed the sniffing for
get_pages()from theWordPress.VIP.RestrictedFunctionssniff as per the VIP guidelines. - Removed the sniffing for
extract()from theWordPress.VIP.RestrictedFunctionssniff as it's now covered in a separate sniff. - Removed the sniffing for the POSIX functions from the
WordPress.PHP.DiscouragedFunctionssniff as it's now covered in a separate sniff.
- Error message precision for the
WordPress.NamingConventions.ValidVariableNamesniff. - Bug in the
WordPress.WhiteSpace.ControlStructureSpacing.BlankLineAfterEndsniff which was incorrectly being triggered on last method of class. - Function name sniffs based on the
AbstractFunctionRestrictionsparent class will now do a case-insensitive function name comparison. - Function name sniffs in the
WordPress.PHP.DiscouragedFunctionssniff will now do a case-insensitive function name comparison. - Whitelist comments directly followed by a PHP closing tag were not being recognized.
- Some PHP Magic constants were not recognized by the
WordPress.XSS.EscapeOutputsniff. - An error message suggesting camel caps rather than the intended snake case format in the
WordPress.NamingConventions.ValidFunctionNamesniff. WordPress.WhiteSpace.ControlStructureSpacingshould no longer throw error notices during live code review.- Errors will be no longer be thrown for methods not complying with the naming conventions when the class extends a parent class or implements an interface -
WordPress.NamingConventions.ValidFunctionNamesniff.
0.9.0 - 2016-02-01
count()to the list of auto-escaped functions.Squiz.PHP.CommentedOutCodesniff toWordPress-VIPruleset.- Support for PHP 5.2.
attachment_url_to_postid()andparse_url()to the restricted functions forWordPress-VIP.WordPress.VIP.OrderByRandsniff.WordPress.PHP.StrictInArraysniff forWordPress-VIPandWordPress-Extra.get_tag_link(),get_category_link(),get_cat_ID(),url_to_post_id(),attachment_url_to_postid()get_posts(),wp_get_recent_posts(),get_pages(),get_children(),wp_get_post_terms()wp_get_post_categories(),wp_get_post_tags(),wp_get_object_terms(),term_exists(),count_user_posts(),wp_old_slug_redirect(),get_adjacent_post(),get_previous_post(),get_next_post()to uncached functions inWordPress.VIP.RestrictedFunctionssniff.wp_handle_upload()andarray_key_exists()to the list of sanitizing functions.- Checking for object properties in
WordPress.PHP.YodaConditionssniff. WordPress.NamingConventions.ValidVariableNamesniff.- Flagging of function calls incorporated into database queries in
WordPress.WP.PreparedSQL. - Recognition of escaping and auto-escaped functions in
WordPress.WP.PreparedSQL. true,false, andnullto the tokens ignored inWordPress.XSS.EscapeOutput.
- Incorrect ternary detection in
WordPress.XSS.EscapeOutputsniff. - False positives when detecting variables interpolated into strings in the
WordPress.WP.PreparedSQLandWordPress.VIP.ValidatedSanitizedInputsniffs. - False positives in
WordPress.PHP.YodaConditionswhen the variable is being casted. $wpdbproperties being flagged inWordPress.WP.PreparedSQLsniff.- False positive in
WordPress.PHP.YodaConditionswhen the a string is on the left side of the comparison.
0.8.0 - 2015-10-02
implode()andjoin()to the list of formatting functions in theWordPress.XSS.EscapeOutputsniff. This is useful when you need to have HTML in the$glueparameter.- Support in the
WordPress.XSS.EscapeOutputsniff for escaping an array of values usingarray_map(). (Otherwise the support forimplode()isn't of much use :) - Docs for running WPCS in Sublime Text.
nl2br()to the list of formatting functions.wp_dropdown_pages()to the list of printing functions.- Error codes to all error/warning messages.
WordPress.WP.PreparedSQLsniff for flagging unprepared SQL queries.
- Sniffing for the number of spaces before a closure's opening parenthesis from the
default configuration of the
WordPress.WhiteSpace.ControlStructureSpacingsniff. It can be re-enabled per-project as desired.
- The
WordPress.XSS.EscapeOutputsniff giving error messages with the closing parenthesis in them instead of the offending function's name.
0.7.1 - 2015-08-31
- The default number of spaces before a closure's opening parenthesis from 1 to 0.
0.7.0 - 2015-08-30
- Automatic error fixing to the
WordPress.Arrays.ArrayKeySpacingRestrictionssniff. - Functions and closures to the control structures checked by the
WordPress.WhiteSpace.ControlStructureSpacingsniff. - Sniffing and fixing for extra spacing in the
WordPress.WhiteSpace.ControlStructureSpacingsniff. (Previously it only checked for insufficient spacing.) .twigfiles to the default ignored files.esc_url_raw()andhash_equals()to the list of sanitizing functions.intval()andboolval()to list of unslashing functions.do_shortcode()to the list of auto-escaped functions.
WordPress.Functions.FunctionDeclarationArgumentSpacingin favor of the upstream sniffSquiz.Functions.FunctionDeclarationArgumentSpacing.
- Reference to incorrect issue in the inline docs of the
WordPress.VIP.SessionVariableUsagesniff. WordPress.XSS.EscapeOutputsniff incorrectly handling ternary conditions inechostatements without parentheses in some cases.
0.6.0 - 2015-06-30
- Support for
wp_cache_add()andwp_cache_delete(), as well as custom cache functions,in theWordPress.VIP.DirectDatabaseQuerysniff.
WordPress.Functions.FunctionRestrictionsandWordPress.Variables.VariableRestrictionsfrom theWordPress-VIPstandard, since they are just parents for other sniffs.
0.5.0 - 2015-06-01
WordPress.CSRF.NonceVerificationsniff to flag form processing without nonce verification.in_array()andis_array()to the list of sanitizing functions.- Support for automatic error fixing to the
WordPress.Arrays.ArrayDeclarationsniff. WordPress.PHP.StrictComparisonsto theWordPress-VIPandWordPress-Extrarulesets.WordPress-Docsruleset to sniff for proper commenting.Generic.PHP.LowerCaseKeyword,Generic.Files.EndFileNewline,Generic.Files.LowercasedFilename,Generic.Formatting.SpaceAfterCast, andGeneric.Functions.OpeningFunctionBraceKernighanRitchieto theWordPress-Coreruleset.Generic.PHP.DeprecatedFunctions,Generic.PHP.ForbiddenFunctions,Generic.Functions.CallTimePassByReference,Generic.Formatting.DisallowMultipleStatements,Generic.CodeAnalysis.EmptyStatement,Generic.CodeAnalysis.ForLoopShouldBeWhileLoop,Generic.CodeAnalysis.ForLoopWithTestFunctionCall,Generic.CodeAnalysis.JumbledIncrementer,Generic.CodeAnalysis.UnconditionalIfStatement,Generic.CodeAnalysis.UnnecessaryFinalModifier,Generic.CodeAnalysis.UselessOverridingMethod,Generic.Classes.DuplicateClassName, andGeneric.Strings.UnnecessaryStringConcatto theWordPress-Extraruleset.- Error for missing use of
wp_unslash()on superglobal data to theWordPress.VIP.ValidatedSanitizedInputsniff.
- The
WordPress.VIP.ValidatedSanitizedInputsniff to require sanitization of input even when it is being directly escaped and output. - The minimum required PHP_CodeSniffer version to 2.2.0.
- The
WordPress.VIP.ValidatedSanitizedInputandWordPress.XSS.EscapeOutputsniffs: the list of escaping functions was split from the list of sanitizing functions. ThecustomSanitizingFunctionsproperty has been moved to theValidatedSanitizedInputsniff, and thecustomEscapingFunctionsproperty should now be used instead for theEscapeOutputsniff. - The
WordPress.Arrays.ArrayDeclarationsniff to give errors forNoSpaceAfterOpenParenthesis,SpaceAfterArrayOpener, andSpaceAfterArrayCloser, instead of warnings. - The
WordPress.NamingConventions.ValidFunctionNamesniff to allow camelCase method names in classes that implement interfaces.
- The
WordPress.VIP.ValidatedSanitizedInputsniff not reporting missing validation when reporting missing sanitization. - The
WordPress.VIP.ValidatedSanitizedInputsniff flagging superglobals as needing sanitization when they were only being used in a comparison usingiforswitch, etc.
0.4.0 - 2015-05-01
- Change log file.
- Handling for string-interpolated input variables in the
WordPress.VIP.ValidatedSanitizedInputsniff. - Errors for using uncached functions when cached equivalents exist.
space_before_colonsetting for theWordPress.WhiteSpace.ControlStructureSpacingsniff, for control structures using alternative syntax. Possible values:'required','optional','forbidden'.- Support for
sanitizationwhitelisting comments for theWordPress.VIP.ValidatedSanitizedInputsniff. - Granular error/warning names for all errors and warnings.
- Handling for ternary conditions in the
WordPress.XSS.EscapeOutputsniff. die,exit,printf,vprintf,wp_die,_deprecated_argument,_deprecated_function,_deprecated_file,_doing_it_wrong,trigger_error, anduser_errorto the list of printing functions in theWordPress.XSS.EscapeOutputsniff.customPrintingFunctionssetting for theWordPress.XSS.EscapeOutputsniff.rawurlencode()andwp_parse_id_list()to the list of "sanitizing" functions in theWordPress.XSS.EscapeOutputsniff.json_encode()to the list of discouraged functions in theWordPress.PHP.DiscouragedFunctionssniff, in favor ofwp_json_encode().vip_powered_wpcom()to the list of auto-escaped functions in theWordPress.XSS.EscapeOutputsniff.debug_print_backtrace()andvar_export()to the list of discouraged functions in theWordPress.PHP.DiscouragedFunctionssniff.- Smart handling for formatting functions (
sprintf()andwp_sprintf()) in theWordPress.XSS.EscapeOutputsniff. WordPress.PHP.StrictComparisonssniff.- Correct handling of
array_map()in theWordPress.VIP.ValidatedSanitizedInputsniff. $_COOKIEand$_FILEto the list of superglobals flagged by theWordPress.VIP.ValidatedSanitizedInputandWordPress.VIP.SuperGlobalInputUsagesniffs.$_SERVERto the list of superglobals flagged by theWordPress.VIP.SuperGlobalInputUsagesniff.Squiz.ControlStructures.ControlSignaturesniff to the rulesets.
WordPress.Arrays.ArrayKeySpacingRestrictionssniff to give errors forNoSpacesAroundArrayKeysandSpacesAroundArrayKeysinstead of just warnings.WordPress.NamingConventions.ValidFunctionNamesniff to allow for camel caps method names in child classes.WordPress.XSS.EscapeOutputsniff to allow for integers (e.g.echo 5andprint( -1 )).
- Errors for mixed key/keyless array elements in the
WordPress.Arrays.ArrayDeclarationsniff. - BOM from
WordPress.WhiteSpace.OperatorSpacingsniff file. $content_widthfrom the list of non-overwritable globals in theWordPress.Variables.GlobalVariablessniff.WordPress.Arrays.ArrayAssignmentRestrictionssniff from theWordPress-VIPruleset.
- Incorrect errors for
elsestatements using alternative syntax. WordPress.VIP.ValidatedSanitizedInputsniff not always treating casting as sanitization.WordPress.XSS.EscapeOutputsniff flagging comments as needing to be escaped.WordPress.XSS.EscapeOutputsniff not sniffing comma-delimitedechoarguments after encountering the first escaping function in the statement.WordPress.PHP.YodaConditionssniff not flagging comparisons to constants or function calls.WordPress.Arrays.ArrayDeclarationsniff not ignoring doc comments.- Link to phpStorm instructions in
README.md. - Poor performance of the
WordPress.Arrays.ArrayAssignmentRestrictionssniff. - Poor performance of the
WordPress.Files.FileNamesniff.
0.3.0 - 2014-12-11
See the comparison for full list.
- Use semantic version tags for releases.
See the comparison for full list.
Initial tagged release.