diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ef81d96..79f8dc24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,149 @@ All notable changes to this project will be documented in this file, in reverse chronological order by release. +## 2.0.0-alpha.4 - TBD + +### Added + +- Nothing. + +### Changed + +- [#22](https://github.com/zendframework/zend-coding-standard/pull/22) refactors + documentation. It now follows the PHP-FIG PSR-12 style. +- [#22](https://github.com/zendframework/zend-coding-standard/pull/22) refactors + the ruleset. It uses PSR-12 as the base ruleset with these additional rules: + + - The short open tag SHOULD NOT be used. + - Deprecated features SHOULD be avoided. + - The backtick operator MUST NOT be used. + - The `goto` language construct SHOULD NOT be used. + - The `global` keyword MUST NOT be used. + - The constant `PHP_SAPI` SHOULD be used instead of the `php_sapi_name()` + function. + - Aliases SHOULD NOT be used. + - There MUST NOT be a space before a semicolon. Redundant semicolons SHOULD + be avoided. + - Non executable code MUST be removed. + - There MUST be a single space after language constructs. + - Parentheses MUST be omitted where possible. + - PHP function calls MUST be in lowercase. + - There MAY NOT be any content before the opening tag. Inline HTML in PHP code + SHOULD be avoided. All code MUST be executable and non executable code SHOULD + be removed. + - The `declare(strict_types=1)` directive MUST be declared and be the first + statement in a file. + - There MAY be maximum one blank line to improve readability and to indicate + related blocks of code except where explicitly forbidden. + - There MAY NOT be any blank line after opening braces and before closing braces. + - There MUST NOT be a space before a semicolon. Redundant semicolons SHOULD be + avoided. + - Encapsed strings MAY be used instead of concatenating strings. When + concatenating strings, there MUST be a single whitespace before and after the + concatenation operator. The concatenation operator MUST NOT be the at the end + of a line. If multi-line concatenation is used there MUST be an indent of 4 + spaces. + - Variable names MUST be declared in camelCase. + - The short array syntax MUST be used to define arrays. + - All values in multiline arrays must be indented with 4 spaces. + - All array values must be followed by a comma, including the last value. + - There MUST NOT be whitespace around the opening bracket or before the closing + bracket when referencing an array. + - All double arrow symbols MUST be aligned to one space after the longest array + key. + - The short list syntax `[...]` SHOULD be used instead of `list(...)`. + - There MUST be a single space after the namespace keyword and there MAY NOT be + a space around a namespace separator. + - Import statements MUST be alphabetically sorted. + - Unused import statements SHOULD be removed. + - Fancy group import statements MUST NOT be used. + - Each import statement MUST be on its own line. + - Import statement aliases for classes, traits, functions and constants MUST + be useful, meaning that aliases SHOULD only be used if a class with the same + name is imported. + - Classes, traits, interfaces, constants and functions MUST be imported. + - There MUST NOT be duplicate class names. + - The file name MUST match the case of the terminating class name. + - PHP 4 style constructors MUST NOT be used. + - Correct class name casing MUST be used. + - Abstract classes MUST have a `Abstract` prefix. + - Exception classes MUST have a `Exception` suffix. + - Interface classes MUST have a `Interface` suffix. + - Trait classes MUST have a `Trait` suffix. + - For self-reference a class lower-case `self::` MUST be used without spaces + around the scope resolution operator. + - Class name resolution via `::class` MUST be used instead of `__CLASS__`, + `get_class()`, `get_class($this)`, `get_called_class()`, `get_parent_class()` + and string reference. + - There MAY NOT be any whitespace around the double colon operator. + - Unused private methods, constants and properties MUST be removed. + - Traits MUST be sorted alphabetically. + - Default null values MUST be omitted for class properties. + - There MUST be a single empty line between methods in a class. + - The pseudo-variable `$this` MUST NOT be called inside a static method or + function. + - Returned variables SHOULD be useful and SHOULD NOT be assigned to a value and + returned on the next line. + - The question mark MUST be used when the default argument value is null. + - The `final` keyword on methods MUST be omitted in final declared classes. + - There MUST be one single space after `break` and `continue` structures with + a numeric argument argument. + - Statements MUST NOT be empty, except for catch statements. + - The `continue` control structure MUST NOT be used in switch statements, + `break` SHOULD be used instead. + - All catch blocks MUST be reachable. + - There MUST be at least one space on either side of an equals sign used + to assign a value to a variable. In case of a block of related + assignments, more spaces MUST be inserted before the equal sign to + promote readability. + - There MUST NOT be any white space around the object operator UNLESS + multilines are used. + - Loose comparison operators SHOULD NOT be used, use strict comparison + operators instead. e.g. use `===` instead of `==`. + - The null coalesce operator SHOULD be used when possible. + - Assignment operators SHOULD be used when possible. + - The `&&` and `||` operators SHOULD be used instead of `and` and `or`. + - There MUST be one whitespace after a type casting operator. + - There MUST be one whitespace after unary not. + - Inherited variables passed via `use` MUST be used in closures. + - Code SHOULD be written so it explains itself. DocBlocks and comments + SHOULD only be used if necessary. They MUST NOT start with `#` and MUST + NOT be empty. They SHOULD NOT be used for already typehinted arguments, + except arrays. + - The asterisks in a DocBlock should align, and there should be one + space between the asterisk and tag. + - PHPDoc tags `@param`, `@return` and `@throws` SHOULD not be aligned or + contain multiple spaces between the tag, type and description. + - If a function throws any exceptions, it SHOULD be documented with + `@throws` tags. + - DocBlocks MUST follow a specific order of annotations with empty + newline between specific groups. + - The annotations `@api`, `@author`, `@category`, `@created`, `@package`, + `@subpackage` and `@version` MUST NOT be used in comments. Git commits + provide accurate information. + - The words _private_, _protected_, _static_, _constructor_, _deconstructor_, + _Created by_, _getter_ and _setter_, MUST NOT be used in comments. + - The `@var` tag MAY be used in inline comments to document the _Type_ + of properties. Single-line property comments with a `@var` tag SHOULD + be written as one-liners. The `@var` MAY NOT be used for constants. + - The correct tag case of PHPDocs and PHPUnit tags MUST be used. + - Inline DocComments MAY be used at the end of the line, with at least a + single space preceding. Inline DocComments MUST NOT be placed after curly + brackets. + - Heredoc and nowdoc tags MUST be uppercase without spaces. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + ## 2.0.0-alpha.3 - 2019-01-01 ### Added @@ -89,7 +232,7 @@ All notable changes to this project will be documented in this file, in reverse return values are still under discussion. We will change these rules, and, when PSR-12 is finalized, adapt them. - [#5](https://github.com/zendframework/zend-coding-standard/pull/5) extends - PSR-12 with ZendFramework specific rules: + PSR-12 with Zend Framework specific rules: *NOTE:* Most of these rules should look familiar as they are already being used in components rewritten for PHP 7.1. diff --git a/README.md b/README.md index 5922b094..b26b61a3 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,6 @@ Contributors have different coding styles and so do the maintainers. During code discussions about spaces and alignments, where and when was said that a function needs to be imported. And that's where this coding standard comes in: To have internal consistency in a component and between components. -> Note: PSR-12 is not finalized. e.g. The `!` operator and `:` placement for return values are still under discussion. -We will change these rules, and, when PSR-12 is finalized, adapt them. - ## Installation 1. Install the module via composer by running: @@ -111,7 +108,7 @@ $xmlPackage->send(); > **New rules or Sniffs may not be introduced in minor or bugfix releases and should always be based on the develop branch and queued for the next major release, unless considered a bugfix for existing rules.** -If you want to test changes against ZendFramework components or your own projects, install your forked +If you want to test changes against Zend Framework components or your own projects, install your forked zend-coding-standard globally with composer: ```bash $ composer global config repositories.zend-coding-standard vcs git@github.com:/zend-coding-standard.git @@ -135,4 +132,3 @@ be found here: - [Configuration Options](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options) - [Selectively Applying Rules](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset#selectively-applying-rules) - [Customisable Sniff Properties](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties) -- [Slevomat Coding Standard](https://github.com/slevomat/coding-standard) diff --git a/composer.json b/composer.json index f8ab01ea..8c069e9d 100644 --- a/composer.json +++ b/composer.json @@ -19,9 +19,9 @@ "require": { "php": "^7.1", "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", - "slevomat/coding-standard": "^4.8.0", - "squizlabs/php_codesniffer": "^3.4.0", - "webimpress/coding-standard": "dev-master" + "slevomat/coding-standard": "^5.0.4", + "squizlabs/php_codesniffer": "^3.5.1", + "webimpress/coding-standard": "^1.0.5" }, "extra": { "branch-alias": { diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 777896bf..f1e529b0 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -1,53 +1,242 @@ # Zend Framework Coding Style Guide -This specification extends and expands [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md), -the extended coding style guide and requires adherence to [PSR-1](https://www.php-fig.org/psr/psr-1), -the basic coding standard. +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", +"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be +interpreted as described in [RFC 2119][]. -> Note: PSR-12 is not finalized. e.g. The `!` operator and `:` placement for return values are still under discussion. -We will change these rules, and, when PSR-12 is finalized, adapt them. +[RFC 2119]: http://tools.ietf.org/html/rfc2119 -## General +## 1. Overview -### Basic Coding Standard +This specification extends [PSR-12][], the coding style guide and +requires adherence to [PSR-1][], the basic coding standard. -Code MUST follow all rules outlined in [PSR-1](https://www.php-fig.org/psr/psr-1) and -[PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md), except in -specific cases outlined in this specification, until PSR-12 is accepted as a standard. +Like [PSR-12][], the intent of this specification is to reduce cognitive friction when +scanning code from different authors contributing to Zend Framework. It does so by +enumerating a shared set of rules and expectations about how to format PHP code. -### Indenting and Alignment +### 1.1 Previous language versions -- There should be one space on either side of an equals sign used to assign a value to a variable. In case of a - block of related assignments, more space may be inserted before the equal sign to promote readability. - [*](ruleset.md#genericformattingmultiplestatementalignment) +Throughout this document, any instructions MAY be ignored if they do not exist in versions +of PHP supported by your project. + +### 1.2 Example + +This example encompasses some of the rules below as a quick overview: ```php factory = $factory; + $this->pipeline = $pipeline; + $this->routes = $routes; + $this->runner = $runner; + } + + /** + * Proxies to composed pipeline to handle. + * {@inheritDocs} + */ + public function handle(ServerRequestInterface $request) : ResponseInterface + { + return $this->pipeline->handle($request); + } -$shortVar = (1 + 2); -$veryLongVarName = 'string'; -$var = foo($bar, $baz, $quux); + /** + * Run the application. + * + * Proxies to the RequestHandlerRunner::run() method. + */ + public function run() : void + { + $this->runner->run(); + } +} ``` -- Short array syntax must be used to define arrays. [*](ruleset.md#genericarraysdisallowlongarraysyntax) -- All values in multiline arrays must be indented with 4 spaces. [*](ruleset.md#genericarraysarrayindent) -- All array values must be followed by a comma, including the last value. [*](ruleset.md#slevomatcodingstandardarraystrailingarraycomma) -- Whitespace is not allowed around the opening bracket or before the closing bracket when referencing an array. - [*](ruleset.md#squizarraysarraybracketspacing) -- All double arrow symbols must be aligned to one space after the longest array key. [*](ruleset.md#squizarraysarraydeclaration) +## 2. General + +### 2.1 Basic Coding Standard + +Code MUST follow all rules outlined in [PSR-1]. + +The term 'StudlyCaps' in PSR-1 MUST be interpreted as PascalCase where the first letter of +each word is capitalized including the very first letter. + +> ### Additional Zend Framework rules +> +> For consistency a bunch of older PHP features SHOULD NOT be used: +> +> - The [short open tag][] SHOULD NOT be used. +> - Deprecated features SHOULD be avoided ([[7.0]][70.deprecated], +> [[7.1]][71.deprecated], [[7.2]][72.deprecated], [[7.3]][73.deprecated], +> [[7.4]][74.deprecated]) +> - The [backtick operator][] MUST NOT be used. +> - The [goto][] language construct SHOULD NOT be used. +> - The [global][] keyword MUST NOT be used. +> - The constant [PHP_SAPI][] SHOULD be used instead of the `php_sapi_name()` function. +> - [aliases][] SHOULD NOT be used. +> +> There MUST NOT be a space before a semicolon. Redundant semicolons SHOULD be avoided. +> +> Non executable code MUST be removed. +> +> There MUST be a single space after language constructs. +> +> Parentheses MUST be omitted where possible. +> +> PHP function calls MUST be in lowercase. + +### 2.2 Files + +> ### Additional Zend Framework rules +> +> There MAY NOT be any content before the opening tag. Inline HTML in PHP code +> SHOULD be avoided. All code MUST be executable and non executable code SHOULD +> be removed. +> +> The `declare(strict_types=1)` directive MUST be declared and be the first +> statement in a file. +> + +All PHP files MUST use the Unix LF (linefeed) line ending only. + +All PHP files MUST end with a non-blank line, terminated with a single LF. + +The closing `?>` tag MUST be omitted from files containing only PHP. + +### 2.3 Lines + +There MUST NOT be a hard limit on line length. + +The soft limit on line length MUST be 120 characters. + +Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD +be split into multiple subsequent lines of no more than 80 characters each. + +There MUST NOT be trailing whitespace at the end of lines. + +Blank lines MAY be added to improve readability and to indicate related +blocks of code except where explicitly forbidden. + +> ### Additional Zend Framework rules +> +> There MAY be maximum one blank line to improve readability and to indicate +> related blocks of code except where explicitly forbidden. +> +> There MAY NOT be any blank line after opening braces and before closing braces. + +There MUST NOT be more than one statement per line. + +> ### Additional Zend Framework rules +> +> There MUST NOT be a space before a semicolon. Redundant semicolons SHOULD be +> avoided. + +### 2.4 Indenting and Spacing + +Code MUST use an indent of 4 spaces for each indent level, and MUST NOT use +tabs for indenting. + +> ### Additional Zend Framework rules +> +> Encapsed strings MAY be used instead of concatenating strings. When +> concatenating strings, there MUST be a single whitespace before and after the +> concatenation operator. The concatenation operator MUST NOT be the at the end +> of a line. If multi-line concatenation is used there MUST be an indent of 4 +> spaces. ```php 'value1', - 'key2' => 'value2', - 'keyTwenty' => 'value3', -]; +// Encapsed strings +$a = 'foo'; +$b = 'bar'; + +$c = "I like $a and $b"; + +// Concatenating +$a = 'Hello '; +$b = $a + . 'World!'; +``` -$var = [ - 'one' => function() { - $foo = [1,2,3]; +### 2.5 Keywords and Types + +All PHP reserved keywords and types [[1]][keywords][[2]][types] MUST be in lower case. + +Any new types and keywords added to future PHP versions MUST be in lower case. + +Short form of type keywords MUST be used i.e. `bool` instead of `boolean`, +`int` instead of `integer` etc. + +### 2.6 Variables + +> ### Additional Zend Framework rules +> +> Variable names MUST be declared in camelCase. + +### 2.7 Arrays + +> ### Additional Zend Framework rules +> +> The short array syntax MUST be used to define arrays. +> +> All values in multiline arrays must be indented with 4 spaces. +> +> All array values must be followed by a comma, including the last value. +> +> There MUST NOT be whitespace around the opening bracket or before the closing +> bracket when referencing an array. +> +> All double arrow symbols MUST be aligned to one space after the longest array +> key. + +```php + function () { + $foo = [1, 2, 3]; $barBar = [ 1, 2, @@ -55,137 +244,656 @@ $var = [ ]; }, 'longer' => 2, - /* three */ 3 => 'three', + 3 => 'three', ]; ``` -### PHP Keywords, Types, Constants and Functions - -- The `global` keyword may not be used. [*](ruleset.md#squizphpglobalkeyword) -- The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` function. [*](ruleset.md#genericphpsapiusage) -- PHP function calls must be in lowercase. [*](ruleset.md#squizphplowercasephpfunctions) -- PHP functions which are an alias may not be used. [*](ruleset.md#genericphpforbiddenfunctions) -- Deprecated functions should not be used. [*](ruleset.md#genericphpdeprecatedfunctions) - -### Commenting - -- Comments may be omitted and should not be used for typehinted arguments. -- Comments may not start with `#`. [*](ruleset.md#pearcommentinginlinecomment) -- Comments may not be empty. [*](ruleset.md#slevomatcodingstandardcommentingemptycomment) -- The words _private_, _protected_, _static_, _constructor_, _deconstructor_, _Created by_, _getter_ and _setter_, - may not be used in comments. [*](ruleset.md#slevomatcodingstandardcommentingforbiddencomments) -- The annotations `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage` and `@version` may not - be used in comments. Git commits provide accurate information. [*](ruleset.md#slevomatcodingstandardcommentingforbiddenannotations) -- The asterisks in a doc comment should align, and there should be one space between the asterisk and tag. - [*](ruleset.md#squizcommentingdoccommentalignment) -- Comment tags `@param`, `@throws` and `@return` should not be aligned or contain multiple spaces between the tag, - type and description. [*](ruleset.md#squizcommentingfunctioncomment) -- If a function throws any exceptions, they should be documented in `@throws` tags. - [*](ruleset.md#squizcommentingfunctioncomment) -- The `@var` tag may be used in inline comments to document the _Type_ of properties. [*](ruleset.md#slevomatcodingstandardcommentinginlinedoccommentdeclaration) -- Single-line comments with a `@var` tag should be written as one-liners. [*](ruleset.md#slevomatcodingstandardcommentingrequireonelinepropertydoccomment) -- Shorthand scalar typehint variants must be used in docblocks. [*](ruleset.md#slevomatcodingstandardtypehintslongtypehints) +> The short list syntax `[...]` SHOULD be used instead of `list(...)`. -## Declare Statements, Namespace, and Import Statements +```php + ### Additional Zend Framework rules +> +> There MUST be a single space after the namespace keyword and there MAY NOT be +> a space around a namespace separator. +> +> Import statements MUST be alphabetically sorted. +> +> Unused import statements SHOULD be removed. +> +> Fancy group import statements MUST NOT be used. +> +> Each import statement MUST be on its own line. +> +> Import statement aliases for classes, traits, functions and constants MUST +> be useful, meaning that aliases SHOULD only be used if a class with the same +> name is imported. +> +> Classes, traits, interfaces, constants and functions MUST be imported. + +The following example illustrates a complete list of all blocks: ```php + + + + + +``` + +Declare statements MUST contain no spaces and MUST be exactly `declare(strict_types=1)` +(with an optional semi-colon terminator). + +Block declare statements are allowed and MUST be formatted as below. Note position of +braces and spacing: + +```php +declare(ticks=1) { + // some code +} +``` + +## 4. Classes, Properties, and Methods + +The term "class" refers to all classes, interfaces, and traits. + +Any closing brace MUST NOT be followed by any comment or statement on the +same line. + +When instantiating a new class, parentheses MUST always be present even when +there are no arguments passed to the constructor. + +```php +new Foo(); +``` + +> ### Additional Zend Framework rules +> +> There MUST NOT be duplicate class names. +> +> The file name MUST match the case of the terminating class name. +> +> PHP 4 style constructors MUST NOT be used. +> +> Correct class name casing MUST be used. +> +> Abstract classes MUST have a `Abstract` prefix. +> +> Exception classes MUST have a `Exception` suffix. +> +> Interface classes MUST have a `Interface` suffix. +> +> Trait classes MUST have a `Trait` suffix. +> +> For self-reference a class lower-case `self::` MUST be used without spaces +> around the scope resolution operator. +> +> Class name resolution via `::class` MUST be used instead of `__CLASS__`, +> `get_class()`, `get_class($this)`, `get_called_class()`, `get_parent_class()` +> and string reference. +> +> There MAY NOT be any whitespace around the double colon operator. +> +> Unused private methods, constants and properties MUST be removed. + +### 4.1 Extends and Implements + +The `extends` and `implements` keywords MUST be declared on the same line as +the class name. + +The opening brace for the class MUST go on its own line; the closing brace +for the class MUST go on the next line after the body. + +Opening braces MUST be on their own line and MUST NOT be preceded or followed +by a blank line. + +Closing braces MUST be on their own line and MUST NOT be preceded by a blank +line. + +```php + ### Additional Zend Framework rules +> +> Traits MUST be sorted alphabetically. ```php ### Additional Zend Framework rules +> +> Default null values MUST be omitted for class properties. + +A property declaration looks like the following: + +```php + ### Additional Zend Framework rules +> +> There MUST be a single empty line between methods in a class. +> +> The pseudo-variable `$this` MUST NOT be called inside a static method or +> function. +> +> Returned variables SHOULD be useful and SHOULD NOT be assigned to a value and +> returned on the next line. + +A method declaration looks like the following. Note the placement of +parentheses, commas, spaces, and braces: + +```php + ### Additional Zend Framework rules +> +> The question mark MUST be used when the default argument value is null. + +```php + ### Additional Zend Framework rules +> +> The `final` keyword on methods MUST be omitted in final declared classes. + +When present, the `static` declaration MUST come after the visibility +declaration. + +```php +bar($arg1); +Foo::bar($arg2, $arg3); +``` + +Argument lists MAY be split across multiple lines, where each subsequent line +is indented once. When doing so, the first item in the list MUST be on the +next line, and there MUST be only one argument per line. A single argument being +split across multiple lines (as might be the case with an anonymous function or +array) does not constitute splitting the argument list itself. + +```php +bar( + $longArgument, + $longerArgument, + $muchLongerArgument +); +``` + +```php +get('/hello/{name}', function ($name) use ($app) { + return 'Hello ' . $app->escape($name); +}); +``` + +## 5. Control Structures + +The general style rules for control structures are as follows: + +- There MUST be one space after the control structure keyword +- There MUST NOT be a space after the opening parenthesis +- There MUST NOT be a space before the closing parenthesis +- There MUST be one space between the closing parenthesis and the opening + brace +- The structure body MUST be indented once +- The body MUST be on the next line after the opening brace +- The closing brace MUST be on the next line after the body + +The body of each structure MUST be enclosed by braces. This standardizes how +the structures look and reduces the likelihood of introducing errors as new +lines get added to the body. + +> ### Additional Zend Framework rules +> +> There MUST be one single space after `break` and `continue` structures with +> a numeric argument argument. +> +> Statements MUST NOT be empty, except for catch statements. + +### 5.1 `if`, `elseif`, `else` + +An `if` structure looks like the following. Note the placement of parentheses, +spaces, and braces; and that `else` and `elseif` are on the same line as the +closing brace from the earlier body. -### if, elseif, else ```php ### Additional Zend Framework rules +> +> The `continue` control structure MUST NOT be used in switch statements, +> `break` SHOULD be used instead. + ```php $value) { } ``` -### try, catch, finally +### 5.6 `try`, `catch`, `finally` -- Catch blocks may be empty. [*](ruleset.md#genericcodeanalysisemptystatementdetectedcatch) -- Catch blocks must be reachable. [*](ruleset.md#slevomatcodingstandardexceptionsdeadcatch) -- Catch blocks must use `Throwable` instead of `Exception`. [*](ruleset.md#slevomatcodingstandardexceptionsreferencethrowableonly) +A `try-catch-finally` block looks like the following. Note the placement of +parentheses, spaces, and braces. ```php ### Additional Zend Framework rules +> +> All catch blocks MUST be reachable. + +## 6. Operators + +Style rules for operators are grouped by arity (the number of operands they +take). + +When space is permitted around an operator, multiple spaces MAY be +used for readability purposes. + +> ### Additional Zend Framework rules +> +> There MUST be at least one space on either side of an equals sign used +> to assign a value to a variable. In case of a block of related +> assignments, more spaces MUST be inserted before the equal sign to +> promote readability. +> +> There MUST NOT be any white space around the object operator UNLESS +> multilines are used. +> +> Loose comparison operators SHOULD NOT be used, use strict comparison +> operators instead. e.g. use `===` instead of `==`. +> +> The null coalesce operator SHOULD be used when possible. +> +> Assignment operators SHOULD be used when possible. +> +> The `&&` and `||` operators SHOULD be used instead of `and` and `or`. + +All operators not described here are left undefined. + +### 6.1. Unary operators + +The increment/decrement operators MUST NOT have any space between +the operator and operand. + +```php +$i++; +++$j; +``` + +Type casting operators MUST NOT have any space within the parentheses. + +> ### Additional Zend Framework rules +> +> There MUST be one whitespace after a type casting operator. -In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#6-operators): +```php +$intValue = (int) $input; +``` -- The not (`!`) operator must be followed by exactly one space. [*](ruleset.md#genericformattingspaceafternot) -- The `&&` and `||` operators must be used instead of `AND` and `OR`. [*](ruleset.md#squizoperatorsvalidlogicaloperators) -- The null coalescing operator `??` should be used when possible. [*](ruleset.md#slevomatcodingstandardcontrolstructuresrequirenullcoalesceoperator) -- Assignment operators (eg `+=`, `.=`) should be used when possible. [*](ruleset.md#slevomatcodingstandardoperatorsrequirecombinedassignmentoperator) +> ### Additional Zend Framework rules +> +> There MUST be one whitespace after unary not. ```php $c) { - $variable = $foo ? 'foo' : 'bar'; +} elseif ($a > $b) { + $foo = $a + $b * $c; } +``` + +### 6.3. Ternary operators + +The conditional operator, also known simply as the ternary operator, MUST be +preceded and followed by at least one space around both the `?` +and `:` characters: -$var = 'foo'; -$aVeryLongName = 'bar'; -$function = function ($arg1, $arg2) {}; +```php +$variable = $foo ? 'foo' : 'bar'; ``` -## Closures +When the middle operand of the conditional operator is omitted, the operator +MUST follow the same style rules as other binary [comparison][] operators: +```php +$variable = $foo ?: 'bar'; +``` -In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#7-closures): +## 7. Closures -- Unused variables should not be passed to closures via `use`. [*](ruleset.md#slevomatcodingstandardfunctionsunusedinheritedvariablepassedtoclosure) +Closures MUST be declared with a space after the `function` keyword, and a +space before and after the `use` keyword. + +The opening brace MUST go on the same line, and the closing brace MUST go on +the next line following the body. + +There MUST NOT be a space after the opening parenthesis of the argument list +or variable list, and there MUST NOT be a space before the closing parenthesis +of the argument list or variable list. + +In the argument list and variable list, there MUST NOT be a space before each +comma, and there MUST be one space after each comma. + +Closure arguments with default values MUST go at the end of the argument +list. + +If a return type is present, it MUST follow the same rules as with normal +functions and methods; if the `use` keyword is present, the colon MUST follow +the `use` list closing parentheses with no spaces between the two characters. + +> ### Additional Zend Framework rules +> +> Inherited variables passed via `use` MUST be used in closures. + +A closure declaration looks like the following. Note the placement of +parentheses, commas, spaces, and braces: ```php bar( + $arg1, + function ($arg2) use ($var1) { + // body + }, + $arg3 +); ``` -## Anonymous Classes +## 8. Anonymous Classes -In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#8-anonymous-classes): +Anonymous Classes MUST follow the same guidelines and principles as closures +in the above section. ```php ` should not have any spaces around it. [*](ruleset.md#squizwhitespaceobjectoperatorspacing) -- Semicolons should not have spaces before them. [*](ruleset.md#squizwhitespacesemicolonspacing) -- The code should not contain superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. [*](ruleset.md#squizwhitespacesuperfluouswhitespace) +## 9. Commenting and DocBlocks + +> ### Additional Zend Framework rules +> +> Code SHOULD be written so it explains itself. DocBlocks and comments +> SHOULD only be used if necessary. They MUST NOT start with `#` and MUST +> NOT be empty. They SHOULD NOT be used for already typehinted arguments, +> except arrays. +> +> The asterisks in a DocBlock should align, and there should be one +> space between the asterisk and tag. +> +> PHPDoc tags `@param`, `@return` and `@throws` SHOULD not be aligned or +> contain multiple spaces between the tag, type and description. +> +> If a function throws any exceptions, it SHOULD be documented with +> `@throws` tags. +> +> DocBlocks MUST follow this specific order of annotations with empty +> newline between specific groups: +> +> ```php +> /** +> * +> * +> * +> * +> * @internal +> * @deprecated +> * +> * @link +> * @see +> * @uses +> * +> * @param +> * @return +> * @throws +> */ +> ``` +> +> The annotations `@api`, `@author`, `@category`, `@created`, `@package`, +> `@subpackage` and `@version` MUST NOT be used in comments. Git commits +> provide accurate information. +> +> The words _private_, _protected_, _static_, _constructor_, _deconstructor_, +> _Created by_, _getter_ and _setter_, MUST NOT be used in comments. +> +> The `@var` tag MAY be used in inline comments to document the _Type_ +> of properties. Single-line property comments with a `@var` tag SHOULD +> be written as one-liners. The `@var` MAY NOT be used for constants. +> +> The correct tag case of PHPDocs and PHPUnit tags MUST be used. +> +> Inline DocComments MAY be used at the end of the line, with at least a +> single space preceding. Inline DocComments MUST NOT be placed after curly +> brackets. +> +> Heredoc and nowdoc tags MUST be uppercase without spaces. + +[PSR-1]: https://www.php-fig.org/psr/psr-1/ +[PSR-2]: https://www.php-fig.org/psr/psr-2/ +[PSR-12]: https://www.php-fig.org/psr/psr-12/ +[keywords]: https://www.php.net/manual/en/reserved.keywords.php +[types]: https://www.php.net/manual/en/reserved.other-reserved-words.php +[arithmetic]: https://www.php.net/manual/en/language.operators.arithmetic.php +[assignment]: https://www.php.net/manual/en/language.operators.assignment.php +[comparison]: https://www.php.net/manual/en/language.operators.comparison.php +[bitwise]: https://www.php.net/manual/en/language.operators.bitwise.php +[logical]: https://www.php.net/manual/en/language.operators.logical.php +[string]: https://www.php.net/manual/en/language.operators.string.php +[type]: https://www.php.net/manual/en/language.operators.type.php +[short open tag]: https://www.php.net/manual/en/language.basic-syntax.phptags.php +[70.deprecated]: https://www.php.net/manual/en/migration70.deprecated.php +[71.deprecated]: https://www.php.net/manual/en/migration71.deprecated.php +[72.deprecated]: https://www.php.net/manual/en/migration72.deprecated.php +[73.deprecated]: https://www.php.net/manual/en/migration73.deprecated.php +[74.deprecated]: https://www.php.net/manual/en/migration74.deprecated.php +[backtick operator]: https://www.php.net/manual/en/language.operators.execution.php +[goto]: https://www.php.net/manual/en/control-structures.goto.php +[global]: https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.global +[PHP_SAPI]: https://www.php.net/manual/en/function.php-sapi-name.php#refsect1-function.php-sapi-name-notes +[aliases]: https://www.php.net/manual/en/aliases.php diff --git a/docs/book/v2/intro.md b/docs/book/v2/intro.md index 7e19599f..82eb3b8e 100644 --- a/docs/book/v2/intro.md +++ b/docs/book/v2/intro.md @@ -17,9 +17,6 @@ Contributors have different coding styles and so do the maintainers. During code discussions about spaces and alignments, where and when was said that a function needs to be imported. And that's where this coding standard comes in: To have internal consistency in a component and between components. -> Note: PSR-12 is not finalized. e.g. The `!` operator and `:` placement for return values are still under discussion. -We will change these rules, and, when PSR-12 is finalized, adapt them. - ## Installation 1. Install the module via composer by running: @@ -109,7 +106,7 @@ $xmlPackage->send(); > **New rules or Sniffs may not be introduced in minor or bugfix releases and should always be based on the develop branch and queued for the next major release, unless considered a bugfix for existing rules.** -If you want to test changes against ZendFramework components or your own projects, install your forked +If you want to test changes against Zend Framework components or your own projects, install your forked zend-coding-standard globally with composer: ```bash $ composer global config repositories.zend-coding-standard vcs git@github.com:/zend-coding-standard.git @@ -133,4 +130,3 @@ be found here: - [Configuration Options](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options) - [Selectively Applying Rules](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset#selectively-applying-rules) - [Customisable Sniff Properties](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties) -- [Slevomat Coding Standard](https://github.com/slevomat/coding-standard) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md deleted file mode 100644 index 7b4b830d..00000000 --- a/docs/book/v2/ruleset.md +++ /dev/null @@ -1,1166 +0,0 @@ -# Ruleset - -## PSR2 -Use PSR-2 coding standard as a base - -### PSR2.ControlStructures.ElseIfDeclaration.NotAllowed -_PSR-12:_ The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words. - - - -## Generic - -### Generic.Arrays.ArrayIndent -All values in multiline arrays must be indented with 4 spaces. - -### Generic.Arrays.DisallowLongArraySyntax -Short array syntax must be used to define arrays. - -```php - 'bar']; -``` - -### Generic.Classes.DuplicateClassName -Class and Interface names should be unique in a project and must have a unique fully qualified name. They should never -be duplicated. - -*Valid: Unique class names.* -```php - 0; $i--) { - echo 'hello'; -} -``` - -*Invalid:* -```php -some string here -Beginning content -` tags or the short-echo `` tags; it must not use the other tag -variations. - -### Generic.PHP.DiscourageGoto -Forbid goto instruction. - -### Generic.PHP.ForbiddenFunctions -PHP functions which are an alias may not be used. _This can't be fixed automatically and need to be done manually._ - -| Alias | Replace with | -| ------------ | ---------------- | -| chop | rtrim | -| close | closedir | -| compact | | -| delete | unset | -| doubleval | floatval | -| extract | | -| fputs | fwrite | -| ini_alter | ini_set | -| is_integer | is_int | -| is_long | is_int | -| is_null | null === | -| is_real | is_float | -| is_writeable | is_writable | -| join | implode | -| key_exists | array_key_exists | -| pos | current | -| settype | | -| show_source | highlight_file | -| sizeof | count | -| strchr | strstr | - -### Generic.PHP.LowerCaseType -_PSR-12:_ Any new types and keywords added to future PHP versions must be in lower case. - -### Generic.PHP.SAPIUsage -The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` function. - -*Valid: PHP_SAPI is used.* -```php -get(); - } -} -``` - -### SlevomatCodingStandard.Commenting.RequireOneLinePropertyDocComment -Single-line comments with a `@var` tag should be written as one-liners. - -*Valid: One-line comment* -```php -a >>= 2; -$this->$$parameter ^= 10; -$this->{'a'} += 10; -``` - -### SlevomatCodingStandard.PHP.ShortList -Short list syntax `[...]` should be used instead of `list(...)`. - -*Valid: The short list syntax is used for array destructuring assignment.* -```php - $a, 'b' => $b, 'c' => $c] = $array; -``` - -*Invalid: Usage of `list`.* -```php - $a, 'b' => $b, 'c' => $c) = $array; -``` - -### SlevomatCodingStandard.PHP.TypeCast -_PSR-12:_ Short form of type keywords must be used. i.e. `bool` instead of `boolean`, `int` instead of `integer`, etc. - -The `binary` and `unset` cast operators are not allowed. - -### SlevomatCodingStandard.TypeHints.DeclareStrictTypes -Each PHP file should have a strict type declaration at the top after the page level docblock. - -_PSR-12:_ Declare statements MUST contain no spaces and MUST be exactly `declare(strict_types=1)`. - -```php - true, - 'debug' => false, - 'zend-expressive' => [ - 'raise_throwables' => true, - 'programmatic_pipeline' => true, - 'error_handler' => [ - 'template_404' => 'error::404', - 'template_error' => 'error::error', - ], - ], -]; -``` - -*Invalid: Double arrow symbols are not aligned.* -```php - true, - 'debug' => false, - 'zend-expressive' => [ - 'raise_throwables' => true, - 'programmatic_pipeline' => true, - 'error_handler' => [ - 'template_404' => 'error::404', - 'template_error' => 'error::error', - ], - ], -]; -``` - -### Squiz.Classes.ClassFileName -_PSR-4:_ The class name must correspond to a file name ending in .php. The file name MUST match the case of the -terminating class name. - -### Squiz.Classes.SelfMemberReference -The `self` keyword should be used instead of the current class name, and should not have spaces around `::`. - -*Valid:* -```php -` to access static variables.* -```php -$staticMember; - } -} -``` - -### Squiz.Strings.ConcatenationSpacing -Force whitespace before and after concatenation - -### Squiz.Strings.DoubleQuoteUsage -#### Squiz.Strings.DoubleQuoteUsage.ContainsVar -Double quote strings may only be used if they contain variables. SQL queries containing single quotes are an exception -to the rule. - -*Valid: Double quote strings are only used when it contains a variable.* -```php -` should not have any spaces around it. - -*Valid: No spaces around the object operator.* -```php -bar(); -``` - -*Invalid: Whitespace surrounding the object operator.* -```php - bar(); -``` - -### Squiz.WhiteSpace.ObjectOperatorSpacing -There should be one space before and after an operators. - -*Valid: One space around the operator.* -```php - - The ZendFramework coding standard. - - - - - - - - - - - - - - - - - - - - - - + The Zend Framework coding standard. - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - + - - - - + - - - - + - - - - - - - - - - - - - - - - - - - - - - + + + + + - - - - - - + - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - + + - + - + + + + + + + + + + + + + @@ -201,232 +75,822 @@ - - - - - - - - - - - - - - - - - - error - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - - - - - - - - - - + + + - - - - - - - - - - - - - + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + - + - + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - - - - - - - - + + + + + + - - - - Variable "%s" not allowed in double quoted string; use sprintf() or concatenation instead + + + + - - - - - - - - - - + + + - + + + + + + + + + + - - - - + + + - + + + + + + + + + + + + + - - - - + + + - - + + + + + + + - - - 5 - + + + + + + + + + + + + + + diff --git a/test/expected-report.txt b/test/expected-report.txt index a90ee1c0..3f1c1fbf 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -3,43 +3,40 @@ PHP CODE SNIFFER REPORT SUMMARY ---------------------------------------------------------------------- FILE ERRORS WARNINGS ---------------------------------------------------------------------- -test/fixable/anonymous-classes.php 11 0 -test/fixable/array-indentation.php 47 1 -test/fixable/class-name-resolution.php 15 0 -test/fixable/class-properties.php 6 0 -test/fixable/classes-traits-interfaces.php 17 1 -test/fixable/closures.php 19 0 -test/fixable/commenting.php 26 0 -test/fixable/concatenation-spacing.php 21 0 -test/fixable/control-structures.php 6 0 -test/fixable/example-class.php 29 0 -test/fixable/extends-and-implements-multiline.php 13 0 -test/fixable/extends-and-implements.php 5 0 -test/fixable/forbidden-comments.php 6 0 -test/fixable/forbidden-functions.php 6 0 -test/fixable/heredoc-nowdoc.php 6 0 -test/fixable/LowCaseTypes.php 2 0 -test/fixable/method-and-function-arguments.php 16 0 -test/fixable/method-and-function-calls.php 15 0 -test/fixable/namespaces-spacing.php 7 0 -test/fixable/naming.php 12 0 -test/fixable/new-with-parentheses.php 19 0 -test/fixable/not-spacing.php 33 1 -test/fixable/operators.php 17 0 -test/fixable/return-type-on-methods.php 17 0 -test/fixable/semicolon-spacing.php 5 0 -test/fixable/spacing.php 18 1 -test/fixable/statement-alignment.php 19 0 -test/fixable/test-case.php 4 0 -test/fixable/traits-uses.php 9 0 -test/fixable/UnusedVariables.php 1 0 -test/fixable/useless-semicolon.php 8 0 -test/fixable/variable-names.php 5 2 -test/fixable/visibility-declaration.php 1 0 +test/fixable/2.1.BasicCodingStandard.php 59 1 +test/fixable/2.2.Files.php 4 0 +test/fixable/2.3.Lines.php 35 0 +test/fixable/2.4.IndentingAndSpacing.php 46 0 +test/fixable/2.5.KeywordsAndTypes.php 13 0 +test/fixable/2.6.Variables.php 3 0 +test/fixable/2.7.Arrays.php 9 0 +test/fixable/3.DeclareNamespaceAndImport.php 15 0 +test/fixable/4.1.ExtendsAndImplements.php 5 0 +test/fixable/4.2.UsingTraits.php 5 0 +test/fixable/4.3.PropertiesAndConstants.php 5 0 +test/fixable/4.4.MethodsAndFunctions.php 26 0 +test/fixable/4.5.MethodAndFunctionArguments.php 66 0 +test/fixable/4.6.AbstractFinalAndStatic.php 4 0 +test/fixable/4.7.MethodAndFunctionCalls.php 11 0 +test/fixable/4.ClassesPropertiesAndMethods.php 32 0 +test/fixable/5.1.IfElseifElse.php 15 1 +test/fixable/5.2.SwitchCase.php 11 0 +test/fixable/5.3.WhileAndDoWhile.php 12 0 +test/fixable/5.4.ForStructure.php 7 0 +test/fixable/5.5.ForEachStructure.php 12 0 +test/fixable/5.6.TryCatchFinally.php 9 0 +test/fixable/5.ControlStructures.php 4 0 +test/fixable/6.1.UnaryOperators.php 6 0 +test/fixable/6.2.BinaryOperators.php 35 0 +test/fixable/6.3.TernaryOperators.php 13 0 +test/fixable/6.Operators.php 97 0 +test/fixable/7.Closures.php 2 0 +test/fixable/8.AnonymousClasses.php 1 0 +test/fixable/9.CommentingAndDocBlocks.php 22 0 ---------------------------------------------------------------------- -A TOTAL OF 441 ERRORS AND 6 WARNINGS WERE FOUND IN 33 FILES +A TOTAL OF 584 ERRORS AND 2 WARNINGS WERE FOUND IN 30 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 377 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 494 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/2.1.BasicCodingStandard.php b/test/fixable/2.1.BasicCodingStandard.php new file mode 100644 index 00000000..48318cc5 --- /dev/null +++ b/test/fixable/2.1.BasicCodingStandard.php @@ -0,0 +1,175 @@ + $b) { + $foo->bar($arg1); + } else { + new DateTimeImmutable('@' . time(), new DateTimeZone('UTC')); + } + } + + final public static function bar(): void + { + // method body + } + + public function testThereMayNotBeAnyContentBeforeTheOpeningTag(): void + { + // There MAY NOT be any content before the opening tag. + } + + public function testTheShortOpenTagMayNotBeUsed(): void + { + // The short open tag MAY NOT be used. + } + + public function testTheShortEchoTagMayBeUsedInTemplates(): void + { + // The short echo tag MAY be used in templates. + } + + public function testThereMayNotBeInlineHtml(): void + { + // There MAY NOT be any inline HTML in PHP code. + } + + public function testDeprecatedPHPFunctionsMustBeAvoided(): void + { + // Deprecated PHP functions MUST be avoided. + } + + public function testTheBacktickOperatorMayNotBeUsed(): void + { + // The backtick operator MAY NOT be used. + } + + public function testTheGotoLanguageConstructMayNotBeUsed(): void + { + // The PHP `goto` language construct MAY NOT be used. + } + + public function testTheGlobalKeywordMayNotBeUsed(): void + { + // The `global` keyword MAY NOT be used. + } + + public function testThePHPSAPIConstantShouldBeUsed(): void + { + // The constant `PHP_SAPI` SHOULD be used instead of the + // `php_sapi_name()` function. + + if (PHP_SAPI !== 'cli') { + return; + } + } + + public function testAliasFunctionsShouldNotBeUsed(): void + { + // Alias functions SHOULD NOT be used. + + echo chop('abc '); + echo sizeof([1, 2, 3]); + echo is_null(456) ? 'y' : 'n'; + $foo = '1'; + settype($foo, 'int'); + var_dump($foo); + $bar = [ + 'foo' => 1, + 'bar' => 2, + 'baz' => 3, + ]; + extract($bar); + compact('foo', 'bar'); + } + + public function testSemicolonsUsage(): void + { + // There MAY NOT be a space before a semicolon. Redundant semicolons + // SHOULD be avoided. + + $a = $b{0} ; + $hello = 1 ;; + $world = $hello ;;; /* comment */ + } + + public function testNonExecutableCodeMMustBeRemoved(int $x): int + { + // Non executable code MUST be removed. + + return $x + 1; + + $x += 2; // Intentional dead code + } + + public function testLanguageConstructSpacing(string $blah): string + { + // There MUST be a single space after language constructs. + + echo $blah; + echo $blah; + + print $blah; + print $blah; + + include $blah; + include_once $blah; + + require $blah; + require_once $blah; + + $obj = new MyClass(); + $obj = new MyClass(); + + return $blah; + } + + public function testLanguageConstructsMustBeCalledWithoutParentheses(): string + { + // Language constructs MUST be called without parentheses where possible. + + include ('file.php'); + include_once('file.php'); + require('file.php'); + require_once('file.php'); + + return('foo'); + } + + public function testPHPFunctionCallsMustBeLowercase(string $text): string + { + // PHP function calls MUST be in lowercase. + + return strToLower /*comment*/ ($text); + } +} diff --git a/test/fixable/2.2.Files.php b/test/fixable/2.2.Files.php new file mode 100644 index 00000000..71672e93 --- /dev/null +++ b/test/fixable/2.2.Files.php @@ -0,0 +1,33 @@ + diff --git a/test/fixable/2.3.Lines.php b/test/fixable/2.3.Lines.php new file mode 100644 index 00000000..f6745588 --- /dev/null +++ b/test/fixable/2.3.Lines.php @@ -0,0 +1,104 @@ + 'value1', + 'key2' => 'value2', + 'keyTwenty' => 'value3', + ]; + + $array2 = [ + 'one' => function () { + $foo = [1, 2, 3]; + $barBar = [ + 1, + 2, + 3, + ]; + }, + 'longer' => 2, + 3 => 'three', + ]; + } + + public function testShortListSyntax(): void + { + // The short list syntax `[...]` SHOULD be used instead of `list(...)`. + + list($a, $b, $c) = array(1, 2, 3); + + list("a" => $a, "b" => $b, "c" => $c) = array("a" => 1, "b" => 2, "c" => 3); + + list($a, $b) = array($b, $a); + } +} diff --git a/test/fixable/3.DeclareNamespaceAndImport.php b/test/fixable/3.DeclareNamespaceAndImport.php new file mode 100644 index 00000000..691d1fb2 --- /dev/null +++ b/test/fixable/3.DeclareNamespaceAndImport.php @@ -0,0 +1,103 @@ +sub(new DateInterval('P1D')) + ->format(DATE_RFC3339) + ); + + new Baz(); + } + + public function testDeclareStatement(): void + { + // When wishing to declare strict types in files containing markup + // outside PHP opening and closing tags, the declaration MUST be on the + // first line of the file and include an opening PHP tag, the strict + // types declaration and closing tag. + // + // Declare statements MUST contain no spaces and MUST be exactly + // declare(strict_types=1) (with an optional semi-colon terminator). + // + // Block declare statements are allowed and MUST be formatted as below. + + declare(ticks=1) + { + // some code + } + } +} diff --git a/test/fixable/4.1.ExtendsAndImplements.php b/test/fixable/4.1.ExtendsAndImplements.php new file mode 100644 index 00000000..dd093fee --- /dev/null +++ b/test/fixable/4.1.ExtendsAndImplements.php @@ -0,0 +1,38 @@ +name; + } + + public function testReturnedVariablesShouldBeUseful(): bool + { + // Returned variables SHOULD be useful and not be assign to a value and + // returned on the next line. + + $a = true; + + return $a; + } +} diff --git a/test/fixable/4.5.MethodAndFunctionArguments.php b/test/fixable/4.5.MethodAndFunctionArguments.php new file mode 100644 index 00000000..38f10392 --- /dev/null +++ b/test/fixable/4.5.MethodAndFunctionArguments.php @@ -0,0 +1,95 @@ +bar( $arg1 ); + Foo::bar( $arg2 , $arg3 ); + } + + public function testArguments(): void + { + // Argument lists MAY be split across multiple lines, where each + // subsequent line is indented once. When doing so, the first item in the + // list MUST be on the next line, and there MUST be only one argument per + // line. A single argument being split across multiple lines (as might be + // the case with an anonymous function or array) does not constitute + // splitting the argument list itself. + + $foo->bar( + $longArgument, $longerArgument, $muchLongerArgument + ); + + $app->get('/hello/{name}', function ($name) use ($app) { + return 'Hello ' . $app->escape($name); + }); + } +} diff --git a/test/fixable/4.ClassesPropertiesAndMethods.php b/test/fixable/4.ClassesPropertiesAndMethods.php new file mode 100644 index 00000000..778d2772 --- /dev/null +++ b/test/fixable/4.ClassesPropertiesAndMethods.php @@ -0,0 +1,118 @@ + 0 && $n < 10) + || ($n > 10 && $n < 20) + || ($n > 20 && $n < 30) + ) { + return $n; + } + + if ( + ( + $expr1 + && $expr2 + && $expr3 + && $expr4 + && $expr5 + && $expr6 + ) + || ($n > 100 && $n < 200) + || ($n > 200 && $n < 300) + ) { + return $n; + } + } +} diff --git a/test/fixable/5.2.SwitchCase.php b/test/fixable/5.2.SwitchCase.php new file mode 100644 index 00000000..ba4c94c9 --- /dev/null +++ b/test/fixable/5.2.SwitchCase.php @@ -0,0 +1,87 @@ + $value ) + { + echo sprintf('%d - %s', $key, $value); + } + } +} diff --git a/test/fixable/5.6.TryCatchFinally.php b/test/fixable/5.6.TryCatchFinally.php new file mode 100644 index 00000000..3efbe61b --- /dev/null +++ b/test/fixable/5.6.TryCatchFinally.php @@ -0,0 +1,43 @@ +getMessage(); + } catch ( OtherThrowableType | AnotherThrowableType $e ) { + echo $e->getMessage(); + } finally + { + echo 'Done!'; + } + } + + public function testUnreacableCatchBlock(): void + { + // All catch blocks MUST be reachable. + + try { + $x = 1 + 2; + } catch (Throwable $e) { + echo $e; + } catch (InvalidArgumentException $e) { + echo $e; // unreachable! + } + } +} diff --git a/test/fixable/5.ControlStructures.php b/test/fixable/5.ControlStructures.php new file mode 100644 index 00000000..697fb18d --- /dev/null +++ b/test/fixable/5.ControlStructures.php @@ -0,0 +1,89 @@ +$b) { + $foo=$a+$b*$c; + } + } +} diff --git a/test/fixable/6.3.TernaryOperators.php b/test/fixable/6.3.TernaryOperators.php new file mode 100644 index 00000000..b2cf0fd8 --- /dev/null +++ b/test/fixable/6.3.TernaryOperators.php @@ -0,0 +1,23 @@ +testOperatorSpacing(); + $this-> testOperatorSpacing(); + $this -> testOperatorSpacing(); + $this + ->testOperatorSpacing(); + $this-> + testOperatorSpacing(); + } + + + public function testUseStrictComparisonOperators(): void + { + // Loose comparison operators SHOULD NOT be used, use strict comparison + // operators instead. + + $foo == 123; + 123 == $foo; + true != 0.0; + false <> true; + } + + public function testUseNullCoalesceOperator(): void + { + // The null coalesce operator MUST be used when possible. + + $a = isset($_GET['a']) ? $_GET['a'] : 'a'; + $b = isset($bb) ? $bb : 'bb'; + $c = isset($cc['c']) ? $cc['c'] : 'c'; + } + + public function testAssignmentOperators(int $var): void + { + // Assignment operators SHOULD be used when possible. + + $var = $var & 2; + $var = $var | 4; + $var = $var . ''; + $var = $var / 10; + $var = $var - 100; + $var = $var ** 2; + $var = $var % 2; + $var = $var * 1000; + $var = $var + 4; + $var = $var << 2; + $var = $var >> 2; + $var = $var ^ 10; + $var = $var + 10; + } +} diff --git a/test/fixable/7.Closures.php b/test/fixable/7.Closures.php new file mode 100644 index 00000000..0d2d140b --- /dev/null +++ b/test/fixable/7.Closures.php @@ -0,0 +1,73 @@ + + * + * + * + * @internal + * @deprecated + * @link + * @see + * @uses + * @param + * + * @return + * + * @throws + * + */ + public function testDocBlockSpacing(): void + { + } + + public function testInlineCommentMustBeAtTheEnd(): void + { + $hello = $world; /* comment */ + $hello = /* comment */ $world; + } + + /** + * Sets a single-line title. + * + * The `param` and `return` tags should be omitted as they are already + * type hinted. + * + * @param string $title + * @return void + */ + public function setTitle(string $title): void + { + // there should be no docblock here + $this->title = $title; + } + + /** + * All tags can be omitted as typehints describe it all. + * + * @param bool $createNew + * @return stdClass|null + */ + public function foo(bool $createNew): ?stdClass + { + if ($createNew) { + return new stdClass(); + } + return null; + } + + /** + * The returned array should be described with a `return` tag. + * + * @return SQLite3[] $connections + */ + public function testIdeAutoCompletion(): array + { + /** @var SQLite3 $sqlite */ + foreach ($connections as $sqlite) { + // there should be no docblock here + $sqlite->open('/my/database/path'); + } + + return $connections; + } +} diff --git a/test/fixable/LowCaseTypes.php b/test/fixable/LowCaseTypes.php deleted file mode 100644 index 41f8803b..00000000 --- a/test/fixable/LowCaseTypes.php +++ /dev/null @@ -1,18 +0,0 @@ - 1, - 'bar' => 2, - 'baz' => 3, -]; - -$singleLine = [ - 1 => 2, -]; -$singleLine2 = [ 'foo' => 'bar' ] ; - -$serializedRequest = [ - 'method' => 'POST', - 'request_target' => '/foo/bar?baz=bat', - 'uri' => 'http://example.com/foo/bar?baz=bat', - 'protocol_version' => '1.1', - 'headers' => [ - 'Host' => ['example.com'], - 'Accept' => ['application/json'], - 'X-Foo-Bar' => [ - 'Baz', - 'Bat', - ], - ], - - 'body' => '{"test":"value"}', -]; - -// https://github.com/zendframework/zend-diactoros/blob/69dc20275fb8b9f7f8e05d556f6c0da5f36cac64/test/ServerRequestFactoryTest.php#L392-L398 -$files = [ 'files' => [ - 'tmp_name' => 'php://temp', - 'size' => 0, - 'error' => 0, - 'name' => 'foo.bar', - 'type' => 'text/plain', -]]; - -// Long lines test -$config = [ - 'dependencies' => [ - 'factories' => [ - App\Domain\User\UserRepository::class => App\Domain\User\Persistence\DoctrineUserRepositoryFactory::class, - App\Http\Auth\LoginHandler::class => App\Http\Auth\LoginHandlerFactory::class, - App\Http\Auth\LogoutHandler::class => App\Http\Auth\LogoutHandlerFactory::class, - - App\Infrastructure\View\TemplateDefaultsMiddleware::class - => App\Infrastructure\View\TemplateDefaultsMiddlewareFactory::class, - App\Http\HomePageHandler::class => App\Http\HomePageHandlerFactory::class, - App\Http\StaticPageHandler::class => App\Http\StaticPageHandlerFactory::class, - ], - ], -]; diff --git a/test/fixable/class-name-resolution.php b/test/fixable/class-name-resolution.php deleted file mode 100644 index d14aa244..00000000 --- a/test/fixable/class-name-resolution.php +++ /dev/null @@ -1,47 +0,0 @@ - 1) { - continue; - } - break 1; -} - -while ($a > 1) { - for ($i = $a; $i < $b; ++$i) { - if ($i % 2) { - continue 1; - } - - break 2; - } -} - -if ($a === ($b + 1)) { - echo 1; -} diff --git a/test/fixable/example-class.php b/test/fixable/example-class.php deleted file mode 100644 index ae713685..00000000 --- a/test/fixable/example-class.php +++ /dev/null @@ -1,101 +0,0 @@ -foo = $foo; - $this->bar = $bar; - $this->baz = $baz; - $this->baxBax = $baxBax; - } - - /** - * Description - */ - public function getFoo(): ? int - { - return $this->foo; - } - - /** - * @return iterable - */ - public function getIterator():array - { - assert($this->bar !== null); - return new \ArrayIterator($this->bar); - } - - public function isBaz() : bool - { - list($foo, $bar, $baz) = $this->bar; - - return $this->baz; - } - - public function mangleBar(int $length) : void - { - if (!$this->baz) { - throw new \InvalidArgumentException(); - } - - $this->bar = (string) $this->baxBax ?? \substr($this->bar, stringLength($this->bar - $length)); - } - - public static function getMinorVersion() : int - { - $version = self::VERSION; - - return $version; - } - - public static function getTestCase() : TestCase - { - return new TestCase(); - } -} diff --git a/test/fixable/extends-and-implements-multiline.php b/test/fixable/extends-and-implements-multiline.php deleted file mode 100644 index d82fa905..00000000 --- a/test/fixable/extends-and-implements-multiline.php +++ /dev/null @@ -1,20 +0,0 @@ - 1, - 'bar' => 2, - 'baz' => 3, -]; -extract($bar); - -compact('foo', 'bar'); diff --git a/test/fixable/heredoc-nowdoc.php b/test/fixable/heredoc-nowdoc.php deleted file mode 100644 index 8d92e1b1..00000000 --- a/test/fixable/heredoc-nowdoc.php +++ /dev/null @@ -1,25 +0,0 @@ -process($bar); - } -} diff --git a/test/fixable/method-and-function-calls.php b/test/fixable/method-and-function-calls.php deleted file mode 100644 index 81f51280..00000000 --- a/test/fixable/method-and-function-calls.php +++ /dev/null @@ -1,23 +0,0 @@ -bar ( $arg1 ); -Foo::bar ($arg2 , $arg3) ; - -$foo->bar( - $longArgument, - $longerArgument, - $muchLongerArgument -); - -somefunction($foo, $bar, [ - // ... -], $baz); - -$app->get ('/hello/{name}' , function ($name) use ($app) { - - return 'Hello ' . $app->escape($name); - -}); diff --git a/test/fixable/namespaces-spacing.php b/test/fixable/namespaces-spacing.php deleted file mode 100644 index f8ace32c..00000000 --- a/test/fixable/namespaces-spacing.php +++ /dev/null @@ -1,20 +0,0 @@ -sub(new DateInterval('P1D')) - ->format(DATE_RFC3339) -); - -new \ Bar \ Baz(); diff --git a/test/fixable/naming.php b/test/fixable/naming.php deleted file mode 100644 index bd516a99..00000000 --- a/test/fixable/naming.php +++ /dev/null @@ -1,25 +0,0 @@ -foo = 'Foo'; -$foo = new $classNamesInObject->foo; - -$whitespaceBetweenClassNameAndParentheses = new stdClass ; - -$x = [ - new stdClass, -]; - -$y = [new stdClass]; - -$z = new stdClass ? new stdClass : new stdClass; - -$q = $q ?: new stdClass; -$e = $e ?? new stdClass; - -// The parentheses around `(new Response())` should not be removed -// https://github.com/slevomat/coding-standard/issues/478 -$response = (new Response()) - ->withStatus(200) - ->withAddedHeader('Content-Type', 'text/plain'); - -$anonymousClass = new class extends DateTime { -}; diff --git a/test/fixable/not-spacing.php b/test/fixable/not-spacing.php deleted file mode 100644 index 43a087c9..00000000 --- a/test/fixable/not-spacing.php +++ /dev/null @@ -1,57 +0,0 @@ - 0) { - echo 1; -} elseif ( !$test === 0) { - echo 0; -} else { - echo 2; -} - -while ( ! true) { - - echo 1; - // comment - -} - -do { - - echo 1; - -} while ( ! true); - -new DateTime(); -new\DateTime(); - - -class SingleLineBetweenMethods -{ - public function __construct() - { - } - public function method() - { - } - - - public function twoLines() - { - } -} - -$a ++; -$b --; --- $c; -++ $d; - -function nullableTypes(? int $int, ? \Complex\Type $ct) : ? string -{ - return function (? bool $b) : ? float { - return 0.0; - }; -} diff --git a/test/fixable/operators.php b/test/fixable/operators.php deleted file mode 100644 index a126e54c..00000000 --- a/test/fixable/operators.php +++ /dev/null @@ -1,46 +0,0 @@ - $b) { - $variable = $foo ? 'foo' : 'bar'; -} - -$foo = isset($_GET['foo']) ? $_GET['foo'] : 'foo'; - -$bar = isset($bar) ? $bar : 'bar'; - -$bar = isset($bar['baz']) ? $bar['baz'] : 'baz'; - -if (isset($foo)) { - $bar = $foo; -} else { - $bar = 'foo'; -} - -$fooBar = isset($foo, $bar) ? 'foo' : 'bar'; - -$baz = ! isset($foo) ? 'foo' : 'baz'; - -echo Something - :: - BAR; - -if ($a && - $b) { - echo 1; -} - -$a ? - $b : - $c; diff --git a/test/fixable/return-type-on-methods.php b/test/fixable/return-type-on-methods.php deleted file mode 100644 index 58bdb665..00000000 --- a/test/fixable/return-type-on-methods.php +++ /dev/null @@ -1,73 +0,0 @@ -select() - ->from() - ->where() -; diff --git a/test/fixable/spacing.php b/test/fixable/spacing.php deleted file mode 100644 index c108bcab..00000000 --- a/test/fixable/spacing.php +++ /dev/null @@ -1,30 +0,0 @@ - [1, 2, 3], - 'longKey' => [111, 222, 333], -]; - -abstract class MyClassSpacing -{ - abstract public function method($x,$y, $z); -} - -$a1 = array_unique([1, 2], [3, 4]); -$a2 = [[1, 2, 3]]; diff --git a/test/fixable/statement-alignment.php b/test/fixable/statement-alignment.php deleted file mode 100644 index 14f5a601..00000000 --- a/test/fixable/statement-alignment.php +++ /dev/null @@ -1,16 +0,0 @@ - $b) { + $foo->bar($arg1); + } else { + new DateTimeImmutable('@' . time(), new DateTimeZone('UTC')); + } + } + + final public static function bar(): void + { + // method body + } + + public function testThereMayNotBeAnyContentBeforeTheOpeningTag(): void + { + // There MAY NOT be any content before the opening tag. + } + + public function testTheShortOpenTagMayNotBeUsed(): void + { + // The short open tag MAY NOT be used. + } + + public function testTheShortEchoTagMayBeUsedInTemplates(): void + { + // The short echo tag MAY be used in templates. + } + + public function testThereMayNotBeInlineHtml(): void + { + // There MAY NOT be any inline HTML in PHP code. + } + + public function testDeprecatedPHPFunctionsMustBeAvoided(): void + { + // Deprecated PHP functions MUST be avoided. + } + + public function testTheBacktickOperatorMayNotBeUsed(): void + { + // The backtick operator MAY NOT be used. + } + + public function testTheGotoLanguageConstructMayNotBeUsed(): void + { + // The PHP `goto` language construct MAY NOT be used. + } + + public function testTheGlobalKeywordMayNotBeUsed(): void + { + // The `global` keyword MAY NOT be used. + } + + public function testThePHPSAPIConstantShouldBeUsed(): void + { + // The constant `PHP_SAPI` SHOULD be used instead of the + // `php_sapi_name()` function. + + if (PHP_SAPI !== 'cli') { + return; + } + } + + public function testAliasFunctionsShouldNotBeUsed(): void + { + // Alias functions SHOULD NOT be used. + + echo chop('abc '); + echo sizeof([1, 2, 3]); + echo is_null(456) ? 'y' : 'n'; + $foo = '1'; + settype($foo, 'int'); + var_dump($foo); + $bar = [ + 'foo' => 1, + 'bar' => 2, + 'baz' => 3, + ]; + extract($bar); + compact('foo', 'bar'); + } + + public function testSemicolonsUsage(): void + { + // There MAY NOT be a space before a semicolon. Redundant semicolons + // SHOULD be avoided. + + $a = $b{0}; + $hello = 1; + $world = $hello; /* comment */ + } + + public function testNonExecutableCodeMMustBeRemoved(int $x): int + { + // Non executable code MUST be removed. + + return $x + 1; + + $x += 2; // Intentional dead code + } + + public function testLanguageConstructSpacing(string $blah): string + { + // There MUST be a single space after language constructs. + + echo $blah; + echo $blah; + + print $blah; + print $blah; + + include $blah; + include_once $blah; + + require $blah; + require_once $blah; + + $obj = new MyClass(); + $obj = new MyClass(); + + return $blah; + } + + public function testLanguageConstructsMustBeCalledWithoutParentheses(): string + { + // Language constructs MUST be called without parentheses where possible. + + include 'file.php'; + include_once 'file.php'; + require 'file.php'; + require_once 'file.php'; + + return 'foo'; + } + + public function testPHPFunctionCallsMustBeLowercase(string $text): string + { + // PHP function calls MUST be in lowercase. + + return strtolower($text); + } +} diff --git a/test/fixed/2.2.Files.php b/test/fixed/2.2.Files.php new file mode 100644 index 00000000..fa0b27d6 --- /dev/null +++ b/test/fixed/2.2.Files.php @@ -0,0 +1,29 @@ + 'value1', + 'key2' => 'value2', + 'keyTwenty' => 'value3', + ]; + + $array2 = [ + 'one' => function () { + $foo = [1, 2, 3]; + $barBar = [ + 1, + 2, + 3, + ]; + }, + 'longer' => 2, + 3 => 'three', + ]; + } + + public function testShortListSyntax(): void + { + // The short list syntax `[...]` SHOULD be used instead of `list(...)`. + + [$a, $b, $c] = [1, 2, 3]; + + ["a" => $a, "b" => $b, "c" => $c] = ["a" => 1, "b" => 2, "c" => 3]; + + [$a, $b] = [$b, $a]; + } +} diff --git a/test/fixed/3.DeclareNamespaceAndImport.php b/test/fixed/3.DeclareNamespaceAndImport.php new file mode 100644 index 00000000..8d525f7b --- /dev/null +++ b/test/fixed/3.DeclareNamespaceAndImport.php @@ -0,0 +1,106 @@ +sub(new DateInterval('P1D')) + ->format(DATE_RFC3339) + ); + + new Baz(); + } + + public function testDeclareStatement(): void + { + // When wishing to declare strict types in files containing markup + // outside PHP opening and closing tags, the declaration MUST be on the + // first line of the file and include an opening PHP tag, the strict + // types declaration and closing tag. + // + // Declare statements MUST contain no spaces and MUST be exactly + // declare(strict_types=1) (with an optional semi-colon terminator). + // + // Block declare statements are allowed and MUST be formatted as below. + + declare(ticks=1) { + // some code + } + } +} diff --git a/test/fixed/4.1.ExtendsAndImplements.php b/test/fixed/4.1.ExtendsAndImplements.php new file mode 100644 index 00000000..065fbc94 --- /dev/null +++ b/test/fixed/4.1.ExtendsAndImplements.php @@ -0,0 +1,36 @@ +name; + } + + public function testReturnedVariablesShouldBeUseful(): bool + { + // Returned variables SHOULD be useful and not be assign to a value and + // returned on the next line. + + return true; + } +} diff --git a/test/fixed/4.5.MethodAndFunctionArguments.php b/test/fixed/4.5.MethodAndFunctionArguments.php new file mode 100644 index 00000000..6b6b7928 --- /dev/null +++ b/test/fixed/4.5.MethodAndFunctionArguments.php @@ -0,0 +1,96 @@ +bar($arg1); + Foo::bar($arg2, $arg3); + } + + public function testArguments(): void + { + // Argument lists MAY be split across multiple lines, where each + // subsequent line is indented once. When doing so, the first item in the + // list MUST be on the next line, and there MUST be only one argument per + // line. A single argument being split across multiple lines (as might be + // the case with an anonymous function or array) does not constitute + // splitting the argument list itself. + + $foo->bar( + $longArgument, + $longerArgument, + $muchLongerArgument + ); + + $app->get('/hello/{name}', function ($name) use ($app) { + return 'Hello ' . $app->escape($name); + }); + } +} diff --git a/test/fixed/4.ClassesPropertiesAndMethods.php b/test/fixed/4.ClassesPropertiesAndMethods.php new file mode 100644 index 00000000..c5de4a54 --- /dev/null +++ b/test/fixed/4.ClassesPropertiesAndMethods.php @@ -0,0 +1,115 @@ + 0 && $n < 10) + || ($n > 10 && $n < 20) + || ($n > 20 && $n < 30) + ) { + return $n; + } + + if ( + ( + $expr1 + && $expr2 + && $expr3 + && $expr4 + && $expr5 + && $expr6 + ) + || ($n > 100 && $n < 200) + || ($n > 200 && $n < 300) + ) { + return $n; + } + } +} diff --git a/test/fixed/5.2.SwitchCase.php b/test/fixed/5.2.SwitchCase.php new file mode 100644 index 00000000..65fc649c --- /dev/null +++ b/test/fixed/5.2.SwitchCase.php @@ -0,0 +1,87 @@ + $value) { + echo sprintf('%d - %s', $key, $value); + } + } +} diff --git a/test/fixed/5.6.TryCatchFinally.php b/test/fixed/5.6.TryCatchFinally.php new file mode 100644 index 00000000..458c487e --- /dev/null +++ b/test/fixed/5.6.TryCatchFinally.php @@ -0,0 +1,40 @@ +getMessage(); + } catch (OtherThrowableType | AnotherThrowableType $e) { + echo $e->getMessage(); + } finally { + echo 'Done!'; + } + } + + public function testUnreacableCatchBlock(): void + { + // All catch blocks MUST be reachable. + + try { + $x = 1 + 2; + } catch (Throwable $e) { + echo $e; + } catch (InvalidArgumentException $e) { + echo $e; // unreachable! + } + } +} diff --git a/test/fixed/5.ControlStructures.php b/test/fixed/5.ControlStructures.php new file mode 100644 index 00000000..eaae62d1 --- /dev/null +++ b/test/fixed/5.ControlStructures.php @@ -0,0 +1,88 @@ + $b) { + $foo = $a + $b * $c; + } + } +} diff --git a/test/fixed/6.3.TernaryOperators.php b/test/fixed/6.3.TernaryOperators.php new file mode 100644 index 00000000..6f031551 --- /dev/null +++ b/test/fixed/6.3.TernaryOperators.php @@ -0,0 +1,23 @@ +testOperatorSpacing(); + $this->testOperatorSpacing(); + $this->testOperatorSpacing(); + $this + ->testOperatorSpacing(); + $this-> + testOperatorSpacing(); + } + + public function testUseStrictComparisonOperators(): void + { + // Loose comparison operators SHOULD NOT be used, use strict comparison + // operators instead. + + $foo === 123; + 123 === $foo; + true !== 0.0; + false !== true; + } + + public function testUseNullCoalesceOperator(): void + { + // The null coalesce operator MUST be used when possible. + + $a = $_GET['a'] ?? 'a'; + $b = $bb ?? 'bb'; + $c = $cc['c'] ?? 'c'; + } + + public function testAssignmentOperators(int $var): void + { + // Assignment operators SHOULD be used when possible. + + $var &= 2; + $var |= 4; + $var .= ''; + $var /= 10; + $var -= 100; + $var **= 2; + $var %= 2; + $var *= 1000; + $var += 4; + $var <<= 2; + $var >>= 2; + $var ^= 10; + $var += 10; + } +} diff --git a/test/fixed/7.Closures.php b/test/fixed/7.Closures.php new file mode 100644 index 00000000..b2aeabc5 --- /dev/null +++ b/test/fixed/7.Closures.php @@ -0,0 +1,73 @@ + + * + * + * + * @internal + * @deprecated + * + * @link + * @uses + * @see + * + * @param + * @return + * @throws + */ + public function testDocBlockSpacing(): void + { + } + + public function testInlineCommentMustBeAtTheEnd(): void + { + $hello = $world; /* comment */ + $hello = $world; /* comment */ + } + + /** + * Sets a single-line title. + * + * The `param` and `return` tags should be omitted as they are already + * type hinted. + */ + public function setTitle(string $title): void + { + // there should be no docblock here + $this->title = $title; + } + + /** + * All tags can be omitted as typehints describe it all. + */ + public function foo(bool $createNew): ?stdClass + { + if ($createNew) { + return new stdClass(); + } + return null; + } + + /** + * The returned array should be described with a `return` tag. + * + * @return SQLite3[] $connections + */ + public function testIdeAutoCompletion(): array + { + /** @var SQLite3 $sqlite */ + foreach ($connections as $sqlite) { + // there should be no docblock here + $sqlite->open('/my/database/path'); + } + + return $connections; + } +} diff --git a/test/fixed/LowCaseTypes.php b/test/fixed/LowCaseTypes.php deleted file mode 100644 index 4782ba1c..00000000 --- a/test/fixed/LowCaseTypes.php +++ /dev/null @@ -1,18 +0,0 @@ - 1, - 'bar' => 2, - 'baz' => 3, -]; - -$singleLine = [ - 1 => 2, -]; -$singleLine2 = ['foo' => 'bar']; - -$serializedRequest = [ - 'method' => 'POST', - 'request_target' => '/foo/bar?baz=bat', - 'uri' => 'http://example.com/foo/bar?baz=bat', - 'protocol_version' => '1.1', - 'headers' => [ - 'Host' => ['example.com'], - 'Accept' => ['application/json'], - 'X-Foo-Bar' => [ - 'Baz', - 'Bat', - ], - ], - - 'body' => '{"test":"value"}', -]; - -// https://github.com/zendframework/zend-diactoros/blob/69dc20275fb8b9f7f8e05d556f6c0da5f36cac64/test/ServerRequestFactoryTest.php#L392-L398 -$files = [ - 'files' => [ - 'tmp_name' => 'php://temp', - 'size' => 0, - 'error' => 0, - 'name' => 'foo.bar', - 'type' => 'text/plain', - ], -]; - -// Long lines test -$config = [ - 'dependencies' => [ - 'factories' => [ - App\Domain\User\UserRepository::class => App\Domain\User\Persistence\DoctrineUserRepositoryFactory::class, - App\Http\Auth\LoginHandler::class => App\Http\Auth\LoginHandlerFactory::class, - App\Http\Auth\LogoutHandler::class => App\Http\Auth\LogoutHandlerFactory::class, - - App\Infrastructure\View\TemplateDefaultsMiddleware::class - => App\Infrastructure\View\TemplateDefaultsMiddlewareFactory::class, - App\Http\HomePageHandler::class => App\Http\HomePageHandlerFactory::class, - App\Http\StaticPageHandler::class => App\Http\StaticPageHandlerFactory::class, - ], - ], -]; diff --git a/test/fixed/class-name-resolution.php b/test/fixed/class-name-resolution.php deleted file mode 100644 index e17d168a..00000000 --- a/test/fixed/class-name-resolution.php +++ /dev/null @@ -1,47 +0,0 @@ - 1) { - break; - } - break; -} - -while ($a > 1) { - for ($i = $a; $i < $b; ++$i) { - if ($i % 2) { - continue; - } - - break 2; - } -} - -if ($a === $b + 1) { - echo 1; -} diff --git a/test/fixed/example-class.php b/test/fixed/example-class.php deleted file mode 100644 index 96cf1a3e..00000000 --- a/test/fixed/example-class.php +++ /dev/null @@ -1,97 +0,0 @@ -foo = $foo; - $this->bar = $bar; - $this->baz = $baz; - $this->baxBax = $baxBax; - } - - /** - * Description - */ - public function getFoo() : ?int - { - return $this->foo; - } - - /** - * @return iterable - */ - public function getIterator() : array - { - assert($this->bar !== null); - return new ArrayIterator($this->bar); - } - - public function isBaz() : bool - { - [$foo, $bar, $baz] = $this->bar; - - return $this->baz; - } - - public function mangleBar(int $length) : void - { - if (! $this->baz) { - throw new InvalidArgumentException(); - } - - $this->bar = (string) $this->baxBax ?? substr($this->bar, stringLength($this->bar - $length)); - } - - public static function getMinorVersion() : int - { - return self::VERSION; - } - - public static function getTestCase() : TestCase - { - return new TestCase(); - } -} diff --git a/test/fixed/extends-and-implements-multiline.php b/test/fixed/extends-and-implements-multiline.php deleted file mode 100644 index 04e643c5..00000000 --- a/test/fixed/extends-and-implements-multiline.php +++ /dev/null @@ -1,18 +0,0 @@ - 1, - 'bar' => 2, - 'baz' => 3, -]; -extract($bar); - -compact('foo', 'bar'); diff --git a/test/fixed/heredoc-nowdoc.php b/test/fixed/heredoc-nowdoc.php deleted file mode 100644 index a929db22..00000000 --- a/test/fixed/heredoc-nowdoc.php +++ /dev/null @@ -1,25 +0,0 @@ -process($bar); - } -} diff --git a/test/fixed/method-and-function-calls.php b/test/fixed/method-and-function-calls.php deleted file mode 100644 index 5f90cf36..00000000 --- a/test/fixed/method-and-function-calls.php +++ /dev/null @@ -1,21 +0,0 @@ -bar($arg1); -Foo::bar($arg2, $arg3); - -$foo->bar( - $longArgument, - $longerArgument, - $muchLongerArgument -); - -somefunction($foo, $bar, [ - // ... -], $baz); - -$app->get('/hello/{name}', function ($name) use ($app) { - return 'Hello ' . $app->escape($name); -}); diff --git a/test/fixed/namespaces-spacing.php b/test/fixed/namespaces-spacing.php deleted file mode 100644 index 8385e1f7..00000000 --- a/test/fixed/namespaces-spacing.php +++ /dev/null @@ -1,23 +0,0 @@ -sub(new DateInterval('P1D')) - ->format(DATE_RFC3339) -); - -new Baz(); diff --git a/test/fixed/naming.php b/test/fixed/naming.php deleted file mode 100644 index bd516a99..00000000 --- a/test/fixed/naming.php +++ /dev/null @@ -1,25 +0,0 @@ -foo = 'Foo'; -$foo = new $classNamesInObject->foo(); - -$whitespaceBetweenClassNameAndParentheses = new stdClass(); - -$x = [ - new stdClass(), -]; - -$y = [new stdClass()]; - -$z = new stdClass() ? new stdClass() : new stdClass(); - -$q = $q ?: new stdClass(); -$e = $e ?? new stdClass(); - -// The parentheses around `(new Response())` should not be removed -// https://github.com/slevomat/coding-standard/issues/478 -$response = (new Response()) - ->withStatus(200) - ->withAddedHeader('Content-Type', 'text/plain'); - -$anonymousClass = new class() extends DateTime { -}; diff --git a/test/fixed/not-spacing.php b/test/fixed/not-spacing.php deleted file mode 100644 index e69e01c1..00000000 --- a/test/fixed/not-spacing.php +++ /dev/null @@ -1,52 +0,0 @@ - 0) { - echo 1; -} elseif (! $test === 0) { - echo 0; -} else { - echo 2; -} - -while (! true) { - echo 1; - // comment -} - -do { - echo 1; -} while (! true); - -new DateTime(); -new DateTime(); - -class SingleLineBetweenMethods -{ - public function __construct() - { - } - - public function method() - { - } - - public function twoLines() - { - } -} - -$a++; -$b--; ---$c; -++$d; - -function nullableTypes(?int $int, ?Complex\Type $ct) : ?string -{ - return function (?bool $b) : ?float { - return 0.0; - }; -} diff --git a/test/fixed/operators.php b/test/fixed/operators.php deleted file mode 100644 index a85c6fad..00000000 --- a/test/fixed/operators.php +++ /dev/null @@ -1,45 +0,0 @@ - $b) { - $variable = $foo ? 'foo' : 'bar'; -} - -$foo = $_GET['foo'] ?? 'foo'; - -$bar = $bar ?? 'bar'; - -$bar = $bar['baz'] ?? 'baz'; - -if (isset($foo)) { - $bar = $foo; -} else { - $bar = 'foo'; -} - -$fooBar = isset($foo, $bar) ? 'foo' : 'bar'; - -$baz = ! isset($foo) ? 'foo' : 'baz'; - -echo Something::BAR; - -if ($a - && $b -) { - echo 1; -} - -$a - ? $b - : $c; diff --git a/test/fixed/return-type-on-methods.php b/test/fixed/return-type-on-methods.php deleted file mode 100644 index 67c377fa..00000000 --- a/test/fixed/return-type-on-methods.php +++ /dev/null @@ -1,73 +0,0 @@ -select() - ->from() - ->where(); diff --git a/test/fixed/spacing.php b/test/fixed/spacing.php deleted file mode 100644 index cbf4e8ee..00000000 --- a/test/fixed/spacing.php +++ /dev/null @@ -1,30 +0,0 @@ - [1, 2, 3], - 'longKey' => [111, 222, 333], -]; - -abstract class MyClassSpacing -{ - abstract public function method($x, $y, $z); -} - -$a1 = array_unique([1, 2], [3, 4]); -$a2 = [[1, 2, 3]]; diff --git a/test/fixed/statement-alignment.php b/test/fixed/statement-alignment.php deleted file mode 100644 index 55cbfbcc..00000000 --- a/test/fixed/statement-alignment.php +++ /dev/null @@ -1,16 +0,0 @@ -