Code formatting
Below coding standards apply to Drupal code and its contributed and custom modules and themes.
Indenting and Whitespace
-
Use an indent of 2 spaces, with no tabs.
-
Lines should have no trailing whitespace at the end.
-
All text files should end in a single newline (\n).
-
All comment doc-blocks at the beginning of a PHP file should be separated by a blank line
Operators
All binary operators( +, -, =, !=, ==, >, etc) should have a space before and after the operator.
Casting
Put a space between the (type) and the $variable in a cast.
Control Structures ( if, for, while, switch)
- Control statements should have one space between the control keyword and opening parenthesis
- Always use curly braces even in situations where they are technically optional.
- The opening curly should be on the same line as the opening statement, preceded by one space.
- The closing curly should be on a line by itself and indented to the same level as the opening statement.
Line length and wrapping
- All lines of code should not be longer than 80 characters.
- Lines containing longer function names, function/class definitions, variable declarations, etc are allowed to exceed 80 characters as exceptions.
- Control structure conditions may exceed 80 characters, if they are simple to read and understand.
- Conditions should not be wrapped into multiple lines.
Function Calls
Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon.
Constructor Calls
When calling class constructors with arguments/no arguments - always include parentheses.
Arrays
Arrays should be formatted using short array syntax with a space separating each element (after the comma), and spaces around the => key association operator.
String Concatenations
Always use a space between the dot and the concatenated parts to improve readability.
PHP Code Tags
Always use <?php ?> to delimit PHP code, not the shorthand, <? ?>.
Constants
Constants should always be all-uppercase, with underscores to separate words. In Drupal 8 and later, constants should be defined using the const PHP language keyword
Resources
https://www.drupal.org/docs/develop/standards/coding-standards