Slevomat Coding Standard
Slevomat Coding Standard for PHP_CodeSniffer provides sniffs that fall into three categories:
- Functional - improving the safety and behaviour of code
- Cleaning - detecting dead code
- Formatting - rules for consistent code looks
Table of contents
- Functional - improving the safety and behaviour of code
- Cleaning - detecting dead code
- Formatting - rules for consistent code looks
Sniffs included in this standard
Functional - improving the safety and behaviour of code
🔧 🚧
SlevomatCodingStandard.TypeHints.ParameterTypeHint - Checks for missing parameter typehints in case they can be declared natively. If the phpDoc contains something that can be written as a native PHP 7.0+ typehint, this sniff reports that.
- Checks for useless
@param
annotations. If the native method declaration contains everything and the phpDoc does not add anything useful, it's reported as useless and can optionally be automatically removed withphpcbf
. - Forces to specify what's in traversable types like
array
,iterable
and\Traversable
.
Sniff provides the following settings:
enableObjectTypeHint
: enforces to transform@param object
into nativeobject
typehint. It's on by default if you're on PHP 7.2+enableMixedTypeHint
: enforces to transform@param mixed
into nativemixed
typehint. It's on by default if you're on PHP 8.0+traversableTypeHints
: enforces which typehints must have specified contained type. E. g. if you set this to\Doctrine\Common\Collections\Collection
, then\Doctrine\Common\Collections\Collection
must always be supplied with the contained type:\Doctrine\Common\Collections\Collection|Foo[]
.
This sniff can cause an error if you're overriding or implementing a parent method which does not have typehints. In such cases add @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
annotation to the method to have this sniff skip it.
🔧 🚧
SlevomatCodingStandard.TypeHints.PropertyTypeHint - Checks for missing property typehints in case they can be declared natively. If the phpDoc contains something that can be written as a native PHP 7.4+ typehint, this sniff reports that.
- Checks for useless
@var
annotations. If the native method declaration contains everything and the phpDoc does not add anything useful, it's reported as useless and can optionally be automatically removed withphpcbf
. - Forces to specify what's in traversable types like
array
,iterable
and\Traversable
.
Sniff provides the following settings:
enableNativeTypeHint
: enforces to transform@var int
into nativeint
typehint. It's on by default if you're on PHP 7.4+enableMixedTypeHint
: enforces to transform@var mixed
into nativemixed
typehint. It's on by default if you're on PHP 8.0+. It can be enabled only whenenableNativeTypeHint
is enabled too.enableUnionTypeHint
: enforces to transform@var string|int
into nativestring|int
typehint. It's on by default if you're on PHP 8.0+. It can be enabled only whenenableNativeTypeHint
is enabled too.traversableTypeHints
: enforces which typehints must have specified contained type. E. g. if you set this to\Doctrine\Common\Collections\Collection
, then\Doctrine\Common\Collections\Collection
must always be supplied with the contained type:\Doctrine\Common\Collections\Collection|Foo[]
.
This sniff can cause an error if you're overriding parent property which does not have typehints. In such cases add @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint
annotation to the property to have this sniff skip it.
🔧 🚧
SlevomatCodingStandard.TypeHints.ReturnTypeHint - Checks for missing return typehints in case they can be declared natively. If the phpDoc contains something that can be written as a native PHP 7.0+ typehint, this sniff reports that.
- Checks for useless
@return
annotations. If the native method declaration contains everything and the phpDoc does not add anything useful, it's reported as useless and can optionally be automatically removed withphpcbf
. - Forces to specify what's in traversable types like
array
,iterable
and\Traversable
.
Sniff provides the following settings:
enableObjectTypeHint
: enforces to transform@return object
into nativeobject
typehint. It's on by default if you're on PHP 7.2+enableStaticTypeHint
: enforces to transform@return static
into nativestatic
typehint. It's on by default if you're on PHP 8.0+enableMixedTypeHint
: enforces to transform@return mixed
into nativemixed
typehint. It's on by default if you're on PHP 8.0+enableUnionTypeHint
: enforces to transform@var string|int
into nativestring|int
typehint. It's on by default if you're on PHP 8.0+.traversableTypeHints
: enforces which typehints must have specified contained type. E. g. if you set this to\Doctrine\Common\Collections\Collection
, then\Doctrine\Common\Collections\Collection
must always be supplied with the contained type:\Doctrine\Common\Collections\Collection|Foo[]
.
This sniff can cause an error if you're overriding or implementing a parent method which does not have typehints. In such cases add @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint
annotation to the method to have this sniff skip it.
🔧
SlevomatCodingStandard.TypeHints.UselessConstantTypeHint Reports useless @var
annotation (or whole documentation comment) for constants because the type of constant is always clear.
🔧
SlevomatCodingStandard.TypeHints.UnionTypeHintFormat Checks format of union type hints.
Sniff provides the following settings:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 8.0 or higher.withSpaces
:yes
requires spaces arount|
,no
requires no space around|
. None is set by default so both is enabled.shortNullable
:yes
requires usage of?
for nullable type hint,no
disallows it. None is set by default so both are enabled.nullPosition
:first
requiresnull
on first position in the type hint,last
requires last position. None is set by default sonull
can be everywhere.
🔧 🚧
SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly In PHP 7.0, a Throwable
interface was added that allows catching and handling errors in more cases than Exception
previously allowed. So, if the catch statement contained Exception
on PHP 5.x, it means it should probably be rewritten to reference Throwable
on PHP 7.x. This sniff enforces that.
🔧 🚧
SlevomatCodingStandard.Exceptions.RequireNonCapturingCatch Sniff provides the following settings:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 8.0 or higher.
It requires non-capturing catch when the variable with exception is not used.
🔧
SlevomatCodingStandard.TypeHints.DeclareStrictTypes Enforces having declare(strict_types = 1)
at the top of each PHP file. Allows configuring how many newlines should be between the <?php
opening tag and the declare
statement.
Sniff provides the following settings:
declareOnFirstLine
: requiresdeclare
on the first line right after<?php
linesCountBeforeDeclare
: allows to set 0 to N lines to be betweendeclare
and previous statement. This option is ignored whendeclareOnFirstLine
is enabled.linesCountAfterDeclare
: allows to set 0 to N lines to be betweendeclare
and next statementspacesCountAroundEqualsSign
: allows to set number of required spaces around the=
operator
SlevomatCodingStandard.Arrays.DisallowImplicitArrayCreation
Disallows implicit array creation.
🔧
SlevomatCodingStandard.Classes.ClassStructure Checks that class/trait/interface members are in the correct order.
Sniff provides the following settings:
groups
: order of groups. Use multiple groups in one<element value="">
to not differentiate among them. You can use specific groups or shortcuts.enableFinalMethods
: enables groups forfinal
methods
List of supported groups: uses, public constants, protected constants, private constants, public properties, public static properties, protected properties, protected static properties, private properties, private static properties, constructor, static constructors, destructor, magic methods, public methods, protected methods, private methods, public final methods, public static final methods, protected final methods, protected static final methods, public abstract methods, public static abstract methods, protected abstract methods, protected static abstract methods, public static methods, protected static methods, private static methods, private methods
List of supported shortcuts: constants, properties, static properties, methods, all public methods, all protected methods, all private methods, static methods, final methods, abstract methods
<rule ref="SlevomatCodingStandard.Classes.ClassStructure">
<properties>
<property name="groups" type="array">
<element value="uses"/>
<!-- Public constants are first but you don't care about the order of protected or private constants -->
<element value="public constants"/>
<element value="constants"/>
<!-- You don't care about the order among the properties. The same can be done with "properties" shortcut -->
<element value="public properties, protected properties, private properties"/>
<!-- Constructor is first, then all public methods, then protected/private methods and magic methods are last -->
<element value="constructor"/>
<element value="all public methods"/>
<element value="methods"/>
<element value="magic methods"/>
</property>
</properties>
</rule>
SlevomatCodingStandard.Classes.DisallowConstructorPropertyPromotion
Disallows usage of constructor property promotion.
🔧
SlevomatCodingStandard.Classes.DisallowLateStaticBindingForConstants Disallows late static binding for constants.
SlevomatCodingStandard.Classes.ForbiddenPublicProperty
Disallows using public properties.
🔧
SlevomatCodingStandard.Classes.RequireConstructorPropertyPromotion Requires use of constructor property promotion.
This sniff provides the following setting:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 8.0 or higher.
🔧
SlevomatCodingStandard.Classes.UselessLateStaticBinding Reports useless late static binding.
SlevomatCodingStandard.ControlStructures.AssignmentInCondition
Disallows assignments in if
, elseif
and do-while
loop conditions:
if ($file = findFile($path)) {
}
Assignment in while
loop condition is specifically allowed because it's commonly used.
This is a great addition to already existing SlevomatCodingStandard.ControlStructures.DisallowYodaComparison
because it prevents the danger of assigning something by mistake instead of using comparison operator like ===
.
Sniff provides the following settings:
ignoreAssignmentsInsideFunctionCalls
: ignores assignment inside function calls, like this:
if (in_array(1, $haystack, $strict = true)) {
}
🔧
SlevomatCodingStandard.ControlStructures.DisallowContinueWithoutIntegerOperandInSwitch Disallows use of continue
without integer operand in switch
because it emits a warning in PHP 7.3 and higher.
SlevomatCodingStandard.ControlStructures.DisallowEmpty
Disallows use of empty()
.
🔧
SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator Requires use of null coalesce operator when possible.
🔧
SlevomatCodingStandard.ControlStructures.RequireNullCoalesceEqualOperator Requires use of null coalesce equal operator when possible.
This sniff provides the following setting:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 7.4 or higher.
🔧
SlevomatCodingStandard.ControlStructures.EarlyExit Requires use of early exit.
Sniff provides the following settings:
ignoreStandaloneIfInScope
: ignoresif
that is standalone in scope, like this:
foreach ($values as $value) {
if ($value) {
doSomething();
}
}
ignoreOneLineTrailingIf
: ignoresif
that has one line content and is on the last position in scope, like this:
foreach ($values as $value) {
$value .= 'whatever';
if ($value) {
doSomething();
}
}
ignoreTrailingIfWithOneInstruction
: ignoresif
that has only one instruction and is on the last position in scope, like this:
foreach ($values as $value) {
$value .= 'whatever';
if ($value) {
doSomething(function () {
// Anything
});
}
}
SlevomatCodingStandard.Functions.StrictCall
Some functions have $strict
parameter. This sniff reports calls to these functions without the parameter or with $strict = false
.
🔧
SlevomatCodingStandard.Functions.StaticClosure Reports closures not using $this
that are not declared static
.
SlevomatCodingStandard.Functions.FunctionLength
Disallows long functions. This sniff provides the following setting:
maxLinesLength
: specifies max allowed function lines length (default value is 20).
🔧
SlevomatCodingStandard.PHP.DisallowDirectMagicInvokeCall Disallows direct call of __invoke()
.
🔧
SlevomatCodingStandard.Operators.DisallowEqualOperators Disallows using loose ==
and !=
comparison operators. Use ===
and !==
instead, they are much more secure and predictable.
SlevomatCodingStandard.Operators.DisallowIncrementAndDecrementOperators
Disallows using ++
and --
operators.
SlevomatCodingStandard.Operators.RequireOnlyStandaloneIncrementAndDecrementOperators
Reports ++
and --
operators not used standalone.
🔧
SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator Requires using combined assignment operators, eg +=
, .=
etc.
Cleaning - detecting dead code
🔧
SlevomatCodingStandard.Functions.UnusedInheritedVariablePassedToClosure Looks for unused inherited variables passed to closure via use
.
🚧
SlevomatCodingStandard.Functions.UnusedParameter Looks for unused parameters.
🚧
SlevomatCodingStandard.Functions.UselessParameterDefaultValue Looks for useless parameter default value.
🔧
SlevomatCodingStandard.Namespaces.UnusedUses Looks for unused imports from other namespaces.
Sniff provides the following settings:
searchAnnotations
(defaults tofalse
): enables searching for class names in annotations.ignoredAnnotationNames
: case sensitive list of annotation names that the sniff should ignore (only the name is ignored, annotation content is still searched). Useful for name collisions like@testCase
annotation andTestCase
class.ignoredAnnotations
: case sensitive list of annotation names that the sniff ignore completely (both name and content are ignored). Useful for name collisions like@group Cache
annotation andCache
class.
🔧
SlevomatCodingStandard.Namespaces.UseFromSameNamespace Prohibits uses from the same namespace:
namespace Foo;
use Foo\Bar;
🔧
SlevomatCodingStandard.Namespaces.UselessAlias Looks for use
alias that is same as unqualified name.
SlevomatCodingStandard.PHP.DisallowReference
Disallows references.
🔧
SlevomatCodingStandard.PHP.ForbiddenClasses Reports usage of forbidden classes, interfaces, parent classes and traits. And provide the following settings:
forbiddenClasses
: forbids creating instances withnew
keyword or accessing with::
operatorforbiddenExtends
: forbids extending withextends
keywordforbiddenInterfaces
: forbids usage inimplements
sectionforbiddenTraits
: forbids imports withuse
keyword
Optionally can be passed as an alternative for auto fixes. See phpcs.xml
file example:
<rule ref="SlevomatCodingStandard.PHP.ForbiddenClasses">
<properties>
<property name="forbiddenClasses" type="array">
<element key="Validator" value="Illuminate\Support\Facades\Validator"/>
</property>
<property name="forbiddenTraits" type="array">
<element key="\AuthTrait" value="null"/>
</property>
</properties>
</rule>
🔧
SlevomatCodingStandard.PHP.RequireExplicitAssertion Requires assertion via assert
instead of inline documentation comments.
🔧
SlevomatCodingStandard.PHP.RequireNowdoc Requires nowdoc syntax instead of heredoc when possible.
🔧
SlevomatCodingStandard.PHP.UselessParentheses Looks for useless parentheses.
Sniff provides the following settings:
ignoreComplexTernaryConditions
(defaults tofalse
): ignores complex ternary conditions - condition must contain&&
,||
etc or end of line.
SlevomatCodingStandard.PHP.OptimizedFunctionsWithoutUnpacking
PHP optimizes some internal functions into special opcodes on VM level. Such optimization results in much faster execution compared to calling standard function. This only works when these functions are not invoked with argument unpacking (...
).
The list of these functions varies across PHP versions, but is the same as functions that must be referenced by their global name (either by \
prefix or using use function
), not a fallback name inside namespaced code.
🔧
SlevomatCodingStandard.PHP.UselessSemicolon Looks for useless semicolons.
SlevomatCodingStandard.Variables.DisallowSuperGlobalVariable
Disallows use of super global variables.
SlevomatCodingStandard.Variables.DuplicateAssignmentToVariable
Looks for duplicate assignments to a variable.
SlevomatCodingStandard.Variables.UnusedVariable
Looks for unused variables.
Sniff provides the following settings:
ignoreUnusedValuesWhenOnlyKeysAreUsedInForeach
(defaults tofalse
): ignore unused$value
in foreach when only$key
is used
foreach ($values as $key => $value) {
echo $key;
}
🔧
SlevomatCodingStandard.Variables.UselessVariable Looks for useless variables.
SlevomatCodingStandard.Exceptions.DeadCatch
This sniff finds unreachable catch blocks:
try {
doStuff();
} catch (\Throwable $e) {
log($e);
} catch (\InvalidArgumentException $e) {
// unreachable!
}
Formatting - rules for consistent code looks
🔧
SlevomatCodingStandard.Arrays.MultiLineArrayEndBracketPlacement Enforces reasonable end bracket placement for multi-line arrays.
🔧
SlevomatCodingStandard.Arrays.SingleLineArrayWhitespace Checks whitespace in single line array declarations (whitespace between brackets, around commas, ...).
Sniff provides the following settings:
spacesAroundBrackets
: number of spaces you require to have around array bracketsenableEmptyArrayCheck
(defaults tofalse
): enables check for empty arrays
🔧
SlevomatCodingStandard.Arrays.TrailingArrayComma Commas after last element in an array make adding a new element easier and result in a cleaner versioning diff.
This sniff enforces trailing commas in multi-line arrays and requires short array syntax []
.
Sniff provides the following settings:
enableAfterHeredoc
: enables/disables trailing commas after HEREDOC/NOWDOC, default based on PHP version.
🔧
SlevomatCodingStandard.Classes.ClassMemberSpacing Checks lines count between different class members, eg. between last property and first method.
Sniff provides the following settings:
linesCountBetweenMembers
: lines count between different class members
🔧
SlevomatCodingStandard.Classes.ConstantSpacing Checks that there is a certain number of blank lines between constants.
Sniff provides the following settings:
minLinesCountBeforeWithComment
: minimum number of lines before constant with a doc commentmaxLinesCountBeforeWithComment
: maximum number of lines before constant with a doc commentminLinesCountBeforeWithoutComment
: minimum number of lines before constant without a doc commentmaxLinesCountBeforeWithoutComment
: maximum number of lines before constant without a doc comment
🔧
SlevomatCodingStandard.Classes.DisallowMultiConstantDefinition Disallows multi constant definition.
🔧
SlevomatCodingStandard.Classes.DisallowMultiPropertyDefinition Disallows multi property definition.
🔧
SlevomatCodingStandard.Classes.MethodSpacing Checks that there is a certain number of blank lines between methods.
Sniff provides the following settings:
minLinesCount
: minimum number of blank linesmaxLinesCount
: maximum number of blank lines
🔧
SlevomatCodingStandard.Classes.ModernClassNameReference Reports use of __CLASS__
, get_parent_class()
, get_called_class()
, get_class()
and get_class($this)
.
Class names should be referenced via ::class
constant when possible.
Sniff provides the following settings:
enableOnObjects
: Enable::class
on all objects. It's on by default if you're on PHP 8.0+
🔧
SlevomatCodingStandard.Classes.ParentCallSpacing Enforces configurable number of lines around parent method call.
Sniff provides the following settings:
linesCountBefore
: allows to configure the number of lines before parent call.linesCountBeforeFirst
: allows to configure the number of lines before first parent call.linesCountAfter
: allows to configure the number of lines after parent call.linesCountAfterLast
: allows to configure the number of lines after last parent call.
🔧
SlevomatCodingStandard.Classes.PropertySpacing Checks that there is a certain number of blank lines between properties.
Sniff provides the following settings:
minLinesCountBeforeWithComment
: minimum number of lines before property with a doc commentmaxLinesCountBeforeWithComment
: maximum number of lines before property with a doc commentminLinesCountBeforeWithoutComment
: minimum number of lines before property without a doc commentmaxLinesCountBeforeWithoutComment
: maximum number of lines before property without a doc comment
🔧
SlevomatCodingStandard.Classes.RequireMultiLineMethodSignature Enforces method signature to be splitted to more lines so each parameter is on its own line.
Sniff provides the following settings:
-
minLineLength
: specifies min line length to enforce signature to be splitted. Use 0 value to enforce for all methods, regardless of length. -
includedMethodPatterns
: allows to configure which methods are included in sniff detection. This is an array of regular expressions (PCRE) with delimiters. You should not use this withexcludedMethodPatterns
, as it will not work properly. -
excludedMethodPatterns
: allows to configure which methods are excluded from sniff detection. This is an array of regular expressions (PCRE) with delimiters. You should not use this withincludedMethodPatterns
, as it will not work properly.
🔧
SlevomatCodingStandard.Classes.RequireSingleLineMethodSignature Enforces method signature to be on a single line.
Sniff provides the following settings:
-
maxLineLength
: specifies max allowed line length. If signature would fit on it, it's enforced. Use 0 value to enforce for all methods, regardless of length. -
includedMethodPatterns
: allows to configure which methods are included in sniff detection. This is an array of regular expressions (PCRE) with delimiters. You should not use this withexcludedMethodPatterns
, as it will not work properly. -
excludedMethodPatterns
: allows to configure which methods are excluded from sniff detection. This is an array of regular expressions (PCRE) with delimiters. You should not use this withincludedMethodPatterns
, as it will not work properly.
SlevomatCodingStandard.Classes.SuperfluousAbstractClassNaming
Reports use of superfluous prefix or suffix "Abstract" for abstract classes.
SlevomatCodingStandard.Classes.SuperfluousInterfaceNaming
Reports use of superfluous prefix or suffix "Interface" for interfaces.
SlevomatCodingStandard.Classes.SuperfluousExceptionNaming
Reports use of superfluous suffix "Exception" for exceptions.
SlevomatCodingStandard.Classes.SuperfluousErrorNaming
Reports use of superfluous suffix "Error" for errors.
SlevomatCodingStandard.Classes.SuperfluousTraitNaming
Reports use of superfluous suffix "Trait" for traits.
🔧
SlevomatCodingStandard.Classes.TraitUseDeclaration Prohibits multiple traits separated by commas in one use
statement.
🔧
SlevomatCodingStandard.Classes.TraitUseSpacing Enforces configurable number of lines before first use
, after last use
and between two use
statements.
Sniff provides the following settings:
linesCountBeforeFirstUse
: allows to configure the number of lines before firstuse
.linesCountBeforeFirstUseWhenFirstInClass
: allows to configure the number of lines before firstuse
when theuse
is the first statement in the class.linesCountBetweenUses
: allows to configure the number of lines between twouse
statements.linesCountAfterLastUse
: allows to configure the number of lines after lastuse
.linesCountAfterLastUseWhenLastInClass
: allows to configure the number of lines after lastuse
when theuse
is the last statement in the class.
🔧
SlevomatCodingStandard.ControlStructures.BlockControlStructureSpacing Enforces configurable number of lines around block control structures (if, foreach, ...).
Sniff provides the following settings:
linesCountBefore
: allows to configure the number of lines before control structure.linesCountBeforeFirst
: allows to configure the number of lines before first control structure.linesCountAfter
: allows to configure the number of lines after control structure.linesCountAfterLast
: allows to configure the number of lines after last control structure.controlStructures
: allows to narrow the list of checked control structures.
For example, with the following setting, only if
and switch
keywords are checked.
<rule ref="SlevomatCodingStandard.ControlStructures.BlockControlStructureSpacing">
<properties>
<property name="controlStructures" type="array">
<element value="if"/>
<element value="switch"/>
</property>
</properties>
</rule>
🔧
SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing Enforces configurable number of lines around jump statements (continue, return, ...).
Sniff provides the following settings:
allowSingleLineYieldStacking
: whether or not to allow multiple yield/yield from statements in a row without blank lines.linesCountBefore
: allows to configure the number of lines before jump statement.linesCountBeforeFirst
: allows to configure the number of lines before first jump statement.linesCountBeforeWhenFirstInCaseOrDefault
: allows to configure the number of lines before jump statement that is first incase
ordefault
linesCountAfter
: allows to configure the number of lines after jump statement.linesCountAfterLast
: allows to configure the number of lines after last jump statement.linesCountAfterWhenLastInCaseOrDefault
: allows to configure the number of lines after jump statement that is last incase
ordefault
linesCountAfterWhenLastInLastCaseOrDefault
: allows to configure the number of lines after jump statement that is last in lastcase
ordefault
jumpStatements
: allows to narrow the list of checked jump statements.
For example, with the following setting, only continue
and break
keywords are checked.
<rule ref="SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing">
<properties>
<property name="jumpStatements" type="array">
<element value="continue"/>
<element value="break"/>
</property>
</properties>
</rule>
🔧
SlevomatCodingStandard.ControlStructures.LanguageConstructWithParentheses LanguageConstructWithParenthesesSniff
checks and fixes language construct used with parentheses.
🔧
SlevomatCodingStandard.ControlStructures.NewWithParentheses Requires new
with parentheses.
🔧
SlevomatCodingStandard.ControlStructures.NewWithoutParentheses Reports new
with useless parentheses.
SlevomatCodingStandard.ControlStructures.DisallowNullSafeObjectOperator
Disallows using ?->
operator.
🔧
SlevomatCodingStandard.ControlStructures.DisallowShortTernaryOperator Disallows short ternary operator ?:
.
Sniff provides the following settings:
fixable
: the sniff is fixable by default, however in strict code it makes sense to forbid this weakly typed form of ternary altogether, you can disable fixability with this option.
🔧
SlevomatCodingStandard.ControlStructures.RequireMultiLineTernaryOperator Ternary operator has to be reformatted to more lines when the line length exceeds the given limit.
Sniff provides the following settings:
lineLengthLimit
(defaults to0
)minExpressionsLength
(defaults tonull
): when the expressions after?
are shorter than this length, the ternary operator does not has to be reformatted.
🔧
SlevomatCodingStandard.ControlStructures.RequireNullSafeObjectOperator Requires using ?->
operator.
Sniff provides the following settings:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 8.0 or higher.
🔧
SlevomatCodingStandard.ControlStructures.RequireSingleLineCondition Enforces conditions of if
, elseif
, while
and do-while
to be on a single line.
Sniff provides the following settings:
maxLineLength
: specifies max allowed line length. If conditition (and the rest of the line) would fit on it, it's enforced. Use 0 value to enforce for all conditions, regardless of length.alwaysForSimpleConditions
: allows to enforce single line for all simple conditions (i.e no&&
,||
orxor
), regardless of length.
🔧
SlevomatCodingStandard.ControlStructures.RequireMultiLineCondition Enforces conditions of if
, elseif
, while
and do-while
with one or more boolean operators to be splitted to more lines
so each condition part is on its own line.
Sniff provides the following settings:
minLineLength
: specifies mininum line length to enforce condition to be splitted. Use 0 value to enforce for all conditions, regardless of length.booleanOperatorOnPreviousLine
: boolean operator is placed at the end of previous line when fixing.alwaysSplitAllConditionParts
: require all condition parts to be on its own line - it reports error even if condition is already multi-line but there are some condition parts on the same line.
🔧
SlevomatCodingStandard.ControlStructures.RequireShortTernaryOperator Requires short ternary operator ?:
when possible.
🔧
SlevomatCodingStandard.ControlStructures.RequireTernaryOperator Requires ternary operator when possible.
Sniff provides the following settings:
ignoreMultiLine
(defaults tofalse
): ignores multi-line statements.
🔧
SlevomatCodingStandard.ControlStructures.DisallowYodaComparison/RequireYodaComparison Yoda conditions decrease code comprehensibility and readability by switching operands around comparison operators forcing the reader to read the code in an unnatural way.
Sniff provides the following settings:
alwaysVariableOnRight
(defaults tofalse
): moves variables always to right.
DisallowYodaComparisonSniff
looks for and fixes such comparisons not only in if
statements but in the whole code.
However, if you prefer Yoda conditions, you can use RequireYodaComparisonSniff
.
SlevomatCodingStandard.Files.LineLength
Enforces maximum length of a single line of code.
Sniff provides the following settings:
lineLengthLimit
: actual limit of the line lengthignoreComments
: whether or not to ignore line length of commentsignoreImports
: whether or not to ignore line length of import (use) statements
🔧
SlevomatCodingStandard.Functions.ArrowFunctionDeclaration Checks fn
declaration.
Sniff provides the following settings:
spacesCountAfterKeyword
: the number of spaces afterfn
.spacesCountBeforeArrow
: the number of spaces before=>
.spacesCountAfterArrow
: the number of spaces after=>
.allowMultiLine
: allows multi-line declaration.
SlevomatCodingStandard.Functions.DisallowEmptyFunction
Reports empty functions body and requires at least a comment inside.
SlevomatCodingStandard.Functions.DisallowArrowFunction
Disallows arrow functions.
🔧
SlevomatCodingStandard.Functions.RequireArrowFunction Requires arrow functions.
Sniff provides the following settings:
allowNested
(defaults totrue
)enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 7.4 or higher.
🔧
SlevomatCodingStandard.Functions.RequireMultiLineCall Enforces function call to be splitted to more lines so each parameter is on its own line.
Sniff provides the following settings:
minLineLength
: specifies min line length to enforce call to be splitted. Use 0 value to enforce for all calls, regardless of length.
🔧
SlevomatCodingStandard.Functions.RequireSingleLineCall Enforces function call to be on a single line.
Sniff provides the following settings:
maxLineLength
: specifies max allowed line length. If call would fit on it, it's enforced. Use 0 value to enforce for all calls, regardless of length.ignoreWithComplexParameter
(defaults totrue
): ignores calls with arrays, closures, arrow functions and nested calls.
SlevomatCodingStandard.Functions.DisallowNamedArguments
This sniff disallows usage of named arguments.
🔧
SlevomatCodingStandard.Functions.DisallowTrailingCommaInCall This sniff disallows trailing commas in multi-line calls.
🔧
SlevomatCodingStandard.Functions.RequireTrailingCommaInCall Commas after the last parameter in function or method call make adding a new parameter easier and result in a cleaner versioning diff.
This sniff enforces trailing commas in multi-line calls.
This sniff provides the following setting:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 7.3 or higher.
🔧
SlevomatCodingStandard.Functions.DisallowTrailingCommaInDeclaration This sniff disallows trailing commas in multi-line declarations.
🔧
SlevomatCodingStandard.Functions.RequireTrailingCommaInDeclaration Commas after the last parameter in function or method declaration make adding a new parameter easier and result in a cleaner versioning diff.
This sniff enforces trailing commas in multi-line declarations.
This sniff provides the following setting:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 8.0 or higher.
🔧
SlevomatCodingStandard.Namespaces.AlphabeticallySortedUses Checks whether uses at the top of a file are alphabetically sorted. Follows natural sorting and takes edge cases with special symbols into consideration. The following code snippet is an example of correctly sorted uses:
use LogableTrait;
use LogAware;
use LogFactory;
use LoggerInterface;
use LogLevel;
use LogStandard;
Sniff provides the following settings:
psr12Compatible
(defaults totrue
): sets the required order toclasses
,functions
andconstants
.false
sets the required order toclasses
,constants
andfunctions
.caseSensitive
: compare namespaces case sensitively, which makes this order correct:
use LogAware;
use LogFactory;
use LogLevel;
use LogStandard;
use LogableTrait;
use LoggerInterface;
SlevomatCodingStandard.Namespaces.RequireOneNamespaceInFile
Requires only one namespace in a file.
🔧
SlevomatCodingStandard.Namespaces.NamespaceDeclaration Enforces one space after namespace
, disallows content between namespace name and semicolon and disallows use of bracketed syntax.
🔧
SlevomatCodingStandard.Namespaces.NamespaceSpacing Enforces configurable number of lines before and after namespace
.
Sniff provides the following settings:
linesCountBeforeNamespace
: allows to configure the number of lines beforenamespace
.linesCountAfterNamespace
: allows to configure the number of lines afternamespace
.
🔧
SlevomatCodingStandard.Namespaces.UseSpacing Enforces configurable number of lines before first use
, after last use
and between two different types of use
(eg. between use function
and use const
). Also enforces zero number of lines between same types of use
.
Sniff provides the following settings:
linesCountBeforeFirstUse
: allows to configure the number of lines before firstuse
.linesCountBetweenUseTypes
: allows to configure the number of lines between two different types ofuse
.linesCountAfterLastUse
: allows to configure the number of lines after lastuse
.
🔧
SlevomatCodingStandard.Numbers.DisallowNumericLiteralSeparator Disallows numeric literal separators.
SlevomatCodingStandard.Numbers.RequireNumericLiteralSeparator
Requires use of numeric literal separators.
This sniff provides the following setting:
enable
: either to enable or not this sniff. By default, it is enabled for PHP versions 7.4 or higher.minDigitsBeforeDecimalPoint
: the mininum digits before decimal point to require separator.minDigitsAfterDecimalPoint
: the mininum digits after decimal point to require separator.
🔧
SlevomatCodingStandard.PHP.ReferenceSpacing Enforces configurable number of spaces after reference.
Sniff provides the following settings:
spacesCountAfterReference
: the number of spaces after&
.
🔧
SlevomatCodingStandard.Operators.NegationOperatorSpacing Checks if there is the same number of spaces after negation operator as expected.
Sniff provides the following settings:
spacesCount
: the number of spaces expected after the negation operator
🔧
SlevomatCodingStandard.Operators.SpreadOperatorSpacing Enforces configurable number of spaces after the ...
operator.
Sniff provides the following settings:
spacesCountAfterOperator
: the number of spaces after the...
operator.
🔧
SlevomatCodingStandard.TypeHints.DisallowArrayTypeHintSyntax Disallows usage of array type hint syntax (eg. int[]
, bool[][]
) in phpDocs in favour of generic type hint syntax (eg. array<int>
, array<array<bool>>
).
Sniff provides the following settings:
traversableTypeHints
: helps fixer detect traversable type hints so\Traversable|int[]
can be converted to\Traversable<int>
.
SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint
Disallows usage of "mixed" type hint in phpDocs.
🔧
SlevomatCodingStandard.TypeHints.LongTypeHints Enforces using shorthand scalar typehint variants in phpDocs: int
instead of integer
and bool
instead of boolean
. This is for consistency with native scalar typehints which also allow shorthand variants only.
🔧
SlevomatCodingStandard.TypeHints.NullTypeHintOnLastPosition Enforces null
type hint on last position in annotations.
🔧
SlevomatCodingStandard.PHP.ShortList Enforces using short form of list syntax, [...]
instead of list(...)
.
🔧
SlevomatCodingStandard.PHP.TypeCast Enforces using shorthand cast operators, forbids use of unset and binary cast operators: (bool)
instead of (boolean)
, (int)
instead of (integer)
, (float)
instead of (double)
or (real)
. (binary)
and (unset)
are forbidden.
🔧
SlevomatCodingStandard.Whitespaces.DuplicateSpaces Checks duplicate spaces anywhere because there aren't sniffs for every part of code to check formatting.
Sniff provides the following settings:
ignoreSpacesBeforeAssignment
: to allow multiple spaces to align assignments.ignoreSpacesInAnnotation
: to allow multiple spaces to align annotations.ignoreSpacesInComment
: to allow multiple spaces to align content of the comment.ignoreSpacesInParameters
: to allow multiple spaces to align parameters.
SlevomatCodingStandard.Files.TypeNameMatchesFileName
For projects not following the PSR-0 or PSR-4 autoloading standards, this sniff checks whether a namespace and a name of a class/interface/trait follows agreed-on way to organize code into directories and files.
Other than enforcing that the type name must match the name of the file it's contained in, this sniff is very configurable. Consider the following sample configuration:
<rule ref="SlevomatCodingStandard.Files.TypeNameMatchesFileName">
<properties>
<property name="rootNamespaces" type="array">
<element key="app/ui" value="Slevomat\UI"/>
<element key="app" value="Slevomat"/>
<element key="build/SlevomatSniffs/Sniffs" value="SlevomatSniffs\Sniffs"/>
<element key="tests/ui" value="Slevomat\UI"/>
<element key="tests" value="Slevomat"/>
</property>
<property name="skipDirs" type="array">
<element value="components"/>
<element value="forms"/>
<element value="model"/>
<element value="models"/>
<element value="services"/>
<element value="stubs"/>
<element value="data"/>
<element value="new"/>
</property>
<property name="ignoredNamespaces" type="array">
<element value="Slevomat\Services"/>
</property>
</properties>
</rule>
Sniff provides the following settings:
rootNamespaces
property expects configuration similar to PSR-4 - project directories mapped to certain namespaces.skipDirs
are not taken into consideration when comparing a path to a namespace. For example, with the above settings, file at pathapp/services/Product/Product.php
is expected to containSlevomat\Product\Product
, notSlevomat\services\Product\Product
.extensions
: allow different file extensions. Default isphp
.ignoredNamespaces
: sniff is not performed on these namespaces.
🔧
SlevomatCodingStandard.Classes.ClassConstantVisibility In PHP 7.1+ it's possible to declare visibility of class constants. In a similar vein to optional declaration of visibility for properties and methods which is actually required in sane coding standards, this sniff also requires declaring visibility for all class constants.
Sniff provides the following settings:
fixable
: the sniff is not fixable by default because we think it's better to decide about each constant one by one however you can enable fixability with this option.
const FOO = 1; // visibility missing!
public const BAR = 2; // correct
🔧
SlevomatCodingStandard.TypeHints.ReturnTypeHintSpacing Enforces consistent formatting of return typehints, like this:
function foo(): ?int
Sniff provides the following settings:
spacesCountBeforeColon
: the number of spaces expected between closing brace and colon.
🔧 🚧
SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue Checks whether the nullablity ?
symbol is present before each nullable and optional parameter (which are marked as = null
):
function foo(
int $foo = null, // ? missing
?int $bar = null // correct
) {
}
🔧
SlevomatCodingStandard.TypeHints.ParameterTypeHintSpacing - Checks that there's a single space between a typehint and a parameter name:
Foo $foo
- Checks that there's no whitespace between a nullability symbol and a typehint:
?Foo
🔧
SlevomatCodingStandard.TypeHints.PropertyTypeHintSpacing - Checks that there's a single space between a typehint and a property name:
Foo $foo
- Checks that there's no whitespace between a nullability symbol and a typehint:
?Foo
- Checks that there's a single space before nullability symbol or a typehint:
private ?Foo
orprivate Foo
SlevomatCodingStandard.Namespaces.DisallowGroupUse
Group use declarations are ugly, make diffs ugly and this sniff prohibits them.
🔧
SlevomatCodingStandard.Namespaces.FullyQualifiedExceptions This sniff reduces confusion in the following code snippet:
try {
$this->foo();
} catch (Exception $e) {
// Is this the general exception all exceptions must extend from? Or Exception from the current namespace?
}
All references to types named Exception
or ending with Exception
must be referenced via a fully qualified name:
try {
$this->foo();
} catch (\FooCurrentNamespace\Exception $e) {
} catch (\Exception $e) {
}
Sniff provides the following settings:
- Exceptions with different names can be configured in
specialExceptionNames
property. - If your codebase uses classes that look like exceptions (because they have
Exception
orError
suffixes) but aren't, you can add them toignoredNames
property and the sniff won't enforce them to be fully qualified. Classes withError
suffix has to be added to ignored only if they are in the root namespace (likeLibXMLError
).
🔧
SlevomatCodingStandard.Namespaces.FullyQualifiedGlobalConstants All references to global constants must be referenced via a fully qualified name.
Sniff provides the following settings:
include
: list of global constants that must be referenced via FQN. If not set all constants are considered.exclude
: list of global constants that are allowed not to be referenced via FQN.
🔧
SlevomatCodingStandard.Namespaces.FullyQualifiedGlobalFunctions All references to global functions must be referenced via a fully qualified name.
Sniff provides the following settings:
include
: list of global functions that must be referenced via FQN. If not set all functions are considered.includeSpecialFunctions
: include complete list of PHP internal functions that could be optimized when referenced via FQN.exclude
: list of global functions that are allowed not to be referenced via FQN.
SlevomatCodingStandard.Namespaces.MultipleUsesPerLine
Prohibits multiple uses separated by commas:
use Foo, Bar;
🔧
SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly Sniff provides the following settings:
searchAnnotations
(defaults tofalse
): enables searching for mentions in annotations.namespacesRequiredToUse
: if not set, all namespaces are required to be used. When set, only mentioned namespaces are required to be used. Useful in tandem with UseOnlyWhitelistedNamespaces sniff.allowFullyQualifiedExceptions
,specialExceptionNames
&ignoredNames
: allows fully qualified exceptions. Useful in tandem with FullyQualifiedExceptions sniff.allowFullyQualifiedNameForCollidingClasses
: allow fully qualified name for a class with a colliding use statement.allowFullyQualifiedNameForCollidingFunctions
: allow fully qualified name for a function with a colliding use statement.allowFullyQualifiedNameForCollidingConstants
: allow fully qualified name for a constant with a colliding use statement.allowFullyQualifiedGlobalClasses
: allows using fully qualified classes from global space (i.e.\DateTimeImmutable
).allowFullyQualifiedGlobalFunctions
: allows using fully qualified functions from global space (i.e.\phpversion()
).allowFullyQualifiedGlobalConstants
: allows using fully qualified constants from global space (i.e.\PHP_VERSION
).allowFallbackGlobalFunctions
: allows using global functions via fallback name withoutuse
(i.e.phpversion()
).allowFallbackGlobalConstants
: allows using global constants via fallback name withoutuse
(i.e.PHP_VERSION
).allowPartialUses
: allows using and referencing whole namespaces:
SlevomatCodingStandard.Namespaces.UseOnlyWhitelistedNamespaces
Disallows uses of other than configured namespaces.
Sniff provides the following settings:
namespacesRequiredToUse
: namespaces in this array are the only ones allowed to be used. E. g. root project namespace.allowUseFromRootNamespace
: also allow using top-level namespace:
use DateTimeImmutable;
🔧
SlevomatCodingStandard.Namespaces.UseDoesNotStartWithBackslash Disallows leading backslash in use statement:
use \Foo\Bar;
🔧
SlevomatCodingStandard.Classes.EmptyLinesAroundClassBraces Enforces one configurable number of lines after opening class/interface/trait brace and one empty line before the closing brace.
Sniff provides the following settings:
linesCountAfterOpeningBrace
: allows to configure the number of lines after opening brace.linesCountBeforeClosingBrace
: allows to configure the number of lines before closing brace.
🔧
SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation Enforces fully qualified names of classes and interfaces in phpDocs - in annotations. This results in unambiguous phpDocs.
SlevomatCodingStandard.Commenting.DeprecatedAnnotationDeclaration
Reports @deprecated
annotations without description.
🔧
SlevomatCodingStandard.Commenting.DisallowCommentAfterCode Disallows comments after code at the same line.
🔧
SlevomatCodingStandard.Commenting.ForbiddenAnnotations Reports forbidden annotations. No annotations are forbidden by default, the configuration is completely up to the user. It's recommended to forbid obsolete and inappropriate annotations like:
@author
,@created
,@version
: we have version control systems.@package
: we have namespaces.@copyright
,@license
: it's not necessary to repeat licensing information in each file.@throws
: it's not possible to enforce this annotation and the information can become outdated.
Sniff provides the following settings:
forbiddenAnnotations
: allows to configure which annotations are forbidden to be used.
🔧
SlevomatCodingStandard.Commenting.ForbiddenComments Reports forbidden comments in descriptions. Nothing is forbidden by default, the configuration is completely up to the user. It's recommended to forbid generated or inappropriate messages like:
Constructor.
Created by PhpStorm.
Sniff provides the following settings:
forbiddenCommentPatterns
: allows to configure which comments are forbidden to be used. This is an array of regular expressions (PCRE) with delimiters.
🔧
SlevomatCodingStandard.Commenting.DocCommentSpacing Enforces configurable number of lines before first content (description or annotation), after last content (description or annotation),
between description and annotations, between two different annotations types (eg. between @param
and @return
).
Sniff provides the following settings:
linesCountBeforeFirstContent
: allows to configure the number of lines before first content (description or annotation).linesCountBetweenDescriptionAndAnnotations
: allows to configure the number of lines between description and annotations.linesCountBetweenDifferentAnnotationsTypes
: allows to configure the number of lines between two different annotations types.linesCountBetweenAnnotationsGroups
: allows to configure the number of lines between annotations groups.linesCountAfterLastContent
: allows to configure the number of lines after last content (description or annotation).annotationsGroups
: allows to configurure order of annotations groups and even order of annotations in every group. Supports prefixes, eg.@ORM\
.
<rule ref="SlevomatCodingStandard.Commenting.DocCommentSpacing">
<properties>
<property name="annotationsGroups" type="array">
<element value="
@ORM\,
"/>
<element value="
@var,
@param,
@return,
"/>
</property>
</properties>
</rule>
If annotationsGroups
is set, linesCountBetweenDifferentAnnotationsTypes
is ignored and linesCountBetweenAnnotationsGroups
is applied.
If annotationsGroups
is not set, linesCountBetweenAnnotationsGroups
is ignored and linesCountBetweenDifferentAnnotationsTypes
is applied.
Annotations not in any group are placed to automatically created last group.
🔧
SlevomatCodingStandard.Commenting.EmptyComment Reports empty comments.
🔧
SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration Reports invalid inline phpDocs with @var
.
Sniff provides the following settings:
allowDocCommentAboveReturn
: Allows documentation comments without variable name abovereturn
statemens.allowAboveNonAssignment
: Allows documentation comments above non-assigment if the line contains the right variable name.
🔧
SlevomatCodingStandard.Commenting.RequireOneLinePropertyDocComment Requires property comments with single-line content to be written as one-liners.
🔧
SlevomatCodingStandard.Commenting.RequireOneLineDocComment Requires comments with single-line content to be written as one-liners.
🔧
SlevomatCodingStandard.Commenting.DisallowOneLinePropertyDocComment Requires comments with single-line content to be written as multi-liners.
🔧
SlevomatCodingStandard.Commenting.UselessFunctionDocComment - Checks for useless doc comments. If the native method declaration contains everything and the phpDoc does not add anything useful, it's reported as useless and can optionally be automatically removed with
phpcbf
. - Some phpDocs might still be useful even if they do not add any typehint information. They can contain textual descriptions of code elements and also some meaningful annotations like
@expectException
or@dataProvider
.
Sniff provides the following settings:
traversableTypeHints
: enforces which typehints must have specified contained type. E. g. if you set this to\Doctrine\Common\Collections\Collection
, then\Doctrine\Common\Collections\Collection
must always be supplied with the contained type:\Doctrine\Common\Collections\Collection|Foo[]
.
This sniff can cause an error if you're overriding or implementing a parent method which does not have typehints. In such cases add @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
annotation to the method to have this sniff skip it.
🔧
SlevomatCodingStandard.Commenting.UselessInheritDocComment Reports documentation comments containing only {@inheritDoc}
annotation because inheritance is automatic and it's not needed to use a special annotation for it.
🔧
SlevomatCodingStandard.ControlStructures.UselessIfConditionWithReturn Reports useless conditions where both branches return true
or false
.
Sniff provides the following settings:
assumeAllConditionExpressionsAreAlreadyBoolean
(defaults tofalse
).
🔧
SlevomatCodingStandard.ControlStructures.UselessTernaryOperator Reports useless ternary operator where both branches return true
or false
.
Sniff provides the following settings:
assumeAllConditionExpressionsAreAlreadyBoolean
(defaults tofalse
).
Installation
The recommended way to install Slevomat Coding Standard is through Composer.
{
"require-dev": {
"slevomat/coding-standard": "~7.0"
}
}
It's also recommended to install php-parallel-lint/php-parallel-lint which checks source code for syntax errors. Sniffs count on the processed code to be syntactically valid (no parse errors), otherwise they can behave unexpectedly. It is advised to run PHP-Parallel-Lint
in your build tool before running PHP_CodeSniffer
and exiting the build process early if PHP-Parallel-Lint
fails.
How to run the sniffs
You can choose one of two ways to run only selected sniffs from the standard on your codebase:
Choose which sniffs to run
The recommended way is to write your own ruleset.xml by referencing only the selected sniffs. This is a sample ruleset.xml:
<?xml version="1.0"?>
<ruleset name="AcmeProject">
<config name="installed_paths" value="../../slevomat/coding-standard"/><!-- relative path from PHPCS source location -->
<rule ref="SlevomatCodingStandard.Arrays.TrailingArrayComma"/>
<!-- other sniffs to include -->
</ruleset>
Then run the phpcs
executable the usual way:
vendor/bin/phpcs --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests
Exclude sniffs you don't want to run
You can also mention Slevomat Coding Standard in your project's ruleset.xml
and exclude only some sniffs:
<?xml version="1.0"?>
<ruleset name="AcmeProject">
<rule ref="vendor/slevomat/coding-standard/SlevomatCodingStandard/ruleset.xml"><!-- relative path to your ruleset.xml -->
<!-- sniffs to exclude -->
</rule>
</ruleset>
However it is not a recommended way to use Slevomat Coding Standard, because your build can break when moving between minor versions of the standard (which can happen if you use ^
or ~
version constraint in composer.json
). We regularly add new sniffs even in minor versions meaning your code won't most likely comply with new minor versions of the package.
Fixing errors automatically
Sniffs in this standard marked by the
vendor/bin/phpcbf --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests
Always remember to back up your code before performing automatic fixes and check the results with your own eyes as the automatic fixer can sometimes produce unwanted results.
Suppressing sniffs locally
Selected sniffs in this standard marked by the
/**
* @param int $max
*/
public function createProgressBar($max = 0): ProgressBar
{
}
The parameter $max
could have a native int
scalar typehint. But because the method in the parent class does not have this typehint, so this one cannot have it either. PHP_CodeSniffer shows a following error:
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
67 | ERROR | [x] Method ErrorsConsoleStyle::createProgressBar()
| | does not have native type hint for its parameter $max
| | but it should be possible to add it based on @param
| | annotation "int".
| | (SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint)
If we want to suppress this error instead of fixing it, we can take the error code (SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
) and use it with a @phpcsSuppress
annotation like this:
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $max
*/
public function createProgressBar($max = 0): ProgressBar
{
}
Contributing
To make this repository work on your machine, clone it and run these two commands in the root directory of the repository:
composer install
bin/phing
After writing some code and editing or adding unit tests, run phing again to check that everything is OK:
bin/phing
We are always looking forward for your bugreports, feature requests and pull requests. Thank you.
Code of Conduct
This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.
-
6.4.1 6.4.1
🐛 FixesNegationOperatorSpacingSniff
: Fixed false positiveBlockControlStructureSpacingSniff
: Fixed false positiveBlockControlStructureSpacingSniff
: Ignoreif
with alternative syntaxJumpStatementsSpacingSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positiveReferenceUsedNamesOnlySniff
: Improved fixerRequireTernaryOperatorSniff
: Improved fixer
-
6.4.0 6.4.0
📣 You can now sponsor Slevomat Coding Standard development🆕 New sniffsRequireSingleLineConditionSniff
: Enforces conditions ofif
,elseif
,while
anddo-while
to be on a single lineRequireMultiLineConditionSniff
: Enforces conditions ofif
,elseif
,while
anddo-while
with one or more boolean operators to be splitted to more lines so each condition part is on its own lineRequireSingleLineCallSniff
: Enforces function call to be on a single lineRequireMultiLineCallSniff
: Enforces function call to be splitted to more lines so each parameter is on its own lineDeprecatedAnnotationDeclarationSniff
: Reports@deprecated
annotations without description (thanks to @gmponos)SuperfluousErrorNamingSniff
: Reports use of superfluous suffixError
for errors (thanks to @gmponos)
🔧 Improvements- All sniffs should work on PHP 8 if you don't use new syntax - new syntax has to be supported by PHPCS first
- Support for
class-string
type hint DuplicateSpacesSniff
: New optionignoreSpacesInParameters
InlineDocCommentDeclarationSniff
: New optionallowAboveNonAssignment
ReferenceUsedNamesOnlySniff
: Less colisions withAlphabeticallySortedUsesSniff
🐛 FixesLanguageConstructWithParenthesesSniff
: Some errors were not reported
⚠️ DeprecatedUnusedPrivateElementsSniff
: Mark as deprecated
-
6.3.11 6.3.11
📣 You can now sponsor Slevomat Coding Standard developmentFixes
UselessVariableSniff
: Fixed false positiveTraitUseSpacingSniff
: Fix for uses with commentsUselessParenthesesSniff
: Fixed false positiveRequireExplicitAssertionSniff
: Fixed fixerDisallowArrayTypeHintSyntaxSniff
: Fixed internal errorParentCallSpacingSniff
: Fixed false positivesDisallowCommentAfterCodeSniff
: Fixed internal errorPropertySpacingSniff
: Fixed internal errorPropertySpacingSniff
: Fixed false positiveConstantSpacingSniff
: Fixed false positiveRequireTernaryOperatorSniff
: Prevent introducing logic errors (thanks to @Khartir)ScopeHelper
: Fixed internal error
Improvements
- Added
@phpstan-throws
support
⚠️ DeprecatedUnusedPrivateElementsSniff
: Mark as deprecated
-
6.3.10 6.3.10
📣 You can now sponsor Slevomat Coding Standard developmentFixes
UselessSemicolonSniff
: Fixed internal errorUselessIfConditionWithReturnSniff
: Don't remove comments automaticallyReferencedNameHelper
: Fixed constant detection
-
6.3.9 6.3.9
📣 You can now sponsor Slevomat Coding Standard developmentFixes
DisallowCommentAfterCodeSniff
: Fixed false positive- Fix error message typos in NumericLiteralSeparator sniffs (thanks to @finwe)
UnusedVariableSniff
: Fixed false positivesEarlyExitSniff
: Fixed fixer for conditions with?:
and??
-
6.3.8 6.3.8
📣 You can now sponsor Slevomat Coding Standard developmentFixes
- Fixed detection of some referenced names
-
6.3.7 6.3.7
📣 You can now sponsor Slevomat Coding Standard developmentFixes
- Fixed internal error
-
6.3.6 6.3.6
📣 You can now sponsor Slevomat Coding Standard developmentFixes
UseSpacingSniff
: Fixed internal errorsFullyQualifiedClassNameInAnnotationSniff
: Fixed false positiveUnusedPrivateElementsSniff
: Fixed missing reports for write-only properties with FQN native typehints
-
6.3.5 6.3.5
📣 You can now sponsor Slevomat Coding Standard developmentFixes
EarlyExitSniff
:yield
does not do early exitEarlyExitSniff
: Fixed false positiveBlockControlStructureSpacingSniff
: Fixed false positivesJumpStatementsSpacingSniff
: Improved fixerRequireTernaryOperatorSniff
: Fixer should not remove comments
-
6.3.4 6.3.4
📣 You can now sponsor Slevomat Coding Standard developmentFixes
EarlyExitSniff
: Fixed internal errorBlockControlStructureSpacingSniff
: Fixed false positiveUselessFunctionDocCommentSniff
: Fixed internal error- Fixed parsing really strange WordPress documentation
TypeNameMatchesFileNameSniff
: Exclude provided base path (thanks to @rmikalkenas)
-
6.3.3 6.3.3
📣 You can now sponsor Slevomat Coding Standard developmentImprovements
ClassMemberSpacingSniff
: Improved for invalid commentsUselessVariableSniff
: Improved fixer
Fixes
StrictCallSniff
: Fixed false positive
-
6.3.2 6.3.2
📣 You can now sponsor Slevomat Coding Standard developmentFixes
- Hotfix for autoload, broken in #969
-
6.3.1 6.3.1
📣 You can now sponsor Slevomat Coding Standard developmentFixes
ClassStructureSniff
: Fixed internal errorClassMemberSpacingSniff
: Fixed false positiveStaticClosureSniff
: Workaround for bug in PHPCS
-
6.3.0 6.3.0
📣 You can now sponsor Slevomat Coding Standard developmentNew sniffs
ClassMemberSpacingSniff
: Checks lines count between different class members, eg. between last property and first methodStrictCallSniff
: Some functions have$strict
parameter. This sniff reports calls to these functions without the parameter or with$strict = false
ForbiddenClassesSniff
: Reports usage of forbidden classes, interfaces, parent classes and traits (thanks to @arxeiss)
Improvements
- Support for parsing and checking
@template
etc annotations - Support for more prefixed annotations (
@psalm-
or@phpstan-
prefixes) EarlyExitSniff
: New optionignoreTrailingIfWithOneInstruction
AssignmentInConditionSniff
: New optionignoreAssignmentsInsideFunctionCalls
(thanks to @nightlinus)DuplicateSpacesSniff
: New optionignoreSpacesInComment
LineLengthSniff
: Speedup (thanks to @nightlinus)
Fixes
FullyQualifiedClassNameInAnnotationSniff
: Does not report@template
ParentCallSpacingSniff
: Fixed false positiveReturnTypeHintSniff
: Fixed false positiveParameterTypeHintSniff
: Fixed false positivePropertyTypeHintSniff
: Fixed false positiveMethodSpacingSniff
: Fixed false positiveEarlyExitSniff
: Fixed missing reportConstantSpacingSniff
: Fixed internal error
-
6.2.0 6.2.0
📣 You can now sponsor Slevomat Coding Standard developmentNew sniffs
ArrowFunctionDeclaration
: Checksfn
declarationMethodSpacingSniff
: Checks that there is a certain number of blank lines between methodsDisallowMultiConstantDefinitionSniff
: Disallows multi constant definitionDisallowMultiPropertyDefinitionSniff
: Disallows multi property definitionDisallowDirectMagicInvokeCallSniff
: Disallows direct call of__invoke()
DisallowSuperGlobalVariableSniff
: Disallows use of super global variablesDisallowInlineCommentAfterCodeSniff
: Disallows comments after code at the same lineDuplicateSpacesSniff
: Checks duplicate spaces anywhere
Improvements
InlineDocCommentDeclarationSniff
: New optionallowDocCommentAboveReturn
EarlyExitSniff
: New optionignoreOneLineTrailingIf
FullyQualifiedGlobalConstantsSniff
: New optioninclude
(thanks to @bbatsche)FullyQualifiedGlobalFunctionsSniff
: New optioninclude
(thanks to @bbatsche)FullyQualifiedGlobalFunctionsSniff
: New optionincludeSpecialFunctions
RequireYodaComparisonSniff
: New optionalwaysVariableOnRight
JumpStatementsSpacingSniff
: New optionslinesCountBeforeWhenFirstInCaseOrDefault
,linesCountAfterWhenLastInCaseOrDefault
andlinesCountAfterWhenLastInLastCaseOrDefault
ClassStructureSniff
: New optionenableFinalMethods
to support final methods groupsRequireNullCoalesceEqualOperatorSniff
: New optionenable
(thanks to @carusogabriel)TrailingCommaInCallSniff
: New optionenable
(thanks to @carusogabriel)RequireArrowFunctionSniff
: New optionenable
(thanks to @carusogabriel)RequireNumericLiteralSeparatorSniff
: New optionenable
(thanks to @carusogabriel)RequireNumericLiteralSeparatorSniff
: New optionminDigitsBeforeDecimalPoint
RequireNumericLiteralSeparatorSniff
: New optionminDigitsAfterDecimalPoint
ClassStructureSniff
: Support for shortcut groupsReferenceThrowableOnlySniff
: Can be suppressed when\Exception
is used as parameterParameterTypeHintSniff
:@psalm-param
and@phpstan-param
are sufficient as type hintsReturnTypeHintSniff
:@psalm-return
and@phpstan-return
are sufficient as type hintsPropertyTypeHintSniff
:@psalm-var
and@phpstan-var
are sufficient as type hintsRequireNullCoalesceOperatorSniff
: Improved fixerPropertyTypeHintSniff
: Improved performancePropertyTypeHintSpacingSniff
: Improved performanceUnusedUsesSniff
: Improved performance (thanks to @nightlinus)UnusedVariableSniff
: Improved performance (thanks to @nightlinus)FullyQualifiedExceptionsSniff
: Improved performanceReferenceUsedNamesOnlySniff
: Improved performanceFullyQualifiedGlobalConstantsSniff
: Improved performanceFullyQualifiedGlobalFunctionsSniff
: Improved performance- Support for PHPCS configuration
php_version
in all possible sniffs NamespaceHelper
: Improved performance (thanks to @nightlinus)
Fixes
PropertySpacingSniff
: Fixed false positiveJumpStatementsSpacingSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positivesEarlyExitSniff
: Fixed false positivesInlineDocCommentDeclarationSniff
: Fixed false positivesBlockControlStructureSpacingSniff
: Fixed false positiveNegationOperatorSpacingSniff
: Fixed internal errorReturnTypeHintSniff
: Fixed breaking syntax on removing useless@return
annotation in one-line doccomment (thanks to @nightlinus)ParameterTypeHintSniff
: Fixed breaking syntax on removing useless@param
annotation in one-line doccommentForbiddenAnnotationsSniff
: Fixed fixer for one-line doccommentsInlineDocCommentDeclarationSniff
: Added support for various spacings in callable typehint (thanks to @simPod)PropertySpacingSniff
: Fixed fixerUnusedUsesSniff
: Fix for duplicate errorsAlphabeticallySortedUsesSniff
: Fix for duplicate errorsReferenceThrowableOnlySniff
: Fix for duplicate errorsFullyQualifiedGlobalConstantsSniff
: Fix for duplicate errorsFullyQualifiedGlobalFunctionsSniff
: Fix for duplicate errorsFullyQualifiedExceptionsSniff
: Fix for duplicate errorsReferenceUsedNamesOnlySniff
: Fix for duplicate errorsUselessAliasSniff
: Fix for duplicate errorsUseSpacingSniff
: Fix for duplicate errorsUseStatementHelper
: Workaround for bug in PHPCS
-
6.1.5 6.1.5
You can now sponsor Slevomat Coding Standard development
Fixes
-
6.1.4 6.1.4
You can now sponsor Slevomat Coding Standard development
Fixes
PropertySpacingSniff
: Fixed support for typed propertiesParameterTypeHintSniff
: Fixed false positivesPropertyTypeHintSniff
: Fixed false positivesReturnTypeHintSniff
: Fixed false positivesEarlyExitSniff
: Fixed fixer for heredoc/nowdoc
-
6.1.3 6.1.3
You can now sponsor Slevomat Coding Standard development
Fixes
ParameterTypeHintSniff
: Fixed false positivesReturnTypeHintSniff
: Fixed false positivesPropertyTypeHintSniff
: Fixed false positives
-
6.1.2 6.1.2
You can now sponsor Slevomat Coding Standard development
Fixes
SingleLineArrayWhitespaceSniff
: Fixed settings by XML configuration (thanks to @mcaskill)UselessParenthesesSniff
: Fixed false positiveParentCallSpacingSniff
: Fixed false positivePropertySpacingSniff
: Fixed settings by XML configuration (thanks to @paxal)ConstantSpacingSniff
: Fixed settings by XML configuration (thanks to @paxal)PropertySpacingSniff
: Fixed false positiveConstantSpacingSniff
: Fixed false positiveUnusedPrivateElementsSniff
: Fixed support for private typed properties (thanks to @paxal)ParameterTypeHintSniff
: Fixed support for union and nullable typesReturnTypeHintSniff
: Fixed support for union and nullable typesPropertyTypeHintSniff
: Fixed support for union and nullable types
Improvements
SingleLineArrayWhitespaceSniff
: Add empty array support (can be enabled with new optionenableEmptyArrayCheck
) (thanks to @mcaskill)TraitUseSpacingSniff
: Added additional settinglinesCountBeforeFirstUseWhenFirstInClass
(thanks to @thled)RequireSingleLineMethodSignatureSniff
: New optionincludedMethodPatterns
(thanks to @RiKap)RequireSingleLineMethodSignatureSniff
: New optionexcludedMethodPatterns
(thanks to @RiKap)RequireMultiLineMethodSignatureSniff
: New optionincludedMethodPatterns
(thanks to @RiKap)RequireMultiLineMethodSignatureSniff
: New optionexcludedMethodPatterns
(thanks to @RiKap)
-
6.1.1 6.1.1
You can now sponsor Slevomat Coding Standard development
Fixes
ParentCallSpacingSniff
: Fixed false positive (thanks to @grongor)RequireSingleLineMethodSignatureSniff
: Fix for semicolons (thanks to @grongor)PropertyTypeHintSniff
: Improved support for union typesReturnTypeHintSniff
: Improved support for union typesParameterTypeHintSniff
: Improved support for union typesClassStructureSniff
: Fix missing support for static abstract methods (thanks to @grongor)
Improvements
NullableTypeForNullDefaultValueSniff
: Allow suppress (thanks to @simPod)
-
6.1.0 6.1.0
You can now sponsor Slevomat Coding Standard development
New sniffs
RequireNullCoalesceEqualOperatorSniff
: Requires use of null coalesce equal operator when possibleRequireMultiLineMethodSignatureSniff
: Enforces method signature to be splitted to more lines so each parameter is on its own lineRequireSingleLineMethodSignatureSniff
: Enforces method signature to be on a single line (thanks to @grongor)PropertySpacingSniff
: Checks that there is a certain number of blank lines between properties (thanks to @grongor)ConstantSpacingSniff
: Checks that there is a certain number of blank lines between constants (thanks to @grongor)ParentCallSpacingSniff
: Enforces configurable number of lines around parent method call (thanks to @grongor)ClassStructureSniff
: Checks that class/trait/interface members are in the correct order (thanks to @grongor)RequireOneLineDocCommentSniff
: Requires comments with single-line content to be written as one-liners (thanks to @grongor)MultiLineArrayEndBracketPlacementSniff
: Enforces reasonable end bracket placement for multiline arrays (thanks to @grongor)SingleLineArrayWhitespaceSniff
: Checks whitespace in single line array declarations (thanks to @grongor)NegationOperatorSpacingSniff
: Checks if there is the same number of spaces after negation operator as expected (thanks to @grongor)LineLengthSniff
: Enforces maximum length of a single line of code (thanks to @grongor)DisallowEmptyFunctionSniff
: Reports empty functions body and require at least a comment inside (thanks to @arxeiss)
Improvements
UnusedPrivateElementsSniff
: New optionalwaysUsedMethodsAnnotations
(thanks to @simPod)- Don't break the complete PHPCS run for unsupported syntaxes (thanks to @jrfnl)
Fixes
FullyQualifiedGlobalConstantsSniff
: Fixed false positivesFullyQualifiedGlobalFunctionsSniff
: Fixed false positivesUnusedVariableSniff
: Fixed false positiveUselessVariableSniff
: Fixed false positivesRequireTernaryOperatorSniff
: Fixed false positives (thanks to @grongor)JumpStatementsSpacingSniff
: Fixed false positives (thanks to @grongor)NullableTypeForNullDefaultValueSniff
: Workaround for bug in PHPCS
-
6.0.8 6.0.8
Fixes
ReferenceUsedNamesOnlySniff
: Fixed missing reportsReferenceUsedNamesOnlySniff
: Fixed false positive
-
6.0.7 6.0.7
Fixes
InlineDocCommentDeclarationSniff
: Fixed false positives
-
6.0.6 6.0.6
Fixes
StaticClosureSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positiveJumpStatementsSpacingSniff
: Fix yield inside function callsDocCommentSpacingSniff
: Fixed support for@phpstan
and@phpcs
annotations
-
6.0.5 6.0.5
Fixes
EarlyExitSniff
: Fixed internal error
Improvements
- Support of phpstan/phpdoc-parser 0.4.2 (thanks to @jeroennoten)
-
6.0.4 6.0.4
Fixes
- Fixed bugs caused by broken
DocCommentHelper
- Fixed bugs caused by broken
-
6.0.3 6.0.3
Fixes
UselessParenthesesSniff
: Fixed false positiveEarlyExitSniff
: Improved internal errors reporting
-
6.0.2 6.0.2
Fixes
UselessParenthesesSniff
: Fixed false positive
-
6.0.1 6.0.1
Fixes
- Fixed array shapes support
UselessVariableSniff
: Variables with@phpstan-var
or@psalm-var
annotation are not reported as uselessUselessParenthesesSniff
: Fixed false positive
-
6.0.0 6.0.0
New sniffs
RequireArrowFunctionSniff
: Requires arrow functionsDisallowArrowFunctionSniff
: Disallows arrow functionsRequireNumericLiteralSeparatorSniff
: Requires use of numeric literal separatorsDisallowNumericLiteralSeparatorSniff
: Disallows numeric literal separatorsRequireNowdocSniff
: Requires nowdoc syntax instead of heredoc when possibleReferenceSpacingSniff
: Enforces configurable number of spaces after referenceDisallowReferenceSniff
: Disallows referencesRequireExplicitAssertionSniff
: Requires assertion viaassert()
instead of inline documentation comments.ParameterTypeHintSniff
: Previously part ofTypeHintDeclarationSniff
PropertyTypeHintSniff
: Previously part ofTypeHintDeclarationSniff
ReturnTypeHintSniff
: Previously part ofTypeHintDeclarationSniff
UselessFunctionDocCommentSniff
: Previously part ofTypeHintDeclarationSniff
BlockControlStructureSpacingSniff
: Previously part ofControlStructureSpacingSniff
JumpStatementsSpacingSniff
: Previously part ofControlStructureSpacingSniff
Improvements
- PHP 7.4 support
- Arrow functions support
- Array shapes in phpDocs support
PropertyTypeHintSniff
: Support for native type hintsInlineDocCommentDeclarationSniff
: Reports missing related variables or no assigmentInlineDocCommentDeclarationSniff
: Added support for doccomments after variable definitionInlineDocCommentDeclarationSniff
: Added support forlist()
and short list[]
TrailingArrayCommaSniff
: New optionenableAfterHeredoc
DisallowMixedTypeHintSniff
: Added suppress supportUselessParenthesesSniff
: Reports more useless parentheses
Fixes
- Fixed support of
@method
annotation InlineDocCommentDeclarationSniff
: Check really only inline doccommentsTrailingCommaInCallSniff
: Some calls were not reportedUselessParenthesesSniff
: Fixed false positiveNamespaceSpacingSniff
: Fixed false positiveUselessSemicolonSniff
: Fixed internal errorTypeNameMatchesFileNameSniff
: Files without namespaces should be reported tooUseSpacingSniff
: Don't report errors for use statements with comments right before or afterUselessVariableSniff
: Fixed false positiveUselessParameterDefaultValueSniff
: Fixed false positiveUnusedPrivateElementsSniff
: Fixed false positiveUnusedUsesSniff
: Better handle php open tags (thanks to @donatj)RequireCombinedAssignmentOperatorSniff
: Fixed false positiveUselessInheritDocCommentSniff
: Fixed internal errorRequireShortTernaryOperatorSniff
: Fix token overrun (thanks to @donatj)- Fix compatibility with non-Composer installs of PHPCS (thanks to @jrfnl)
⚠️ BC breaksTypeHintDeclarationSniff
is dead, long liveParameterTypeHintSniff
,PropertyTypeHintSniff
,ReturnTypeHintSniff
andUselessFunctionDocCommentSniff
ControlStructureSpacingSniff
is dead, long liveBlockControlStructureSpacingSniff
andJumpStatementsSpacingSniff
(thanks to @grongor)
-
5.0.4 5.0.4
Fixes
EarlyExitSniff
: Fixed false positiveControlStructureSpacingSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positives
-
5.0.3 5.0.3
Fixes
ControlStructureSpacingSniff
: Fixed false positive
-
5.0.2 5.0.2
Fixes
ControlStructureSpacingSniff
: FixedT_CASE
andT_DEFAULT
supportUselessParenthesesSniff
: Fixed false positivesUnusedVariableSniff
: Fixed false positiveConditionHelper
: Fixed getNegativeCondition()TypeHintHelper
: Added more unofficial type hints
-
5.0.1 5.0.1
Fixes
DisallowArrayTypeHintSyntaxSniff
: Follow type hint when converting to generics syntax (thanks to @thewilkybarkid)UnusedVariableSniff
: Fixed false positiveUselessVariableSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positiveTypeHintDeclarationSniff
: Invalid annotations should be ignored
Improvements
UseStatementHelper
: SpeedupUseStatementHelper
: Mark method getUseStatements() as deprecated
-
5.0.0 5.0.0
New sniffs
SpreadOperatorSpacingSniff
: Enforces configurable number of spaces after the...
operatorDisallowArrayTypeHintSyntaxSniff
: Disallows usage of array type hint syntax (eg.int[]
,bool[][]
) in phpDocs in favour of generic type hint syntax (eg.array<int>
,array<array<bool>>
)TrailingCommaInCallSniff
: Enforces trailing commas in multi-line callsDisallowMixedTypeHintSniff
: Disallows usage of "mixed" type hint in phpDocsSuperfluousTraitNamingSniff
: Reports use of superfluous suffixTrait
for traits
Improvements
- Added support for generic and intersection types in PHP docs
- Improved support for more namespaces in a file
UselessIfConditionWithReturnSniff
: New optionassumeAllConditionExpressionsAreAlreadyBoolean
EarlyExitSniff
: More uselesselseif
andelse
conditions are reportedNullTypeHintOnLastPositionSniff
: Added support for@property
and@method
annotationsFullyQualifiedClassNameInAnnotationSniff
: Added support for@property
and@method
annotationsLongTypeHintsSniff
: Added support for@property
and@method
annotationsLongTypeHintsSniff
: Inline doccomments are checked nowReferenceUsedNamesOnlySniff
: Added support for@method
annotations (thanks to @hranicka)UselessParenthesesSniff
: Some useless parentheses were not reported
Fixes
OptimizedFunctionsWithoutUnpackingSniff
: Fix for trailing commas in function callsUnusedVariableSniff
: Fixed false positiveUselessVariableSniff
: Fixed false positive
⚠️ BC breaksEmptyLinesAroundTypeBracesSniff
: Renamed toEmptyLinesAroundClassBracesSniff
and moved to namespaceClasses
DisallowEqualOperatorsSniff
: Moved to namespaceOperators
UselessConditionWithReturnSniff
: Splitted toUselessIfConditionWithReturnSniff
andUselessTernaryOperatorSniff
- Removed support for
@var
annotation in format/** @var $variable type */
for most of the sniffs - Removed support for
@param
annotations without parameter name for most of the sniffs AlphabeticallySortedUsesSniff
:psr12Compatible
option is now enabled by defaultNullableTypeForNullDefaultValueSniff
: Removed deprecatedenabled
optionClassConstantVisibilitySniff
: Removed deprecatedenabled
optionTypeHintDeclarationSniff
: MarkenableObjectTypeHint
option as deprecatedTypeHintDeclarationSniff
: Removed deprecatedusefulAnnotations
optionTypeHintDeclarationSniff
: Removed deprecatedenableNullableTypeHints
optionTypeHintDeclarationSniff
: Removed deprecatedenableVoidTypeHint
option- Removed deprecated
DisallowLateStaticBindingForContantsSniff
(alias forDisallowLateStaticBindingForConstantsSniff
)
-
4.8.7 4.8.7
⚠️ PHPCS 3.4+ is now required (thanks to @carusogabriel)Fixes:
DeclareStrictTypesSniff
: Fixed correct number of whitespaces in autofix and errormessage (thanks to @wietsewarendorff)RequireMultiLineTernaryOperatorSniff
: Fixed close tag w/o prior semi (thanks to @donatj)UnusedPrivateElementsSniff
: Fixed false positiveSuperfluousExceptionNamingSniff
: Fixed false positiveControlStructureSpacingSniff
: Fixed internal errorsDocCommentSpacingSniff
: Fixed infinite loopDisallowYodaComparisonSniff
: Don't fix assigment in conditionRequireOnlyStandaloneIncrementAndDecrementOperatorsSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positiveReferencedNameHelper
: Fixed reference names with whitespace
-
4.8.6 4.8.6
⚠️ PHPCS 3.3.1+ is now required for PHP 7.3 compatibility.Fixes:
UnusedVariableSniff
: Fixed false positivesUnusedPrivateElementsSniff
: Fixed false positivesUselessParenthesesSniff
: Fixed false positivesTraitUseSpacingSniff
: Fixer should not remove useful codeNamespaceDeclarationSniff
: Fixed false positiveRequireOneNamespaceInFileSniff
: Fixed false positiveControlStructureSpacingSniff
: Fixed false positiveUnusedUsesSniff
: Fixed false positiveRequireMultiLineTernaryOperatorSniff
: Fixed false positiveOptimizedFunctionsWithoutUnpackingSniff
: Fixed infinite loop
-
4.8.5 4.8.5
Fixes:
UnusedVariableSniff
: Fixed false positiveDisallowImplicitArrayCreationSniff
: Fixed false positiveDisallowImplicitArrayCreationSniff
: Fixed missing reportingUselessParenthesesSniff
: Fixed false positivesUselessParenthesesSniff
: Fixed internal error
-
4.8.4 4.8.4
Fixes:
ControlStructureSpacingSniff
: Fixed reporting and fixerControlStructureSpacingSniff
: Fixed internal errorUselessParenthesesSniff
: Fixed false positivesUselessVariableSniff
: Fixed false positive
-
4.8.3 4.8.3
Fixes:
UnusedInheritedVariablePassedToClosureSniff
: Fixed fixerDocCommentSpacingSniff
: Some errors were not reported and fixedDocCommentSpacingSniff
: Fixed internal errorRequireTernaryOperatorSniff
: Fixed internal error
-
4.8.2 4.8.2
Fixes:
DocCommentSpacingSniff
: Some errors were not reported and fixedDocCommentSpacingSniff
: Fixed fixerDocCommentSpacingSniff
: Fixed internal errorStaticClosureSniff
: Fixed false positive
-
4.8.1 4.8.1
Fixes:
ControlStructureSpacingSniff
: Fixed internal errorDisallowLateStaticBindingForConstantsSniff
: Fixed typo in sniff name (previous name still works)
-
4.8.0 4.8.0
⚠️ PHPCS 3.3.0+ is now required.New sniffs:
RequireOnlyStandaloneIncrementAndDecrementOperatorsSniff
: Reports++
and--
operators not used standaloneUselessParameterDefaultValueSniff
: Looks for useless parameter default valueDisallowLateStaticBindingForContantsSniff
: Disallows late static binding for constantsUselessLateStaticBindingSniff
: Reports useless late static bindingControlStructureSpacingSniff
: Enforces configurable number of lines around control structuresUselessConditionWithReturnSniff
: Reports useless conditions where both branches returntrue
orfalse
RequireTernaryOperatorSniff
: Requires ternary operator when possibleRequireMultiLineTernaryOperatorSniff
: Ternary operator has to be reformatted to more lines when the line length exceeds the given limitDisallowImplicitArrayCreationSniff
: Disallows implicit array creationDuplicateAssignmentToVariableSniff
: Looks for duplicate assignments to a variableDisallowContinueWithoutIntegerOperandInSwitchSniff
: Disallows use ofcontinue
without integer operand inswitch
because it's emits warning in PHP 7.3 and higherOptimizedFunctionsWithoutUnpackingSniff
: Reports functions that should not be invoked with argument unpacking because of opcache optimizations (thanks to @Majkl578)
Improvements:
DocCommentSpacingSniff
: New optionslinesCountBetweenAnnotationsGroups
andannotationsGroups
UselessParenthesesSniff
: New optionignoreComplexTernaryConditions
UnusedVariableSniff
: New optionignoreUnusedValuesWhenOnlyKeysAreUsedInForeach
EarlyExitSniff
: New optionignoreStandaloneIfInScope
ShortListSniff
: Improved fixer
Fixes:
EarlyExitSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positivesUselessParenthesesSniff
: Fixed false positiveModernClassNameReferenceSniff
: Fixed fixerRequireShortTernaryOperatorSniff
: Infinite loop fix (thanks to @dg)ReferenceUsedNamesOnlySniff
: Possible fix of false positivesDisallowIncrementAndDecrementOperatorsSniff
: Fixed error codes for post operators in some situationsIdentificatorHelper
: A lot of fixes
-
4.7.3 4.7.3
Fixes:
ModernClassNameReferenceSniff
: Fixed false positivesUnusedVariableSniff
: Fixed false positiveUselessVariableSniff
: Fixed false positives
-
4.7.2 4.7.2
Fixes:
ReferenceUsedNamesOnlySniff
: Fixed false positivesRequireShortTernaryOperatorSniff
: Fixed false positiveStaticClosureSniff
: Fixed false positiveModernClassNameReferenceSniff
: Fixed fixerUnusedParameterSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positiveUselessInheritDocCommentSniff
: Fixed false positivesUselessParenthesesSniff
: Fixed false positive
-
4.7.1 4.7.1
Fixes:
UnusedParameterSniff
: Fixed false positiveUnusedVariableSniff
: Fixed false positivesUnusedInheritedVariablePassedToClosure
: Fixed false positivesRequireNullCoalesceOperatorSniff
: Fixed false positivesModernClassNameReferenceSniff
: Fixed false positives with get_class()ModernClassNameReferenceSniff
: Fixed error messagesUselessVariableSniff
: Fixed false positiveUselessParenthesesSniff
: Fixed false positivesUselessParenthesesSniff
: Fixed checks for parentheses around "case"
-
4.7.0 4.7.0
New sniffs:
ModernClassNameReferenceSniff
: Reports use of__CLASS__
,get_parent_class()
,get_called_class()
,get_class()
andget_class($this)
. Class names should be referenced via::class
contant when possibleStaticClosureSniff
: Reports closures not using$this
that are not declaredstatic
RequireCombinedAssignmentOperatorSniff
: Requires using combined assigment operators, eg+=
,.=
etcNullTypeHintOnLastPositionSniff
: Enforcesnull
type hint on last position in@var
,@param
and@return
annotationsUselessConstantTypeHint
: Reports useless@var
annotation (or whole documentation comment) for class constants because the type of constant is always clearUselessInheritDocCommentSniff
: Reports documentation comments containing only{@inheritDoc}
annotation because inheritance is automatic and it's not needed to use a special annotation for itTraitUseDeclarationSniff
: Prohibits multiple traits separated by commas in oneuse
statementTraitUseSpacingSniff
: Enforces configurable number of lines before firstuse
, after lastuse
and between twouse
statementsUnusedVariableSniff
: Looks for unused variablesUselessVariableSniff
: Looks for useless variablesUnusedParameterSniff
: Looks for unused parametersUnusedInheritedVariablePassedToClosureSniff
: Looks for unused inherited variables passed to closure viause
UselessAliasSniff
: Looks foruse
alias that is same as unqualified nameUselessSemicolonSniff
: Looks for useless semicolonsUselessParenthesesSniff
: Looks for useless parenthesesNewWithoutParenthesesSniff
: Reportsnew
with useless parentheses
Improvements:
RequireNullCoalesceOperatorSniff
:=== null
and!== null
conditions are detected tooRequireShortTernaryOperatorSniff
: Works with properties too
Fixes:
UnusedUsesSniff
: Fixed false positives for classes used in@see
annotationFullyQualifiedClassNameInAnnotationSniff
: Fixed fixerNamespaceSpacingSniff
: Fixed false positive whenphpcs
comment is before namespace
-
4.6.3 4.6.3
Fixes:
UnusedPrivateElementsSniff
: FixedalwaysUsedPropertiesAnnotations
support of prefixesUnusedPrivateElementsSniff
: Fixed false positive with constant in stringLongTypeHintsSniff
: Fixer should be case insensitiveTypeHintDeclarationSniff
: Added missing@inheritdoc
support for properties
-
4.6.2 4.6.2
Fixes:
EarlyExitSniff
: Added missingyield from
supportLanguageConstructWithParenthesesSniff
: Added missingyield from
checkFunctionHelper
: Added missingyield from
detection if function returns value
-
4.6.1 4.6.1
Compatibility with PHPCS 3.3
Fixes:
ReferenceUsedNamesOnlySniff
: Fixed fixer for classes in doccommentsDisallowEqualOperatorsSniff
: Fixed message when operator is<>
(thanks to @carusogabriel)
-
4.6.0 4.6.0
New sniffs:
NamespaceDeclarationSniff
: Enforces one space afternamespace
, disallows content between namespace name and semicolon and disallows use of bracketed syntaxNamespaceSpacingSniff
: Enforces configurable number of lines before and afternamespace
RequireOneNamespaceInFileSniff
: Requires only one namespace in a fileDisallowIncrementAndDecrementOperatorsSniff
: Disallows using++
and--
operatorsRequireShortTernaryOperatorSniff
: Requires short ternary operator?:
when possibleDisallowShortTernaryOperatorSniff
: Disallows short ternary operator?:
DisallowEmptySniff
: Disallows use ofempty()
ShortListSniff
: Enforces using short form of list syntax,[...]
instead oflist(...)
(thanks to @Majkl578)
Improvements:
InlineDocCommentDeclarationSniff
: Reports empty@var
annotationsInlineDocCommentDeclarationSniff
: Reports invalid comment type used for inline documentation commentInlineDocCommentDeclarationSniff
: Reports doccomment above foreach and while as wellUseSpacingSniff
: Enforce zero number of lines between same types of use statementUnusedUsesSniff
:ignoredAnnotations
- Case sensitive list of annotation names that the sniff ignore completely (both name and content are ignored)TypeHintDeclarationSniff
:allAnnotationsAreUseful
- Doccomment is useful if it contain any annotation, optionusefulAnnotations
is deprecatedUnusedPrivateElementsSniff
:alwaysUsedPropertiesAnnotations
supports prefixesUnusedUsesSniff
: Improved@method
annotation parsing
Fixes:
EarlyExitSniff
: Fixed noticesEarlyExitSniff
: Fixed fixer for complicated logical conditionsUnusedUsesSniff
: Fixed false positivesUnusedPrivateElementsSniff
: Fixed false positive when property used innew
ReferencedNameHelper
:goto
label should not be resolved as constantTypeHelper
: Fixed regexp
-
4.5.2 4.5.2
Fixes:
TypeHintDeclarationSniff
: Return annotation is not useless when return type hint is missing
-
4.5.1 4.5.1
Fixes:
EmptyCommentSniff
: Empty comments in multiline commented code are not reportedReferencedNameHelper
: Global constant used in class constant definition was not detected
-
4.5.0 4.5.0
⚠️ PHPCS 3.2.3+ is now required.New sniffs:
SuperfluousExceptionNamingSniff
: Reports usage of superfluous suffixException
for exceptionsSuperfluousAbstractClassNamingSniff
: Reports usage of superfluous prefix or suffixAbstract
for abstract classesSuperfluousInterfaceNamingSniff
: Reports usage of superfluous prefix or suffixInterface
for interfacesUseSpacingSniff
: Enforces configurable number of lines before firstuse
, after lastuse
and between two different types ofuse
(eg. betweenuse function
anduse const
)EmptyCommentSniff
: Reports empty commentsDocCommentSpacing
: Enforces configurable number of lines before first content (description or annotation), after last content (description or annotation), between description and annotations, between two different annotations typesDisallowOneLinePropertyDocCommentSniff
: Require comments with single-line content to be written as multi-liners (thanks to @Majkl578)RequireOneLinePropertyDocCommentSniff
: Require comments with single-line content to be written as one-liners (thanks to @Majkl578)TypeCastSniff
: Enforces using shorthand cast operators, forbids use of unset and binary cast operators (thanks to @Majkl578)
Improvements:
EarlyExitSniff
: New check "Remove useless elseif to reduce code nesting"UnusedUsesSniff
:ignoredAnnotationNames
- To ignore specified annotation names (thanks to @xificurk)ReferenceUsedNamesOnlySniff
: Improved annotations parsingFullyQualifiedClassNameInAnnotationSniff
: Improved annotations parsingForbiddenAnnotationsSniff
: Improved annotations parsingAlphaneticallySortedUsesSniff
: Make error message more clear (thanks to @brettdorrans)
Fixes:
EarlyExitSniff
: Reportelse
when all conditions contain early exit
-
4.4.8 4.4.8
Fixes:
UnusedUsesSniff
: Fixed false positives for mismatch case
-
4.4.7 4.4.7
Fixes:
UnusedUsesSniff
: Fixed false positivesReferenceUsedNamesOnlySniff
: Fixed fixer for code without namespaceAnnotationHelper
: Fixed parsing of annotations with dashReferencedNameHelper
: Fixed false positive
-
4.4.6 4.4.6
Fixes:
UnusedUsesSniff
: Fixed false positives
-
4.4.5 4.4.5
Fixes:
UnusedUsesSniff
: Fixed false positives of case mismatch in doccommentsForbiddenAnnotationsSniff
: fixed empty lines when fixer removes annotations
-
4.4.4 4.4.4
Fixes:
ReferenceUsedNamesOnlySniff
: Importing global functions and constants is not necessary in the global namespaceReferenceUsedNamesOnlySniff
: Some references were ignored because of bug inallowFullyQualifiedNameForCollidingClasses
optionEarlyExitSniff
: Fixed fixing of complex conditionsEarlyExitSniff
: Improved fixing conditions with commentsEarlyExitSniff
: Fixed fixing of two negative conditionsUnusedUsesSniff
: Case mismatch should be reported in doccomments tooUnusedUsesSniff
: All occurrences of case mismatch are reported nowUseStatementHelper
: Anonymous function in function should not be detected asuse
statement (thanks to @grongor)
-
4.4.3 4.4.3
Fixes:
EarlyExitSniff
: Fixed fixing of negative logical conditionsEarlyExitSniff
: Fixed fixing of binary AND conditionReferenceUsedNamesOnlySniff
: Fixed fixing of types in annotations at the end of line (thanks to @Majkl578)