Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs

Overview

Slevomat Coding Standard

Latest version Downloads Build status Code coverage PHPStan

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

  1. Sniffs included in this standard
  1. Installation
  2. How to run the sniffs
  1. Fixing errors automatically
  2. Suppressing sniffs locally
  3. Contributing

Sniffs included in this standard

🔧 = Automatic errors fixing

🚧 = Sniff check can be suppressed locally

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 with phpcbf.
  • 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 native object typehint. It's on by default if you're on PHP 7.2+
  • enableMixedTypeHint: enforces to transform @param mixed into native mixed 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 with phpcbf.
  • 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 native int typehint. It's on by default if you're on PHP 7.4+
  • enableMixedTypeHint: enforces to transform @var mixed into native mixed typehint. It's on by default if you're on PHP 8.0+. It can be enabled only when enableNativeTypeHint is enabled too.
  • enableUnionTypeHint: enforces to transform @var string|int into native string|int typehint. It's on by default if you're on PHP 8.0+. It can be enabled only when enableNativeTypeHint 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 with phpcbf.
  • 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 native object typehint. It's on by default if you're on PHP 7.2+
  • enableStaticTypeHint: enforces to transform @return static into native static typehint. It's on by default if you're on PHP 8.0+
  • enableMixedTypeHint: enforces to transform @return mixed into native mixed typehint. It's on by default if you're on PHP 8.0+
  • enableUnionTypeHint: enforces to transform @var string|int into native string|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 requires null on first position in the type hint, last requires last position. None is set by default so null 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: requires declare on the first line right after <?php
  • linesCountBeforeDeclare: allows to set 0 to N lines to be between declare and previous statement. This option is ignored when declareOnFirstLine is enabled.
  • linesCountAfterDeclare: allows to set 0 to N lines to be between declare and next statement
  • spacesCountAroundEqualsSign: 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 for final 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: ignores if that is standalone in scope, like this:
foreach ($values as $value) {
	if ($value) {
		doSomething();
	}
}
  • ignoreOneLineTrailingIf: ignores if 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: ignores if 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 to false): 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 and TestCase 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 and Cache 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 with new keyword or accessing with :: operator
  • forbiddenExtends: forbids extending with extends keyword
  • forbiddenInterfaces: forbids usage in implements section
  • forbiddenTraits: forbids imports with use 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 to false): 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 to false): 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 brackets
  • enableEmptyArrayCheck (defaults to false): 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 comment
  • maxLinesCountBeforeWithComment: maximum number of lines before constant with a doc comment
  • minLinesCountBeforeWithoutComment: minimum number of lines before constant without a doc comment
  • maxLinesCountBeforeWithoutComment: 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 lines
  • maxLinesCount: 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 comment
  • maxLinesCountBeforeWithComment: maximum number of lines before property with a doc comment
  • minLinesCountBeforeWithoutComment: minimum number of lines before property without a doc comment
  • maxLinesCountBeforeWithoutComment: 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 with excludedMethodPatterns, 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 with includedMethodPatterns, 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 with excludedMethodPatterns, 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 with includedMethodPatterns, 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 first use.
  • linesCountBeforeFirstUseWhenFirstInClass: allows to configure the number of lines before first use when the use is the first statement in the class.
  • linesCountBetweenUses: allows to configure the number of lines between two use statements.
  • linesCountAfterLastUse: allows to configure the number of lines after last use.
  • linesCountAfterLastUseWhenLastInClass: allows to configure the number of lines after last use when the use 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 in case or default
  • 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 in case or default
  • linesCountAfterWhenLastInLastCaseOrDefault: allows to configure the number of lines after jump statement that is last in last case or default
  • 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 to 0)
  • minExpressionsLength (defaults to null): 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 &&, || or xor), 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 to false): 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 to false): 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 length
  • ignoreComments: whether or not to ignore line length of comments
  • ignoreImports: 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 after fn.
  • 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 to true)
  • 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 to true): 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 to true): sets the required order to classes, functions and constants. false sets the required order to classes, constants and functions.
  • 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 before namespace.
  • linesCountAfterNamespace: allows to configure the number of lines after namespace.

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 first use.
  • linesCountBetweenUseTypes: allows to configure the number of lines between two different types of use.
  • linesCountAfterLastUse: allows to configure the number of lines after last use.

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 path app/services/Product/Product.php is expected to contain Slevomat\Product\Product, not Slevomat\services\Product\Product.
  • extensions: allow different file extensions. Default is php.
  • 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 or private 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 or Error suffixes) but aren't, you can add them to ignoredNames property and the sniff won't enforce them to be fully qualified. Classes with Error suffix has to be added to ignored only if they are in the root namespace (like LibXMLError).

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 to false): 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 without use (i.e. phpversion()).
  • allowFallbackGlobalConstants: allows using global constants via fallback name without use (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 above return 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 to false).

