Přehled pravidel
Všechna vestavěná pravidla DressCode podle oblasti, u každého odkaz na stránku s příklady a volbami.
Pravidlo, které porušení jen hlásí a neopravuje, je tak označeno, stejně jako pravidlo, jehož opravy mohou změnit
chování kódu a čekají na svolení v klíči fixRisky; pravidlo pro syntaxi novějšího PHP nese verzi, od
které se zapíná.
Pravidla se zapínají standardem, skupinou nebo
jednotlivě v konfiguraci; jméno pravidla je
to, co vidíte ve výpisu dresscode check, a dresscode explain <pravidlo> k němu vypíše popis
a volby.
Soubor
Co platí pro celý soubor nebo pro každý jeho řádek: tagy, kódování, konce řádků, hlavička.
- declareSpacing: Removes whitespace inside a
declarestatement. - eofLineEnding: Ends the file with exactly one line ending.
- fullOpeningTag: Requires the
<?phpopening tag. - lineEnding: Unifies line endings.
- lineLength Řádek širší než délka řádku z konfigurace se ohlásí; opravit ho pravidlo neumí. (jen hlásí)
- noBom: Removes the UTF-8 byte order mark.
- noClosingTag: Removes the closing tag at the end of the file.
- noInvisibleCharacters: Removes or escapes invisible characters in comments and strings, reports them in names.
- noTrailingWhitespace: Removes whitespace at the end of lines.
- strictTypesRequired: Requires
declare(strict_types=1)as the first statement of a file. (rizikové opravy)
Jmenné prostory a importy
Importy a zápis jmen tříd, funkcí a konstant.
- importNotation: Writes the imports of each kind one per use statement or all in one, and expands group use declarations or writes the imports of one namespace as one.
- multilineImport: Spreads a group use over lines where its line would be too long, its names filling the lines.
- nameFallback: Writes a global function or constant in a namespace qualified, or bare and reached by the fallback at run time. (rizikové opravy)
- nameNotation: Writes a referenced name imported or with the leading backslash.
- nativeClassCasing: Writes the names of internal classes, interfaces and enums in their declared case.
- noReservedNames: Reports the names of declarations and imports that PHP 8.6 reserved. (jen hlásí)
- noUnlistedNamespacedDeclarations: Reports a function or a constant declared in a namespace that the configuration does not list. (jen hlásí)
- orderedImports: Sorts use statements alphabetically, classes before functions before constants.
- unusedImports Import, který kód nikde nepoužije, se odstraní.
- uselessAlias: Removes an import alias equal to the imported name.
- uselessLeadingBackslash: Removes the leading backslash from imported names and from names referenced in the global namespace.
- uselessSameNamespaceImport: Removes imports of names from the current namespace.
Třídy
Deklarace třídy a jejích členů.
- classConstantForConstantCall: Fetches a class constant by its name instead of asking
constant()for it. (PHP 8.3+) - classDefinitionSpacing: Puts single spaces in the head of a class declaration.
- classNameReferenceForString: Writes a class name held in a string as
::class. (rizikové opravy) - finalInternalClass: Makes classes annotated as internal final. (rizikové opravy)
- getClassNotation: Uses
::classinstead ofget_class()and__CLASS__. (rizikové opravy) - kindInClassName: Decides whether the name of a class, interface or trait repeats its kind. (jen hlásí)
- nameCasing: Reports declared names that do not follow the case convention configured for their kind. (jen hlásí)
- noConstructorReturnValues: Removes the value returned from a constructor or a destructor, which PHP 8.6 deprecated.
- noFinalParents: Reports a class extending a final one. (jen hlásí)
- noNullDebugInfo: Returns an empty array from
__debugInfo()where it returnsnull. (rizikové opravy) - noSleepAndWakeup: Reports the
__sleep()and__wakeup()methods PHP 8.5 soft-deprecated. - noStaticThis: Reports
$thisused where no object is available. (jen hlásí) - noUnimplementedAbstractMethods: Reports an abstract method a class that is not abstract inherits and does not implement. (jen hlásí)
- orderedMembers: Orders class members by kind and visibility.
- overrideAttributeRequired: Marks a member overriding an inherited one with
#[\Override]. (PHP 8.3+) - overrideSignature: Declares an overriding method the way the ancestor declares it: its types, its parameters and their names. (rizikové opravy)
- promotedPropertyForAssignment: Promotes a constructor parameter that is only assigned to a property. (rizikové opravy, PHP 8.0+)
- readonlyClassForReadonlyMembers: Marks a class whose every property is readonly as readonly. (PHP 8.2+)
- readonlyForAnnotation: Replaces the
@readonlyannotation with thereadonlykeyword. (rizikové opravy, PHP 8.1+) - readonlyForUnwrittenProperty: Marks a property written only in the constructor, or not at all, as readonly. (rizikové opravy, PHP 8.1+)
- selfForCurrentClass: Replaces the name of the current class with
self. (rizikové opravy) - serializeMethodsRequired: Reports a class implementing
Serializablewithout__serialize()and__unserialize(). (jen hlásí) - singleMemberPerDeclaration: Splits a declaration of several constants, properties or traits into one per member.
- singleMemberPerLine: Puts every member of a class on its own line.
- staticForMethodWithoutThis: Marks a private method that does not use
$thisas static. (rizikové opravy) - staticSetStateRequired: Declares
__set_state()static, which is how PHP calls it. - stringableRequired: Declares a class with a
__toString()method asStringable. (PHP 8.0+) - uselessModifier: Removes a member modifier the class already implies.
- uselessNullInitialization: Removes the explicit
nullinitialization of untyped properties. - uselessOverridingMethod: Removes a method that only calls the parent method with the same arguments. (rizikové opravy)
- uselessReturnTypeWillChange: Removes
#[\ReturnTypeWillChange]from a method that declares the return type of the method it implements. (PHP 8.1+) - visibilityRequired: Requires visibility on class members and orders their modifiers.
Funkce
Deklarace i volání funkcí a metod, parametry a argumenty.
- arrayFirstNotation: Reads the first or the last element of an array with
array_first()andarray_last(). (rizikové opravy, PHP 8.5+) - arrowFunction: Replaces a closure returning a single expression with an arrow function.
- callableNotation: Writes a callable as a first-class callable or, from PHP 8.6, a closure forwarding its parameters as a partial application. (rizikové opravy, PHP 8.1+)
- clampForMinMax: Replaces a
max()around amin()holding a value between bounds withclamp(). (rizikové opravy, PHP 8.6+) - commentedOutFunction: Comments out statements calling the configured debugging functions. (rizikové opravy)
- csvEscapeArgumentRequired: Writes out the
escapeargument of the CSV functions, whose default PHP 8.4 deprecated. - firstClassCallableForStrings: Writes a callable naming
self,parentorstaticin a string as a first-class callable. (PHP 8.1+) - functionNameSpacing: Removes whitespace between a function name and its parentheses.
- getDebugTypeForTernary: Replaces a ternary asking whether a value is an object with
get_debug_type(). (rizikové opravy, PHP 8.0+) - jsonValidateForDecode: Replaces
json_decode()called only to test the input withjson_validate(). (rizikové opravy, PHP 8.3+) - mbConvertEncodingForUtf8: Replaces the deprecated
utf8_encode()andutf8_decode()withmb_convert_encoding(). (rizikové opravy) - multilineCall: Puts every argument of a multi-line call on its own line.
- multilineSignature: Splits long signatures and constructors with promoted properties into one parameter per line.
- namedArgumentSpacing: Normalizes whitespace around the colon of a named argument.
- nativeFunctionCasing: Calls native functions in lowercase.
- newInitializerForNullDefault: Gives a parameter defaulting to null the object its body puts in its place as the default. (rizikové opravy, PHP 8.1+)
- noAliasFunctions: Calls a function by its canonical name instead of an alias. (rizikové opravy)
- noCallUserFunc: Calls a callable directly instead of through
call_user_func(). (rizikové opravy, PHP 7.0+) - noConversionFunctions: Uses a cast instead of
intval()and friends. (rizikové opravy) - noDeprecatedArguments: Reports the values of arguments the targeted version of PHP deprecated. (jen hlásí)
- noDeprecatedFunctions: Reports calls of internal functions deprecated in the targeted version of PHP. (jen hlásí)
- noDirectInvokeCalls: Calls an invokable object directly instead of its
__invoke()method. - noDirnameOfFile: Replaces
dirname(__FILE__)with__DIR__and nesteddirname()calls with thelevelsargument. (rizikové opravy) - noInnerFunctions: Reports a function declared inside another function. (jen hlásí)
- noIsNull: Replaces
is_null()with a comparison withnull. (rizikové opravy) - noManualEmptyStringTests: Tests whether a string is empty by comparing it with the empty string.
- noManualSubstringTests: Replaces a hand-written test for a substring with
str_contains(),str_starts_with()orstr_ends_with(). (rizikové opravy, PHP 8.0+) - noSettype: Assigns a cast instead of calling
settype(). (rizikové opravy) - optimizedCallNotation: Writes the arguments of a call PHP optimizes positionally and reports unpacking in it. (rizikové opravy)
- roundingModeNotation: Writes the rounding mode of
round()as a case of theRoundingModeenum. (PHP 8.4+) - sensitiveParameterRequired: Marks the parameters the configuration names with
#[\SensitiveParameter]. (PHP 8.2+) - staticClosure: Declares a closure that does not use
$thisasstatic. (rizikové opravy) - strictCall: Calls
in_array(),array_search(),array_keys(),base64_decode()andmb_detect_encoding()with$strict = true. (rizikové opravy) - uselessArguments: Removes the arguments PHP ignores and those that repeat the default of their parameter.
- uselessNoOpCall: Removes calls that have done nothing since PHP 8.0 or 8.1: the functions freeing an object and
setAccessible(). (PHP 8.0+) - uselessParameterDefault: Removes a default value that a required parameter makes unreachable.
Řízení toku
Řídicí struktury, příkazy, bloky a výjimky.
- arrayFunctionForFilter: Asks with
array_any(),array_all(),array_find()andarray_find_key()whatarray_filter()was built for. (rizikové opravy, PHP 8.4+) - arrayFunctionForForeach: Replaces a
foreachthat only searches or tests its items witharray_any(),array_all(),array_find()orarray_find_key(). (PHP 8.4+) - controlStructureBraces: Encloses the body of every control structure in braces.
- earlyExit: Turns a trailing
ifinto a guard that leaves early, and anelsethat leaves into the first branch. - elseifKeyword: Replaces
else ifwithelseif. - fallThroughComment: Requires a comment on an intentional case fall-through.
- matchForSwitch: Writes a
switchwhose every case assigns or returns one value as amatch. (rizikové opravy, PHP 8.0+) - multilineCondition: Writes a condition of
if,elseif,whileanddo-whilein the shape the configuration asks for. - noAlternativeSyntax: Replaces the alternative syntax with braces.
- noContinueInSwitch: Leaves a
switchwithbreak, never withcontinue. - noEmptyStatements: Removes empty statements.
- noFinallyReturns: Reports a
returninsidefinally, which PHP 8.6 deprecated. (jen hlásí) - noUnreachableCatches: Reports a
catchblock following one that catchesThrowable. (jen hlásí) - referenceThrowableOnly: Reports references to the general
ExceptionwhereThrowablebelongs. (jen hlásí) - returnForBooleanIf: Replaces an
ifreturningtrueorfalsewith areturnof the condition. - switchCaseColon: Ends
caseanddefaultwith a colon. - switchCaseSpacing: Removes whitespace before the colon of a
case. - ternaryForIf: Uses the ternary operator where an
if-elseonly picks one of two values. - throwExpressionForNullGuard: Writes a
throwguarding an assigned value against null as?? throw. (rizikové opravy, PHP 8.0+) - uselessBraces: Removes braces around a bare statement group.
- uselessCatchVariable: Removes the variable of a
catchclause that is never used. (PHP 8.0+) - uselessConstructParentheses: Removes parentheses around the operand of a language construct.
- uselessElse: Removes an
elseafter branches which always leave, and may turn anelseifthere into anif. - uselessReturn: Removes a bare
returnat the end of a function body.
Výrazy
Operátory, přetypování, ternár, instanciace a přístup ke členům.
- binaryOperatorSpacing Kolem binárního operátoru, přiřazení, instanceof, ⇒ a = výchozí hodnoty je z každé strany mezera; jestli smí zůstat i zarovnání do sloupců, říká volba.
- castCanonicalType: Writes a cast with the short type name in lowercase.
- castSpacing: Puts a single space between a cast and its operand.
- cloneWithNotation: Writes a clone with the properties assigned after it as
clone()taking them. (rizikové opravy, PHP 8.5+) - combinedAssignmentForRepeatedTarget: Uses
+=and friends where an assignment repeats its target. (rizikové opravy) - concatSpacing: Puts a single space around the concatenation operator.
- doubleColonSpacing: Removes whitespace around the double colon.
- emptyArgumentParentheses: Requires or forbids the empty parentheses of an instantiation and an attribute.
- explicitOperatorPrecedence: Parenthesizes an operand where the precedence of logical or bitwise operators is easy to misread.
- incrementForAddOne: Uses
++and--instead of+= 1and-= 1. (rizikové opravy) - multilineChain: Puts every link of a multi-line chain of calls on its own line, the first one included.
- multilineTernary: Puts the two operators of a multi-line ternary on lines of their own.
- noErrorSuppression: Reports the
@error suppression operator. (jen hlásí) - noShortBoolCasts: Replaces
!!with a(bool)cast. - notEqualsNotation: Writes
!=instead of<>. - nullCoalescingForNullTernary: Replaces a ternary testing for null with the null coalescing operator. (rizikové opravy)
- nullsafeForGuardedAccess: Replaces a ternary guarding a member access against null with the nullsafe operator. (PHP 8.0+)
- objectOperatorSpacing: Removes whitespace around the object operator.
- offsetBracketSpacing: Removes whitespace around the brackets of an offset access.
- pipeOperator: Writes nested calls passing one result into the next with the pipe operator. (PHP 8.5+)
- referenceSpacing: Removes whitespace between
&and its operand. - shortTernaryForRepeatedCondition Ternár, který ve své prostřední části opakuje podmínku, se píše zkráceně jako ?:.
- spreadOperatorSpacing: Removes whitespace between
...and its operand. - strictComparison: Replaces loose comparisons with strict ones. (rizikové opravy)
- symbolicLogicalOperators: Uses
&&and||instead ofandandor. - ternaryOperatorSpacing: Puts whitespace around the ternary operators.
- unaryOperatorSpacing: Removes whitespace between a unary operator and its operand.
- uselessParenthesesAroundNew: Removes the parentheses around
newwhen a member of the new object is accessed. (PHP 8.4+) - uselessTernaryOperator: Replaces a ternary operator choosing between
trueandfalsewith the condition. - yoda: Decides which side of a comparison the constant stands on.
Literály
Zápis řetězců, čísel, konstant a klíčových slov.
- complexStringVariable: Replaces the deprecated
${name}interpolation with{$name}. - heredocIndentation: Indents the body and the closing marker of a heredoc relative to its starting line.
- keywordCasing: Writes keywords in lowercase,
true,falseandnulland magic constants in the chosen case. - noBacktickOperators: Runs a command through
shell_exec()instead of backticks. - noImplicitBackslashes: Writes every backslash of a string escaped.
- noTrailingWhitespaceInString: Removes trailing whitespace from string lines. (rizikové opravy)
- nowdocWithoutInterpolation: Uses nowdoc where a heredoc interpolates nothing.
- numericLiteralSeparator: Groups the digits of long numbers with underscores.
- octalNotation Osmičkové číslo se píše s prefixem 0o, ne s pouhou nulou na začátku. (PHP 8.1+)
- stringQuotes: Decides which quotes a string that needs neither kind is written with.
- uselessStringConcat: Joins two string literals concatenated on one line and drops concatenation with an empty string.
Pole
Pole a destrukturace jako syntaktická konstrukce.
- arraySpacing: Removes whitespace inside the brackets of an array.
- multilineArray: Spreads a multi-line or too wide array over lines, an item on each or several filling a line, the opening bracket on the line before.
- noManualListTests: Replaces a hand-written test for a list with
array_is_list(). (rizikové opravy, PHP 8.1+) - noNullArrayKeys: Writes a
nullarray key as the empty string it becomes. - shortArraySyntax: Writes arrays and destructuring with the short syntax.
- spreadForArrayMerge: Writes the arrays merged by
array_merge()as an array spreading them. (rizikové opravy, PHP 8.1+) - trailingComma Víceřádkový seznam má čárku za poslední položkou podle toho, co pro jeho druh říká volba, jednořádkový ji nemá.
Typy
Typové deklarace v kódu, ne v anotacích.
- neverForThrowingFunction: Declares a function that always throws or exits as returning
never. (PHP 8.1+) - nullableTypeForDefaultNull: Marks the type of a parameter defaulting to
nullas nullable. - typeHintRequired: Adds native types from annotations and reports declarations without any type. (rizikové opravy)
- typeHintSpacing: Normalizes whitespace in type declarations.
- typeNotation: Writes a nullable type as
?T, putsnulllast in a union type and may sort the rest.
PhpDoc
Dokumentační komentáře a anotace v nich.
- annotationCasing: Writes known annotations in their canonical case.
- attributeAfterPhpdoc: Moves a doc comment written after the attributes above them.
- deprecatedAttributeForAnnotation: Replaces the
@deprecatedannotation with the#[\Deprecated]attribute. (rizikové opravy, PHP 8.4+) - explicitAssertion: Replaces an inline
@varannotation with anassert()of the type. (rizikové opravy) - forbiddenAnnotations: Removes the configured annotations from doc comments.
- forbiddenPhpdocLines: Removes description lines matching the configured patterns from doc comments.
- noConsecutivePhpdocs: Reports a doc comment followed by another one. (jen hlásí)
- noEmptyPhpdocs: Removes empty doc comments.
- noEmptyVarAnnotations: Reports a
@varor@seewithout content in a property doc comment. (jen hlásí) - noMismatchedFunctionAnnotations: Reports an annotation of a function that does not agree with its signature: a
@paramof an unknown parameter, a second@return. (jen hlásí) - phpdocAlignment: Aligns the stars of a doc comment with its opening.
- phpdocTrim: Removes extra blank lines in a doc comment.
- phpdocTypeNotation: Writes the types in doc comments in one notation: short lowercase built-ins, one array notation, no repeated type in a union, and the nullable and union notation of typeNotation.
- promotedPropertyAnnotationPosition: Moves the
@paramannotation of a promoted property to a doc comment at the property. - propertyPhpdocRequired: Reports a plain comment in place of a property doc comment. (jen hlásí)
- propertyPhpdocSingleline: Writes a property doc comment with a single line of content on one line.
- propertyVarAnnotation: Reports a repeated or misplaced
@varin a property doc comment. (jen hlásí) - uselessConstantVarAnnotation: Removes a useless
@varfrom a class constant. - uselessFunctionPhpdoc: Removes a function doc comment that only repeats the native types.
- uselessInheritdoc: Removes a doc comment consisting of
@inheritDoconly.
Komentáře
Obyčejné komentáře.
- commentSpacing: Puts a space after the marker of a comment and before a comment following code.
- noEmptyComments: Removes empty comments.
- noHashComments: Writes single-line comments with
//, not#.
Proměnné
Proměnné, jejich rozsah a životnost.
- combinedIssets: Asks about several variables in one
isset()instead of a chain joined by&&. - combinedUnsets: Drops several variables in one
unsetinstead of consecutive statements. - noDuplicateAssignments: Reports an assignment repeated to the same variable in one expression. (jen hlásí)
- noGlobalStatements: Forbids the
globalstatement. (jen hlásí)
Bílé znaky
Bílé znaky, které nepatří žádné jedné konstrukci: odsazení, závorky, čárky, prázdné řádky.
- attributePosition: Puts the attributes of a declaration on lines of their own above it.
- attributeSpacing: Removes whitespace inside the brackets of an attribute group.
- blankLines Prázdné řádky tam, kde je standard chce: v hlavičce souboru kolem declare, namespace a importů, ve třídě mezi metodami a členy, za otevírací a před zavírací závorkou bloku a kolem příkazů jako return.
- bracesPosition Otevírací složená závorka stojí u tříd a funkcí na vlastním řádku a u řídicích struktur, closure (anonymní funkce) a anonymních tříd na řádku hlavičky; tělo začíná na novém řádku, zavírací závorka má řádek pro sebe a else, catch či finally stojí na jejím řádku.
- commaSpacing: Puts a single space after a comma and none before it.
- constructSpacing: Puts a single space around language constructs.
- indentation: Indents every line by the construct it continues, one level per nesting.
- parenthesesSpacing: Removes whitespace inside parentheses.
- semicolonSpacing: Removes whitespace before a semicolon and puts a single space after it.
- singleLevelIndentation: Reports indentation that deepens by more than a level or returns to a level nothing opened. (jen hlásí)
- singleStatementPerLine: Puts every statement on its own line.
Aktualizace kódu
Pravidla, jejichž předmětem je katalog, ne konstrukce: mapy náhrad a zákazů, které plní projekt nebo balíčky pravidel, a zavržení, na která se ty mapy ptají.
- attributeForAnnotation: Writes the attribute a project or its libraries read instead of an annotation.
- attributeForMember: Writes the attribute of a class a library reads instead of a member the class declares.
- forbiddenClasses: Reports references of the configured classes with what to do instead. (jen hlásí)
- forbiddenFunctions: Reports calls of the configured functions with what to do instead. (jen hlásí)
- forbiddenMembers: Reports uses and declarations of the configured members with what to do instead. (jen hlásí)
- noDeprecatedClasses: Replaces deprecated classes with the class their deprecation names, and reports the rest.
- noDeprecatedMembers: Replaces deprecated constants, methods and properties with the member their deprecation names, and reports the rest.
- replacedCalls: Writes a call, an access or an instantiation the way a project or its libraries write it instead. (rizikové opravy)
- replacedClasses: Writes the class a project or its libraries write instead of another one.
- replacedFunctions: Calls the function a project or its libraries write instead of another one. (rizikové opravy)
- replacedMembers: Writes the member a project or its libraries write instead of another one. (rizikové opravy)