phpcsstandards/phpcsextra
PHPCSExtra adds extra rules, sniffs, and tooling to enhance PHP_CodeSniffer code style checks. Designed to complement existing standards, it helps catch more issues, enforce consistency, and integrate smoothly into CI for cleaner PHP codebases.
Universal.Attributes.BracketSpacing sniff to enforce a fixed number of spaces on the inside of attribute block brackets. #386, #406
The sniff offers the following properties to influence its behaviour:
spacing (defaults to 0).ignoreNewlines (defaults to false).
When new lines are allowed (ignoreNewlines=true) and a new line is found, the sniff will verify that there are no superfluous blank lines at the start/end of an attribute block.Universal.Attributes.DisallowAttributeParentheses sniff to forbid parentheses for attribute instantiations without arguments. #387, #409Universal.Attributes.RequireAttributeParentheses sniff to demand that all attribute instantiations always use parentheses, even if no argument is passed. #387, #410Universal.Attributes.TrailingComma sniff to demand a trailing comma for multi-line, multi-attribute attribute blocks and forbid trailing commas in single-line attribute blocks and in multi-line attributes containing only a single attribute. #397, #413Universal.PHP.DisallowExitDieParentheses sniff to forbid invocations of exit/die with parentheses when no argument is passed. #399Universal.PHP.RequireExitDieParentheses sniff to demand that invocations of exit/die always use parentheses, even if no argument is passed. #398Universal.WhiteSpace.FirstClassCallableSpacing sniff to enforce consistent spacing around the ellipses for first class callables. #385
The sniff offers the following property to influence its behaviour: spacing (defaults to 0).Universal.WhiteSpace.CommaSpacing: improved handling of commas in PHP attributes. #391, #412
*InAttributeBlock error code suffix, so in-/excluding them selectively is more straight-forward.
Note: spacing around commas between parameters passed to an attribute will still be reported with the *InFunctionCall error code suffix, same as before.Universal.OOStructures.AlphabeticExtendsImplements incorrectly displayed the "expected" and "found" names. #378Universal.WhiteSpace.CommaSpacing could accidentally cause a fatal error if the content adjacent to the comma was a text string containing percentage signs. Thanks [@westonruter] for reporting! #400, #401Universal.PHP.NoFQNTrueFalseNull: fix breakage due to upstream change in tokenization. #3754.x branch in anticipation of the PHP_CodeSniffer 4.0 release. #367
PHPCSExtra should now be fully compatible with PHP_CodeSniffer 4.0. If you still find an issue, please report it.PHP_CodeSniffer requirement has been updated to ^3.13.0 (was ^3.12.1). #361PHPCSUtils requirement has been updated to ^1.1.0 (was ^1.0.12). #361Universal.WhiteSpace.PrecisionAlignment: support for scanning JS/CSS files via this sniff is now deprecated. #367Universal.Arrays.DuplicateArrayKey: false positives for numeric strings with leading/trailing underscores. Fixed via the update to PHPCSUtils 1.1.0. #363Universal.Arrays.DuplicateArrayKey: false negatives for fully qualified true/false/null arrays keys. Fixed via the update to PHPCSUtils 1.1.0. #363Universal.WhiteSpace.CommaSpacing: wrong errorcode for comma's in closure use statements after the update to PHPCSUtils 1.1.0. #362PHPCSUtils requirement has been updated to ^1.0.12 (was ^1.0.9). #346Universal.UseStatements.DisallowMixedGroupUse: the fixer could get confused when the "base" name for the group name contained a leading backslash, leading to parse errors in the fixed code. #350Universal.PHP.NoFQNTrueFalseNull sniff to forbid using true, false and null as fully qualified constants. Thanks [@rodrigoprimo] for reviewing. #327Universal.Operators.TypeSeparatorSpacing: support for checking the spacing around the parentheses used in PHP 8.2+ DNF types. #329Universal.WhiteSpace.DisallowInlineTabs sniff will now also check for inline tabs in heredoc/nowdoc openers and between the yield and from keywords. #320PHP_CodeSniffer requirement has been updated to ^3.8.0 (was ^3.7.2). #298PHPCSUtils requirement has been updated to ^1.0.9 (was ^1.0.8). #298Please ensure you run composer update phpcsstandards/phpcsextra --with-dependencies to benefit from this.
Universal.CodeAnalysis.NoDoubleNegative sniff to detect double negatives (!!) and advise to use a boolean cast instead. Thanks [@diedexx] for reviewing. #277Universal.Operators.ConcatPosition sniff to enforce that the concatenation operator for multi-line concatenations is in a preferred position, either always at the start of the next line or always at the end of the previous line. #294Universal.PHP.LowercasePHPTag sniff to enforce that the "PHP" in a PHP open tag is lowercase. Thanks [@fredden] for reviewing. #276NormalizedArrays.Arrays.CommaAfterLast: the sniff now has two extra error codes to distinguish between multi-line arrays with the last array item on the same line as the array closer vs the last array item being on a line before the array closer. Thanks [@stronk7] for suggesting and patching this. #283, #284
These new error codes allow for selectively excluding that specific situation from triggering the sniff.
The new error codes are FoundMultiLineCloserSameLine (for multiLine="forbid") and MissingMultiLineCloserSameLine (for multiLine="enforce").
The pre-existing FoundMultiLine and FoundSingleLine error codes continue to be used for multi-line arrays with the last array item on a different line than the array closer.Universal.CodeAnalysis.ConstructorDestructorReturn: the sniff will now correctly ignore methods mirroring the class name (PHP-4 style constructors) in namespaced code. [#207], #272Modernize.FunctionCalls.Dirname: the sniff will now respect a potentially set [php_version configuration option][php_version-config] and only report on modernizations which are possible on the configured php_version. #261
If the php_version is not set, the sniff will continue to report on all modernization options.Universal.CodeAnalysis.NoEchoSprintf sniff to detect use of the inefficient echo [v]sprintf(...); combi and recommends using [v]printf() instead. #242Universal.FunctionDeclarations.NoLongClosures sniff to detect "long" closures and recommend using a named function instead. #240
The sniff offers the following properties to influence its behaviour: recommendedLines (defaults to 5), maxLines (defaults to 8), ignoreCommentLines (defaults to true) and ignoreEmptyLines (defaults to true).Universal.FunctionDeclarations.RequireFinalMethodsInTraits sniff to enforce non-private, non-abstract methods in traits to be declared as final. #243, #245
There is a separate NonFinalMagicMethodFound error code for magic methods to allow those to be excluded from the check.Universal.UseStatements.DisallowMixedGroupUse sniff to disallow group use statements which import a combination of namespace/OO construct, functions and/or constants in one statement. #241, #246
Note: the fixer will use a semi-standardized format for group use statements. If there are more specific requirements for the formatting of group use statements, the ruleset configurator should ensure that additional sniffs are included in the ruleset to enforce the required format.Universal.UseStatements.KeywordSpacing sniff to enforce the use of a single space after the use, function, const keywords and both before and after the as keyword in import use statements. #247
The sniff has modular error codes to allow for disabling individual checks.Universal.UseStatements.NoUselessAliases sniff to detect useless aliases (aliasing something to its original name) in import use statements. #244
Note: as OO and function names in PHP are case-insensitive, aliasing to the same name, using a different case is also considered useless.Universal.WhiteSpace.CommaSpacing sniff to enforce that there is no space before a comma and exactly one space, or a new line, after a comma. #254
Additionally, the sniff also enforces that the comma should follow the code and not be placed after a trailing comment.
The sniff has modular error codes to allow for disabling individual checks and checks in certain contexts.
The sniff will respect a potentially set [php_version configuration option][php_version-config] when deciding how to handle the spacing after a heredoc/nowdoc closer.Universal.Arrays.DuplicateArrayKey and the Universal.CodeAnalysis.ConstructorDestructorReturn sniffs. #251, #252:warning: Important: this package now requires PHPCSUtils 1.0.0. Please make sure you use --with-[all-]dependencies when running composer update. :exclamation:
For the full list of features, please see the changelogs of the alpha/rc releases:
Modernize.FunctionCalls.Dirname: the sniff will now correctly recognize magic constants in a case-insensitive manner. #187:warning: Important: this package now requires PHPCSUtils 1.0.0-alpha4. Please make sure you use --with-[all-]dependencies when running composer update. :exclamation:
Modernize.FunctionCalls.Dirname sniff to detect and auto-fix two typical code modernizations which can be made related to the dirname() function. #172Universal.Classes.DisallowAnonClassParentheses sniff to disallow the use of parentheses when declaring an anonymous class without passing parameters. #76, #162Universal.Classes.RequireAnonClassParentheses sniff to require the use of parentheses when declaring an anonymous class, whether parameters are passed or not. #76, #166Universal.Classes.DisallowFinalClass sniff to disallow classes being declared final. #108, #114, #148, #163Universal.Classes.RequireFinalClass sniff to require all non-abstract classes to be declared final. #109, #148, #164
Warning: the auto-fixer for this sniff may have unintended side-effects for applications and should be used with care! This is considered a risky fixer.Universal.Classes.ModifierKeywordOrder sniff to standardize the modifier keyword order for class declarations. #142
The sniff offers an order property to specify the preferred order.Universal.CodeAnalysis.ConstructorDestructorReturn sniff to verify that class constructor/destructor methods 1) do not have a return type declaration and 2) do not return a value. #137, #140, #146 Inspired by [@derickr].Universal.CodeAnalysis.ForeachUniqueAssignment sniff to detect foreach control structures which use the same variable for both the key as well as the value assignment as this will lead to unexpected - and most likely unintended - behaviour. #110, #175
The fixer will maintain the existing behaviour of the code. Mind: this may not be the intended behaviour.Universal.CodeAnalysis.StaticInFinalClass sniff to detect using static instead of self in OO constructs which are final. #116, #180
The sniff has modular error codes to allow for making exceptions based on the type of use for static.Universal.Constants.LowercaseClassResolutionKeyword sniff to enforce that the class keyword when used for class name resolution, i.e. ::class, is in lowercase. #72Universal.Constants.ModifierKeywordOrder sniff to standardize the modifier keyword order for OO constant declarations. #143
The sniff offers an order property to specify the preferred order.Universal.ControlStructures.DisallowLonelyIf sniff to disallow if statements as the only statement in an else block. #85, #168, #169
Inspired by the ESLint "no lonely if" rule.
Note: This sniff will not fix the indentation of the "inner" code. It is strongly recommended to run this sniff together with the Generic.WhiteSpace.ScopeIndent sniff to get the correct indentation.Universal.Files.SeparateFunctionsFromOO sniff to enforce that a file should either declare (global/namespaced) functions or declare OO structures, but not both. #95, #170, #171
Nested function declarations, i.e. functions declared within a function/method will be disregarded for the purposes of this sniff.
The same goes for anonymous classes, closures and arrow functions.Universal.NamingConventions.NoReservedKeywordParameterNames sniff to verify that function parameters do not use reserved keywords as names, as this can quickly become confusing when people use them in function calls using named parameters. #80, #81, #106, #107, #173
The sniff has modular error codes to allow for making exceptions for specific keywords.Universal.Operators.TypeSeparatorSpacing sniff to enforce no spaces around union type and intersection type separators. #117Universal.PHP.OneStatementInShortEchoTag sniff to disallow short open echo tags <?= containing more than one PHP statement. #89, #147, #165Universal.WhiteSpace.AnonClassKeywordSpacing sniff to standardize the amount of spacing between the class keyword and the open parenthesis (if any) for anonymous class declarations. #120
The sniff offers a spacing property to set the amount of spaces the sniff should check for.Universal.WhiteSpace.PrecisionAlignment sniff to enforce indentation to always be a multiple of a tabstop, i.e. disallow precision alignment. #119, #122, #123, #124
Note:
Generic.WhiteSpace.DisallowTabIndent or the Generic.WhiteSpace.DisallowSpaceIndent sniff.tab-width is set and either don't set the $indent property or set it to the tab-width (or a multiple thereof).Generic.WhiteSpace.ScopeIndent sniff for more precise indentation fixes.indent: the indent used for the codebase.ignoreAlignmentBefore: allows for providing a list of token names for which (preceding) precision alignment should be ignored.ignoreBlankLines: whether or not potential trailing whitespace on otherwise blank lines should be examined or ignored.Universal.Arrays.DisallowShortArraySyntax: the sniff will now record metrics about long vs short array usage. #154Universal.Arrays.DuplicateArrayKey: where relevant, the sniff will now make a distinction between keys which will be duplicate in all PHP version and (numeric) keys which will only be a duplicate key in PHP < 8.0 or PHP >= 8.0. #177, #178
If a [php_version configuration option][php_version-config] has been passed to PHPCS, it will be respected by the sniff and only report duplicate keys for the configured PHP version.Universal.ControlStructures.DisallowAlternativeSyntax: the sniff will now also record a metric when single-line (no body) control structures are encountered. #158Universal.ControlStructures.DisallowAlternativeSyntax: the error message thrown by the sniff is now more descriptive. #159Universal.ControlStructures.DisallowAlternativeSyntax: metrics will no longer be recorded for elseif and else keywords, but only on the if keyword as the type of syntax used has to be the same for the whole "chain". #161Universal.Lists.DisallowLongListSyntax: the sniff will no longer record (incomplete) metrics about long vs short list usage. #155Universal.Lists.DisallowShortListSyntax: the sniff will now record (complete) metrics about long vs short list usage. #155Universal.OOStructures.AlphabeticExtendsImplements: documented support for enum ... implements. #150Universal.UseStatements.DisallowUseClass: updated error message and metric name to take PHP 8.1 enums into account. #149Universal.UseStatements.NoLeadingBackslash: the sniff will now also flag and auto-fix leading backslashes in group use statements. #167PHP_CodeSniffer requirement has been updated to ^3.7.1 (was ^3.3.1). #115, #130abstract classes in this package are now final. #121The upgrade to PHPCSUtils 1.0.0-alpha4 took care of a number of bugs, which potentially could have affected sniffs in this package.
NormalizedArrays.Arrays.ArrayBraceSpacing: the sniff now allows for trailing comments after the array opener in multi-line arrays. #118NormalizedArrays.Arrays.ArrayBraceSpacing: trailing comments at the end of an array, but before the closer, in multi-line arrays will no longer confuse the sniff. #135NormalizedArrays.Arrays.CommaAfterLast: the fixer will now recognize PHP 7.3+ flexible heredoc/nowdocs and in that case, will add the comma on the same line as the heredoc/nowdoc closer. #144Universal.Arrays.DisallowShortArraySyntax: nested short arrays in short lists will now be detected and fixed correctly. #153Universal.ControlStructures.DisallowAlternativeSyntax: the sniff will no longer bow out indiscriminately when the allowWithInlineHTML property is set to true. #90, #161Universal.ControlStructures.DisallowAlternativeSyntax: when alternative control structure syntax is allowed in combination with inline HTML (allowWithInlineHTML property set to true), inline HTML in functions declared within the control structure body will no longer be taken into account for determining whether or not the control structure contains inline HTML. #160Universal.Lists.DisallowShortListSyntax: the sniff will work around a tokenizer bug in PHPCS 3.7.1, which previously could lead to false negatives. #151.Universal.Lists.DisallowShortListSyntax: nested short lists in short arrays will now be detected and fixed correctly. #152Universal.Operators.DisallowStandalonePostIncrementDecrement: the sniff will now correctly recognize stand-alone statements which end on a PHP close tag. #176Universal.Arrays.DisallowShortArraySyntax sniff to disallow short array syntax. #40
In contrast to the PHPCS native Generic.Arrays.DisallowShortArraySyntax sniff, this sniff will ignore short list syntax and not cause parse errors when the fixer is used.Universal.Constants.UppercaseMagicConstants sniff to enforce that PHP native magic constants are in uppercase. #64Universal.Namespaces.DisallowDeclarationWithoutName sniff to disallow namespace declarations without a namespace name. #50Universal.Operators.DisallowLogicalAndOr sniff to enforce the use of the boolean && and || operators instead of the logical and/or operators. #52
Note: as the operator precedence of the logical operators is significantly lower than the operator precedence of boolean operators, this sniff does not contain an auto-fixer.Universal.Operators.DisallowShortTernary sniff to disallow the use of short ternaries ?:. #42
While short ternaries are useful when used correctly, the principle of them is often misunderstood and they are more often than not used incorrectly, leading to hard to debug issues and/or PHP warnings/notices.Universal.Operators.DisallowStandalonePostIncrementDecrement sniff disallow the use of post-in/decrements in stand-alone statements and discourage the use of multiple increment/decrement operators in a stand-alone statement. #65Universal.Operators.StrictComparisons sniff to enforce the use of strict comparisons. #48
Warning: the auto-fixer for this sniff may cause bugs in applications and should be used with care! This is considered a risky fixer.Universal.OOStructures.AlphabeticExtendsImplements sniff to verify that the names used in a class "implements" statement or an interface "extends" statement are listed in alphabetic order. #55
orderby property to determine the sort order to use for the statement.
If all names used are unqualified, the sort order won't make a difference.
However, if one or more of the names are partially or fully qualified, the chosen sort order will determine how the sorting between unqualified, partially and fully qualified names is handled.
The sniff supports two sort order options:
ImplementsWrongOrder - for "class implements" statements.ImplementsWrongOrderWithComments - for "class implements" statements interlaced with comments. These will not be auto-fixed.ExtendsWrongOrder - for "interface extends" statements.ExtendsWrongOrderWithComments - for "interface extends" statements interlaced with comments. These will not be auto-fixed.implements/extends statement will not be maintained.
The fixer will separate each name with a comma and one space.
If alternative formatting is desired, a sniff which will check and fix the formatting should be added to the ruleset.Universal.UseStatements.LowercaseFunctionConst sniff to enforce that function and const keywords when used in an import use statement are always lowercase. #58Universal.UseStatements.NoLeadingBackslash sniff to verify that a name being imported in an import use statement does not start with a leading backslash. #46
Names in import use statements should always be fully qualified, so a leading backslash is not needed and it is strongly recommended not to use one.
This sniff handles all types of import use statements supported by PHP, in contrast to other sniffs for the same in, for instance, the PSR12 or the Slevomat standard, which are incomplete.Universal.WhiteSpace.DisallowInlineTabs sniff to enforce using spaces for mid-line alignment. #43master branch has been renamed to stable.Universal.ControlStructures.DisallowAlternativeSyntax sniff to disallow using the alternative syntax for control structures. #23
allowWithInlineHTML property to allow alternative syntax when inline HTML is used within the control structure. In all other cases, the use of the alternative syntax will still be disallowed.Universal.UseStatements.DisallowUseClass/Function/Const: new, additional metrics about the import source will be shown in the info report. #25Universal.Arrays.DuplicateArrayKey: wording of the error message. #18Universal.UseStatements.DisallowUseClass/Function/Const: the error codes have been made more modular. #25
Each of these sniffs now has four additional error codes:
--generator=text. #17Universal.Arrays.DuplicateArrayKey: improved handling of parse errors. #34Universal.ControlStructures.IfElseDeclaration: the fixer will now respect tab indentation. #19Universal.UseStatements.DisallowUseClass/Function/Const: the determination of whether a import is aliased in now done in a case-insensitive manner. #25Universal.UseStatements.DisallowUseClass/Function/Const: an import from the global namespace would previously always be seen as non-aliased, even when it was aliased. #25Universal.UseStatements.DisallowUseClass/Function/Const: improved tolerance for use import statements with leading backslashes. #25Initial alpha release containing:
NormalizedArrays standard which will contain a full set of sniffs to check the formatting of array declarations.Universal standard which will contain a collection of universally applicable sniffs.
DO NOT INCLUDE THIS AS A STANDARD.
Universal, like the upstream PHPCS Generic standard, contains sniffs which contradict each other.
Include individual sniffs from this standard in a custom project/company ruleset to use them.This initial alpha release contains the following sniffs:
NormalizedArrays.Arrays.ArrayBraceSpacing: enforce consistent spacing for the open/close braces of array declarations.
The sniff allows for having different settings for:
keywordSpacing property.
Accepted values: (int) number of spaces or false to turn this check off. Defaults to 0 spaces.spacesWhenEmpty property.
Accepted values: (string) newline, (int) number of spaces or false to turn this check off. Defaults to 0 spaces.spacesSingleLine property;
Accepted values: (int) number of spaces or false to turn this check off. Defaults to 0 spaces.spacesMultiLine property.
Accepted values: (string) newline, (int) number of spaces or false to turn this check off. Defaults to newline.
Note: if any of the above properties are set to newline, it is recommended to also include an array indentation sniff. This sniff will not handle the indentation.NormalizedArrays.Arrays.CommaAfterLast: enforce/forbid a comma after the last item in an array declaration.
By default, this sniff will:
Universal.Arrays.DuplicateArrayKey: detects duplicate array keys in array declarations.Universal.Arrays.MixedArrayKeyTypes: best practice sniff: don't use a mix of integer and numeric keys for array items.Universal.Arrays.MixedKeyedUnkeyedArray: best practice sniff: don't use a mix of keyed and unkeyed array items.Universal.ControlStructures.IfElseDeclaration: verify that else(if) statements with braces are on a new line.Universal.Lists.DisallowLongListSyntax: disallow the use of long lists.Universal.Lists.DisallowShortListSyntax: disallow the use of short lists.Universal.Namespaces.DisallowCurlyBraceSyntax: disallow the use of the alternative namespace declaration syntax using curly braces.Universal.Namespaces.EnforceCurlyBraceSyntax: enforce the use of the alternative namespace syntax using curly braces.Universal.Namespaces.OneDeclarationPerFile: disallow the use of multiple namespaces within a file.Universal.UseStatements.DisallowUseClass: forbid using import use statements for classes/traits/interfaces.
Individual sub-types can be allowed by excluding specific error codes.Universal.UseStatements.DisallowUseConst: forbid using import use statements for constants.
Individual sub-types can be allowed by excluding specific error codes.Universal.UseStatements.DisallowUseFunction: forbid using import use statements for functions.
Individual sub-types can be allowed by excluding specific error codes.[@anomiex]: https://github.com/anomiex [@derickr]: https://github.com/derickr [@diedexx]: https://github.com/diedexx [@fredden]: https://github.com/fredden [@GaryJones]: https://github.com/GaryJones [@rodrigoprimo]: https://github.com/rodrigoprimo [@stronk7]: https://github.com/stronk7 [@szepeviktor]: https://github.com/szepeviktor [@westonruter]: https://github.com/westonruter
How can I help you explore Laravel packages today?