SlevomatCodingStandard.ControlStructures.UselessTernaryOperator 🔧

Reports useless ternary operator where both branches return true or false.

Sniff provides the following settings:

  • assumeAllConditionExpressionsAreAlreadyBoolean (defaults to false).

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 🔧 symbol support automatic fixing of coding standard violations. To fix your code automatically, run phpcbf instead of phpcs:

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 🚧 symbol can be suppressed for a specific piece of code using an annotation. Consider the following example:

/**
 * @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.

Comments
  • UnusedUsesSniff and case mismatch

    UnusedUsesSniff and case mismatch

    Hi,

    I can see via https://github.com/slevomat/coding-standard/commit/7795645f18aebbff58ae1d0062ec6590642d0b3f there was a change to search for case-mismatch.. however Im not sure if this is a behaviour change. In the example below its flagged because exception !== Exception however.. this is a just a documentation comment about the class.. Was this meant to target types in docblocks only?

    Documentation like this tends to be written in non-programming syntax, whats the thought behind this change long term?

    
    use Exception;
    use Symfony\Component\HttpFoundation\Response;
    
    /**
    * An exception that encodes a fully-formed HTTP response.
    */
    class ResponseException extends Exception
    

    Another example, a simple documentation comment written in english.

    /**
     * A custom Doctrine type for personal details in a checkout.
     */
    class PersonalDetailsType extends Type
    
    opened by gsdevme 30
  • Removal of `dealerdirect/phpcodesniffer-composer-installer` in a new major?

    Removal of `dealerdirect/phpcodesniffer-composer-installer` in a new major?

    Let's face it: composer plugins are a pain.

    I'd better not have them at all, and run everything with --no-plugins during installation.

    I wonder if it's possible to remove dealerdirect/phpcodesniffer-composer-installer in the next major release, and to endorse (in the docs) referencing the sniff via absolute vendor/ path?

    opened by Ocramius 26
  • TypeHintDeclarationSniff removing Doctrine annotations

    TypeHintDeclarationSniff removing Doctrine annotations

    Several times now I got this:

    Method ........ does not need documentation comment.                                                                                          
    (SlevomatCodingStandard\Sniffs\TypeHints\TypeHintDeclarationSniff)   
    

    And the entire docblock with the annotations was removed.

    I know I can set some annotations to not be removed like this with usefulAnnotations but my application uses a lot of Doctrine annotations (Doctrine entities, Symfony validators, Arachne/Verifier rules and so on) so the list would be really really long and I could easily forget something. Is there a better way to prevent removal of Doctrine annotations?

    opened by enumag 21
  • FullyQualifiedGlobal{Constants,Functions}Sniff: Configuration options needed

    FullyQualifiedGlobal{Constants,Functions}Sniff: Configuration options needed

    It should be possible to:

    • specify whether use is allowed for referencing functions/constants,
    • specify whether \ is allowed for referencing functions/constants,
    • specify how to apply the fix, either by prepending \ (currently forced now) or by adding use.

    Original PR: #235

    opened by Majkl578 19
  • Sniff to have one attribute per line

    Sniff to have one attribute per line

    #[Column(unique: true)] protected string $name;
    #[Cache] #[ManyToOne(targetEntity: 'City', inversedBy: 'attractions')] #[JoinColumn(name: 'city_id', referencedColumnName: 'id')] protected City $city;
    

    would be good to be able to enforce

    #[Column(unique: true)]
    protected string $name;
    
    #[Cache] 
    #[ManyToOne(targetEntity: 'City', inversedBy: 'attractions')] 
    #[JoinColumn(name: 'city_id', referencedColumnName: 'id')] 
    protected City $city;
    

    attributes can be used also inside of function calls, constructor promotion etc.

    Would be nice to combine with https://github.com/slevomat/coding-standard/issues/1259 in order to allow alphabetical sorting of attributes.

    Maybe have an option to allow inline attributes in case that there is just one? can be useful for function params:

    function passwordHash(#[\SensitiveParameter] string $password) {
        var_dump(debug_backtrace());
    }
    
    Enhancement 
    opened by michnovka 17
  • SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint suggests void union return type for void|bool

    SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint suggests void union return type for void|bool

    Using recent tag 7.0.19 and following code:

    /**
       * @return void|bool
       */
      public function method(string $argument) {
        if ($argument !== 'foo')) {
          return FALSE;
        }
        return parent::method($entity);
      }
    

    Method \Vendor\project\Class::method() does not have native return type hint for its return value but it should be possible to add it based on @return annotation "void|bool".

    However, the RFC doesn't allow combining void in union with anything else. I can't change the interface either, because the parent class is out of my control and is provided by another library project. And it is what returns void.

    Wontfix 
    opened by heddn 17
  • Contradicting switch with return

    Contradicting switch with return

    Currently there there are two contradicting rules. return requires no enters after it, while case requires enters after it. Both rules I want to keep but in this instance I want to use the case rule so it is more clear of the separate cases. unforunatly I cannot see a parameter option of any kind to do this.

    Code

    The following code states (correctly) that there is an enter missing

    switch ($baz) {
        case 'foo':
            return 'foo';
        case 'bar':
            return 'bar';
    }
    

    (phpcs output)

    136 | ERROR | [x] Expected 1 lines after "case", found 0.
    (SlevomatCodingStandard.ControlStructures.BlockControlStructureSpacing.IncorrectLinesCountAfterControlStructure)
    138 | ERROR | [x] Expected 1 lines before "case", found 0.
    (SlevomatCodingStandard.ControlStructures.BlockControlStructureSpacing.IncorrectLinesCountBeforeControlStructure)
    

    To fix this an enter is added between the two cases, however this triggers the an issue with an enter after the return

    switch ($orderType) {
        case 'foo':
            return 'foo';
    
        case 'bar':
            return 'bar';
    }
    

    (phpcs output)

    137 | ERROR | [x] Expected 0 lines after "return", found 1.
    (SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing.IncorrectLinesCountAfterLastControlStructure)
    

    I am I missing an option that can fix this or is it one or the other rule?

    The phpcs config in use

    Enhancement 
    opened by mkroeders 16
  • UnusedUses - Classes `use`'d by Documentation Now Marked Unused

    UnusedUses - Classes `use`'d by Documentation Now Marked Unused

    We updated from 4.1.0 to 4.4.5 today and suddenly all our types that are use-d for documentation by strictly in documentation like @return DiInterface are marked unused by SlevomatCodingStandard.Namespaces.UnusedUses

    I suspect #283 may have had something to do with the break.

    The following is a broken example:

    <?php
    
    namespace Controller\cli\tools;
    
    use Iron\Controller\AbstractController;
    use Iron\Di\DiInterface;
    
    class Report extends AbstractController {
    
    	/** @var DiInterface */
    	protected $di;
    }
    

    We have an automatic process to cbf fix SlevomatCodingStandard.Namespaces.UnusedUses specifically so this came as a bit of a shock as hundreds of files suddenly had their documentation broken ;)

    opened by donatj 16
  • Feature request: isolated return statement

    Feature request: isolated return statement

    Hey,

    I've got a feature request which could improve overal code readability.

    One of my colleagues came with the convention to place a newline before a return statement in a function (and closures/anonymous functions etc.) if the function body contains other logic to increase readability.

    For example:

    // This is fine:
    function myFunction(): string
    {
        $result = $this->doSomeCode();
        $result = $this->doSomeMoreCode($result);
    
        return $result;
    }
    
    // This is also fine:
    function myFunction(): string
    {
        return $result;
    }
    
    // This comment is fine:
    function myFunction(): string
    {
        $result = $this->doSomeCode();
        $result = $this->doSomeMoreCode($result);
    
        // Some explanation here
        return $result;
    }
    
    // This comment -although questionable- could be fine:
    function myFunction(): string
    {
        $result = $this->doSomeCode();
        $result = $this->doSomeMoreCode($result);
        // Some explanation here
    
        return $result;
    }
    
    
    // This is not fine:
    function myFunction(): string
    {
        $result = $this->doSomeCode();
        $result = $this->doSomeMoreCode($result);
        return $result;
    }
    
    // This comment is not fine:
    function myFunction(): string
    {
        $result = $this->doSomeCode();
        $result = $this->doSomeMoreCode($result);
        // Some explanation here
        return $result;
    }
    
    // This might not be fine.. bit weird to have a random newline laying around:
    function myFunction(): string
    {
    
        return $result;
    }
    
    // This is already caught by PSR2.Methods.FunctionClosingBrace.SpacingBeforeClose
    function myFunction(): string
    {
        return $result;
    
    }
    

    Let me know what you think :)

    Enhancement 
    opened by Levivb 15
  • A combination of sniffs and their fixers produces syntactically invalid code

    A combination of sniffs and their fixers produces syntactically invalid code

    Below are the relevant dependency versions:

    $ composer show # truncated
    
    doctrine/coding-standard       7.0.2   The Doctrine Coding Standard is a ...
    slevomat/coding-standard       6.1.4   Slevomat Coding Standard for PHP_C...
    squizlabs/php_codesniffer      3.5.4   PHP_CodeSniffer tokenizes PHP, Jav...
    

    Consider the following code example:

    <?php
    
    declare(strict_types=1);
    
    class Problem
    {
        public function test() : int
        {
            if (true) { // Comment
                return 1;
            } else if (true) { // Comment
                return 2;
            } else { // Comment
                return 3;
            }
        }
    }
    

    All coding standard violations are reported as fixable and seem to be non-conflicting:

    ------------------------------------------------------------------------------------------------
    FOUND 5 ERRORS AFFECTING 5 LINES
    ------------------------------------------------------------------------------------------------
     10 | ERROR | [x] Expected 1 lines before "return", found 0.
        |       |     (SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing.IncorrectLinesCountBeforeControlStructure)
     11 | ERROR | [x] Usage of ELSE IF is discouraged; use ELSEIF instead
        |       |     (PSR2.ControlStructures.ElseIfDeclaration.NotAllowed)
     12 | ERROR | [x] Expected 1 lines before "return", found 0.
        |       |     (SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing.IncorrectLinesCountBeforeControlStructure)
     13 | ERROR | [x] Remove useless else to reduce code nesting.
        |       |     (SlevomatCodingStandard.ControlStructures.EarlyExit.UselessElse)
     14 | ERROR | [x] Expected 1 lines before "return", found 0.
        |       |     (SlevomatCodingStandard.ControlStructures.JumpStatementsSpacing.IncorrectLinesCountBeforeControlStructure)
    ------------------------------------------------------------------------------------------------
    

    An attempt to fix this file using phpcs fails:

    ----------------------------------------------------------------------
    FILE                                                  FIXED  REMAINING
    ----------------------------------------------------------------------
    Problem.php                                           FAILED TO FIX
    ----------------------------------------------------------------------
    A TOTAL OF 1 ERROR WERE FIXED IN 1 FILE
    ----------------------------------------------------------------------
    PHPCBF FAILED TO FIX 1 FILE
    ----------------------------------------------------------------------
    

    and produces the following code:

    <?php
    
    declare(strict_types=1);
    
    class Problem
    {
        public function test() : int
        {
            if (true) { // Comment
                return 1;
            }
    
            if (true) { // Comment
                return 2;
            }
        } else { // Comment
    
    
            return 3;
        }
    }
    }
    
    $ php -l Problem.php
    
    Parse error: syntax error, unexpected 'else' (T_ELSE), expecting function (T_FUNCTION) or const (T_CONST) in Problem.php on line 16
    Errors parsing Problem.php
    

    Replacing else if with elseif solves the syntax error issue but still doesn’t help the auto-fixing the violations.

    Bug 
    opened by morozov 14
  • Undefined index: parenthesis_closer

    Undefined index: parenthesis_closer

    vendor/slevomat/coding-standard/SlevomatCodingStandard/Sniffs/Functions/StrictCallSniff.php on line 59
    vendor/slevomat/coding-standard/SlevomatCodingStandard/Sniffs/Variables/UnusedVariableSniff.php on line 329
    

    Using version 6.3.8.

    Bug 
    opened by enumag 13
  • Recommendation on if without curly braces?

    Recommendation on if without curly braces?

    Thanks for the great work.

    In this closed issue you mention that the Exception is intended.

    Sorry for the spam, but I could use some direction as to what I would do to get around it, or exactly what is happening when I include these standards with my phpcbf configs.

    opened by MikeiLL 0
  • ParameterTypeHintSniff does not recognize list<T> as traversable

    ParameterTypeHintSniff does not recognize list as traversable

    Following method is not reported as missing native array typehint for $items.

        /**
         * @param list<string> $items
         */
        public function myMethod($items): void {}
    

    PHPStan added proper list support in 1.9.0, do you plan to implement this within slevomat/cs too? Thanks

    Enhancement 
    opened by janedbal 1
  • Pass error message data to PHPCS in fully qualified reference sniffs

    Pass error message data to PHPCS in fully qualified reference sniffs

    AbstractFullyQualifiedGlobalReference->process() makes its own call to sprintf() and then passes on that finalized error message to ->addFixableError. This means that customizations of the message for these sniffs cannot use the name of the function/constant via %s.

    Changing the call to let PHPCS do the formatting sends this data downstream for possible customization.

    opened by benvoynick 1
  • Add IntersectionTypeHintSniff

    Add IntersectionTypeHintSniff

    Add IntersectionTypeHintSniff to control the whitespaces of intersection types.

    I copied and cleaned all the logic from UnionTypeHintFormatSniff and its tests.

    opened by fancyweb 3
  • Optionally allow attributes and targets on the same line

    Optionally allow attributes and targets on the same line

    I've tested the SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing Sniff and stumbled upon an edge case. While I agree that an attributes and its target should not be on the same line, there is one situation where I'd like to allow it.

    Symfony introduced in 5.2 the #[CurrentUser] attribute for controller arguments: https://symfony.com/blog/new-in-symfony-5-2-controller-argument-attributes

    <?php
    
    class IndexController
    {
        public function index(
            #[CurrentUser] ?User $user,
            SomeServce $someServce,
            SomeOtherService $someOtherService
        ): Response {
            //do something
        }
    }
    

    It would be great if either a) the error followed by $areOnSameLine could be disabled (e.g. by the new property allowOnSameLine) https://github.com/slevomat/coding-standard/blob/da14851de59f39fb68556cb4e5cbf0a68ca27276/SlevomatCodingStandard/Sniffs/Attributes/AttributeAndTargetSpacingSniff.php#L60

    b) or by a special handling for argument attributes (controlled by the new property allowArgumentAttributesOnSameLine).

    What do you think?

    opened by stlrnz 0
  • Sniff to check enum case spacing

    Sniff to check enum case spacing

    I'd like to ask if there is an existing Sniff to check for spaces between cases in native enum declarations? Something like SlevomatCodingStandard.Classes.PropertySpacing would be nice.

    I want to prevent declations like this.

    <?php
    
    enum SimpleEnum
    {
        case C1;
    
        case C2;
        case C3;
    }
    

    And instead force this.

    <?php
    
    enum SimpleEnum
    {
        case C1;
        case C2;
        case C3;
    }
    
    Enhancement 
    opened by stlrnz 0
Releases(8.7.1)
  • 8.7.1(Dec 15, 2022)

  • 8.7.0(Dec 13, 2022)

    🔧 Improvements

    • Support for phpstan/phpdoc-parser 1.15
    • Support for phpstan/phpdoc-parser 1.14
    • SlevomatCodingStandard.Attributes.AttributesOrder: New option orderAlphabetically
    • SlevomatCodingStandard.Attributes.AttributesOrder: Attributes could be ordered by mask (thanks to @alexndlm)

    🐛 Fixes

    • SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing: Fixed fixer
    Source code(tar.gz)
    Source code(zip)
  • 8.6.4(Nov 14, 2022)

    🔧 Improvements

    • Improved annotations parsing
    • SlevomatCodingStandard.Classes.ClassConstantVisibility: Added support for traits with constants
    • SlevomatCodingStandard.Classes.ConstantSpacing: Added support for traits with constants

    🐛 Fixes

    • SlevomatCodingStandard.Attributes.DisallowAttributesJoining: Fix for attribute with trailing comma (thanks to @javer)
    Source code(tar.gz)
    Source code(zip)
  • 8.6.3(Nov 10, 2022)

    🐛 Fixes

    • Slevomat.Namespaces.ReferenceUsedNamesOnly: Fixed fixer when there's conflict with Slevomat.Namespaces.UnusedUses
    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for int<0, max> and int<min, 100>
    • SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing: Fixed false positive for comment after attribute
    Source code(tar.gz)
    Source code(zip)
  • 8.6.2(Oct 22, 2022)

  • 8.6.1(Oct 21, 2022)

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.12.0

    🐛 Fixes

    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for global constants
    • SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration: Fixed false positives for constants
    Source code(tar.gz)
    Source code(zip)
  • 8.6.0(Oct 17, 2022)

    🆕 New sniffs

    • Added SlevomatCodingStandard.Attributes.AttributesOrder
    • Added SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing
    • Added SlevomatCodingStandard.Attributes.DisallowMultipleAttributesPerLine
    • Added SlevomatCodingStandard.Attributes.DisallowAttributesJoining (thanks to @michnovka)
    • Added SlevomatCodingStandard.Attributes.RequireAttributeAfterDocComment

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.11.0
    • Support for @phpstan-self-out/@phpstan-this-out
    • Support for @param-out annotation`
    • Support for @template with default value
    • Add dev Composer keyword (thanks to @GaryJones)

    🐛 Fixes

    • Improved detection of references in double quotes strings
    Source code(tar.gz)
    Source code(zip)
  • 8.5.2(Sep 27, 2022)

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled
    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled
    Source code(tar.gz)
    Source code(zip)
  • 8.5.1(Sep 23, 2022)

  • 8.5.0(Sep 21, 2022)

    🔧 Improvements

    • PHP 8.2: Support for standalone null, true and false type hints
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Improved support for native simple types
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: New option enableIntegerRanges
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: New option enableAdvancedStringTypes
    • Support of phpstan/phpdoc-parser 1.8.0

    🐛 Fixes

    • SlevomatCodingStandard.Classes.PropertyDeclaration: Fixed false positive
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Fixed false positive
    • SlevomatCodingStandard.ControlStructures.DisallowYodaComparison/RequireYodaComparison: Fixed support for condition in arrow function
    • SlevomatCodingStandard.Classes.DisallowMultiPropertyDefinition: Fixed false positives for old array definition style
    • SlevomatCodingStandard.Variables.UselessVariable: Fixed false positives
    Source code(tar.gz)
    Source code(zip)
  • 8.4.0(Aug 9, 2022)

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.7.0

    🐛 Fixes

    • Fixed detection of some PHP 8.1 types
    • SlevomatCodingStandard.PHP.RequireNowdoc: Accepts escaped sequences (thanks to @dg)
    • SlevomatCodingStandard.Functions.RequireSingleLineCall: Skip calls with multi-line double-quoted string (thanks to @schlndh)
    • SlevomatCodingStandard.PHP.UselessParentheses: Fixed false positive with xor
    • SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator: Try to ignore string offsets
    Source code(tar.gz)
    Source code(zip)
  • 8.3.0(Jul 16, 2022)

    🆕 New sniffs

    • Added SlevomatCodingStandard.Complexity.Cognitive (thanks to @bkdotcom)
    • Added SlevomatCodingStandard.Files.FileLength (thanks to @bkdotcom)
    • Added SlevomatCodingStandard.Classes.ClassLength (thanks to @bkdotcom)

    🐛 Fixes

    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Do not throw away static type (thanks to @simPod)
    Source code(tar.gz)
    Source code(zip)
  • 8.2.0(Jul 8, 2022)

    🆕 New sniffs

    • Added SlevomatCodingStandard.Classes.BackedEnumTypeSpacing

    🔧 Improvements

    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: MissingTraversableTypeHintSpecification is not reported when promoted property has @var annotation
    Source code(tar.gz)
    Source code(zip)
  • 8.1.0(Jun 24, 2022)

    🔧 Improvements

    • SlevomatCodingStandard.Classes.PropertyDeclaration: New option checkPromoted to enable check of promoted properties
    • SlevomatCodingStandard.Classes.PropertyDeclaration: New option enableMultipleSpacesBetweenModifiersCheck to enable check of spaces between property modifiers
    • SlevomatCodingStandard.Classes.PropertyDeclaration: Improved error messages
    • SlevomatCodingStandard.Classes.ForbiddenPublicProperty: New option checkPromoted to enable check of promoted properties

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fix inconsistent enableIntersectionTypeHint (thanks to @schlndh)
    Source code(tar.gz)
    Source code(zip)
  • 8.0.1(Jun 22, 2022)

    🐛 Fixes

    • Group use statements are ignored - we don't support them
    • SlevomatCodingStandard.PHP.UselessParentheses: Fixed false positive
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Fixed internal error (thanks to @schlndh)
    Source code(tar.gz)
    Source code(zip)
  • 8.0.0(Jun 17, 2022)

    🔧 Improvements

    • Support for intersection types
    • Support for readonly properties
    • Support for enums
    • Support for never type hint
    • Support for more unofficial type hints
    • SlevomatCodingStandard.Classes.PropertyDeclaration: Checks also order of modifiers
    • SlevomatCodingStandard.Classes.ClassStructure: Support for enum cases and readonly properties

    🐛 Fixes

    • SlevomatCodingStandard.Classes.PropertyDeclaration: Fixed missing support for only static property
    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fixed missing support for only static property
    • SlevomatCodingStandard.Commenting.EmptyComment: Fixed internal error
    • SlevomatCodingStandard.Classes.ForbiddenPublicProperty: Fixed internal error
    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for @psalm-import-type in @psalm-var
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Ignore unsupported unofficial type hints

    ⚠️BC breaks

    • SlevomatCodingStandard.TypeHints.PropertyTypeHintSpacing renamed to SlevomatCodingStandard.Classes.PropertyDeclaration
    • SlevomatCodingStandard.Classes.ClassStructure: Removed option enableFinalMethods
    • Removed error SlevomatCodingStandard.Namespaces.UnusedUses.MismatchingCaseSensitivity
    Source code(tar.gz)
    Source code(zip)
  • 7.2.1(May 25, 2022)

    🐛 Fixes

    • SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly: Fixed false positives for colliding functions and constants
    • SlevomatCodingStandard.Commenting.DisallowCommentAfterCode: Don't break multi-line string during auto-fix (thanks to @schlndh)
    • Fixed detection of function object
    Source code(tar.gz)
    Source code(zip)
  • 7.2.0(May 6, 2022)

    🆕 New sniffs

    • Added SlevomatCodingStandard.Functions.DisallowTrailingCommaInClosureUse
    • Added SlevomatCodingStandard.Functions.RequireTrailingCommaInClosureUse

    🔧 Improvements

    • Support for offset access type syntax in annotations
    • Support for @phpstan-assert/@psalm-assert annotations
    • SlevomatCodingStandard.Whitespaces.DuplicateSpacesSniff: New option ignoreSpacesInMatch
    • SlevomatCodingStandard.Functions.DisallowTrailingCommaInCall: New option onlySingleLine
    • SlevomatCodingStandard.Functions.DisallowTrailingCommaInDeclaration: New option onlySingleLine

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: Fixed internal error
    • SlevomatCodingStandard.ControlStructures.UselessIfConditionWithReturn: Fixed internal error
    • SlevomatCodingStandard.Functions.RequireSingleLineCall: Fixed false positive
    • SlevomatCodingStandard.Variables.UnusedVariable: Resolve false positives with increment/decrement operators (thanks to @aadmathijssen)
    • SlevomatCodingStandard.Variables.UnusedVariable: allow increment/decrement operators after yield (thanks to @aadmathijssen)
    Source code(tar.gz)
    Source code(zip)
  • 7.1.0(Mar 29, 2022)

    ⚠️ Removed support for PHP 7.1

    🆕 New sniffs

    • Added SlevomatCodingStandard.Classes.RequireAbstractOrFinal (thanks to @roslov)
    • Added SlevomatCodingStandard.Exceptions.DisallowNonCapturingCatch (thanks to @olsavmic)

    🔧 Improvements

    • Support for conditional types in annotations
    • SlevomatCodingStandard.Numbers.RequireNumericLiteralSeparator: Added option ignoreOctalNumbers
    • SlevomatCodingStandard.Functions.FunctionLength: New options includeComments and includeWhitespace (thanks to @bkdotcom)
    Source code(tar.gz)
    Source code(zip)
  • 7.0.20(Mar 25, 2022)

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: Improved - Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Improved - Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Improved - Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: It was not possible to suppress some errors
    • SlevomatCodingStandard.Classes.ParentCallSpacing: Fixed false positive
    Source code(tar.gz)
    Source code(zip)
  • 7.0.19(Mar 1, 2022)

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: Type alias should not be reported as "missing traversable type hint specification"
    • SlevomatCodingStandard.ControlStructures.RequireYodaComparison: Fixed false positives with match
    • SlevomatCodingStandard.ControlStructures.DisallowYodaComparison: Fixed false positives with match
    • SlevomatCodingStandard.Commenting.DocCommentSpacing: Fixed internal error
    • SlevomatCodingStandard.Variables.UnusedVariable: Fixed false positive
    • SlevomatCodingStandard.Variables.UnusedVariable: Fixed missing report when option ignoreUnusedValuesWhenOnlyKeysAreUsedInForeach is enabled
    • SlevomatCodingStandard.Functions.RequireTrailingCommaInCall: Fixed false positive
    • ReferencedNameHelper: Fixed searching of class references in heredoc
    • Ignore invalid @template and @type annotations
    Source code(tar.gz)
    Source code(zip)
  • 7.0.18(Dec 7, 2021)

  • 7.0.17(Dec 6, 2021)

    🐛 Fixes

    • SlevomatCodingStandard.Namespaces.UnusedUses: Improved detection of relative name in generic annotation
    • SlevomatCodingStandard.Classes.ClassConstantVisibility: Added support for final constants
    • SlevomatCodingStandard.Functions.RequireTrailingCommaInCall: Skip instances on same line as closing parenthesis (thanks to @donatj)
    Source code(tar.gz)
    Source code(zip)
  • 7.0.16(Oct 22, 2021)

    🐛 Fixes

    • SlevomatCodingStandard.Classes.ModernClassNameReference: Don't flag method declarations (thanks to @jrfnl)
    • SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration: Fixed false positive
    • SlevomatCodingStandard.ControlStructures.NewWithParentheses: Fixed false positive
    • Appended logic in ReferencedNameHelper for find names of class inside double quotes (thanks to @AIlkiv)
    Source code(tar.gz)
    Source code(zip)
  • 7.0.15(Sep 9, 2021)

    🐛 Fixes

    • UseSpacingSniff: Fixed false positive
    • TypeCastSniff: Fixed internal error
    • RequireConstructorPropertyPromotionSniff: Fixed false positives
    • ClassStructureSniff: Add missing magic methods (thanks to @jrfnl)
    • Updated phpstan/phpdoc-parser (thanks to @alexndlm)
    Source code(tar.gz)
    Source code(zip)
  • 7.0.14(Aug 26, 2021)

    🐛 Fixes

    • InlineDocCommentDeclarationSniff: Don't report missing assigment for $this
    • ParameterTypeHintSniff, ReturnTypeHintSniff, PropertyTypeHintSniff: Short nullable is now reported as useless annotation too
    • Don't try to find references in double quoted string - it's difficult to parse it with PHPCS
    Source code(tar.gz)
    Source code(zip)
  • 7.0.13(Jul 29, 2021)

  • 7.0.12(Jul 12, 2021)

  • 7.0.10(Jul 9, 2021)

    🐛 Fixes

    • RequireNonCapturingCatchSniff: Fixed false positive
    • ReturnTypeHintSniff: It knows unofficial void type hints
    • ReturnTypeHintSniff: Method returning value with void annotation is reported only
    • ParentCallSpacingSniff: Fixed false positive
    • Fixed array shapes parsing
    Source code(tar.gz)
    Source code(zip)
  • 7.0.9(Jun 7, 2021)

    🐛 Fixes

    • UselessInheritDocCommentSniff: Fixed false positive
    • RequireNullSafeObjectOperatorSniff: Fixed false positives
    • UnusedVariableSniff: Fixed false positive
    Source code(tar.gz)
    Source code(zip)
Owner
Slevomat
Slevomat
PHP Compatibility check for PHP_CodeSniffer

PHP Compatibility Coding Standard for PHP CodeSniffer This is a set of sniffs for PHP CodeSniffer that checks for PHP cross-version compatibility. It

PHPCompatibility 1.9k Dec 28, 2022
Baseline tool for PHP_CodeSniffer

PHP_CodeSniffer Baseliner This tool enables you to integrate PHP_CodeSniffer into an existing project by automatically adding phpcs:ignore and phpcs:d

ISAAC 13 Nov 26, 2022
phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in PHP code

phpcs-security-audit v3 About phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in

Floe design + technologies 655 Jan 3, 2023
A tool to automatically fix PHP Coding Standards issues

PHP Coding Standards Fixer The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP codi

null 11.6k Jan 3, 2023
PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions.

PHPCheckstyle Overview PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions. The tools checks the inpu

PHPCheckstyle 157 Dec 5, 2022
A tool to automatically fix PHP Coding Standards issues by Dragon Code.

A tool to automatically fix PHP Coding Standards issues by Dragon Code.

The Dragon Code 24 Aug 27, 2022
Provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths

sebastian/environment This component provides functionality that helps writing PHP code that has runtime-specific (PHP / HHVM) execution paths. Instal

Sebastian Bergmann 6.5k Jan 3, 2023
The Stopwatch component provides a way to profile code.

Stopwatch Component The Stopwatch component provides a way to profile code.

Symfony 2.6k Dec 28, 2022
Coding-standard - Magento PHP CodeSniffer Coding Standard

ECG Magento Code Sniffer Coding Standard ECG Magento Code Sniffer Coding Standard is a set of rules and sniffs for PHP_CodeSniffer tool. It allows aut

Magento ECG 309 Jan 3, 2023
WPForms coding standards are based on the WordPress Coding Standards and the PHPCompatibility Coding Standards and help create strict and high-quality code.

WPForms coding standards are based on the WordPress Coding Standards and the PHPCompatibility Coding Standards and help create strict and high-quality code.

Awesome Motive, Inc. 7 Nov 29, 2022
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

About PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a define

Squiz Labs 9.9k Jan 4, 2023
Composer installer for PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

Dealerdirect 462 Dec 22, 2022
This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

PHPCSStandards 393 Feb 25, 2022
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Squiz Labs 9.9k Jan 5, 2023
Check modules in app/code and vendor for PHP 8 compatibility status - PHP_CodeSniffer & php-compatibility standard

M2 PHP version compatibility check How To use Requires PHP 7.3+ | PHP 8 This app will run PHP_CodeSniffer with phpcompatibility/php-compatibility on t

William Tran 24 Oct 13, 2022
This plugin allows you to create many-to-many relationships between pages in Kirby and synchronizes them on both sides.

Kirby 3 Many To Many Field This plugin allows you to create many-to-many relationships between pages in Kirby.

Jonas Holfeld 41 Nov 19, 2022
This is a lightweight package that allows you assign roles and permissions to any Laravel model, or on a pivot table (many to many relationship).

Simple Laravel roles and permissions Introduction This package allows you to assign roles and permissions to any laravel model, or on a pivot table (m

null 52 Nov 10, 2022
Magento 1.x Coding Standard

Magento Extension Quality Program Coding Standard ⚠️ Versions 3.0.0 and above of the MEQP Coding Standard are for Magento 1.x code only. To check Mage

Magento 224 Nov 29, 2022
Magento Coding Standard

Magento Coding Standard A set of Magento rules for PHP_CodeSniffer tool. Installation within a Magento 2 site To use within your Magento 2 project you

Magento 290 Dec 31, 2022
Documentation on clean coding and demonstration of studied clean coding principals with PHP.

practice-php-clean-code Documentation on clean coding and demonstration of studied clean coding principals with PHP. The document contained in this re

Ferdous Islam 1 Feb 21, 2022