From dbacd1210aa564afe7eb56d7718eacd1d56b2f23 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 10:35:45 +0200 Subject: [PATCH 01/60] Import strict ruleset --- .gitignore | 4 + README.md | 2 +- composer.json | 20 +- ruleset.xml | 23 -- src/ZendCodingStandard/ruleset.xml | 379 +++++++++++++++++++++++++++++ 5 files changed, 401 insertions(+), 27 deletions(-) create mode 100644 .gitignore delete mode 100644 ruleset.xml create mode 100644 src/ZendCodingStandard/ruleset.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..46946e2b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +vendor/ +phpcs.xml +composer.lock +phpcs.log diff --git a/README.md b/README.md index 2a7e94a8..4f0b2e13 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Usage ``` * To automatically fix many CS issues: - + ```bash $ composer cs-fix ``` diff --git a/composer.json b/composer.json index 89f82020..1425db1e 100644 --- a/composer.json +++ b/composer.json @@ -1,12 +1,26 @@ { "name": "zendframework/zend-coding-standard", - "description": "Zend Framework coding standard", - "license": "BSD-3-Clause", + "type": "phpcodesniffer-standard", + "description": "Zend Framework Coding Standard", "keywords": [ "zf", "coding standard" ], + "license": "BSD-3-Clause", "require": { - "squizlabs/php_codesniffer": "^2.7" + "php": "^7.1", + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", + "slevomat/coding-standard": "^4.7.3", + "squizlabs/php_codesniffer": "^3.3.1" + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "ZendCodingStandard\\Sniffs\\": "src/ZendCodingStandard/Sniffs" + } } } diff --git a/ruleset.xml b/ruleset.xml deleted file mode 100644 index 2e2536e0..00000000 --- a/ruleset.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - Zend Framework Coding Standard - - - - - - - - - - - - - - - - - - - - diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml new file mode 100644 index 00000000..d2feb76e --- /dev/null +++ b/src/ZendCodingStandard/ruleset.xml @@ -0,0 +1,379 @@ + + + The ZendFramework coding standard. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Variable "%s" not allowed in double quoted string; use sprintf() or concatenation instead + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + From 5863c14c718dea9cb7821119789dcfad63e496cb Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 19:58:23 +0200 Subject: [PATCH 02/60] Allow functions inside functions --- src/ZendCodingStandard/ruleset.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index d2feb76e..5e98669c 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -327,8 +327,6 @@ - - From 06a5606d26253ed1aea79b63538154acfc8a1316 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 19:58:53 +0200 Subject: [PATCH 03/60] Allow @var for constants --- src/ZendCodingStandard/ruleset.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 5e98669c..309b21f7 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -248,8 +248,6 @@ - - From d27454daba42a408f3a1b9bbef8e836706d2fe3e Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 19:59:36 +0200 Subject: [PATCH 04/60] Allow @since for noting API additions --- src/ZendCodingStandard/ruleset.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 309b21f7..98cb4b9a 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -125,7 +125,6 @@ @category, @created, @package, - @since, @subpackage, @version " From 646eea12ebed33899f30d5ded184e8f41829455a Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 20:00:30 +0200 Subject: [PATCH 05/60] Allow fancy yoda conditions as a defensive programming approach --- src/ZendCodingStandard/ruleset.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 98cb4b9a..c5ea631c 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -150,8 +150,6 @@ - - From fa193f3a62538bb8c26105e088f4d8b747e27295 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 20:08:12 +0200 Subject: [PATCH 06/60] Forbid short open tag, but allow short echo tags for use in templates --- src/ZendCodingStandard/ruleset.xml | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index c5ea631c..8c769ab1 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -11,6 +11,8 @@ + + @@ -22,6 +24,11 @@ + + + + + @@ -71,6 +78,11 @@ "/> + + + + + @@ -78,15 +90,6 @@ - - - - - - - - - @@ -143,7 +146,7 @@ ~^(?:(?!private|protected|static)\S+ )?(?:con|de)structor\.\z~i, ~^Created by \S+\.\z~i, ~^\S+ [gs]etter\.\z~i, - " /> + "/> From f1cef3fee456cf3a4b215893e4ef90f52bcc9788 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 22:17:39 +0200 Subject: [PATCH 07/60] Add documentation structure --- .gitignore | 14 +- .travis.yml | 55 ++++++++ LICENSE.md | 2 +- README.md | 15 +- composer.json | 11 +- CONDUCT.md => docs/CODE_OF_CONDUCT.md | 2 +- docs/CONTRIBUTING.md | 189 ++++++++++++++++++++++++++ docs/ISSUE_TEMPLATE.md | 19 +++ docs/PULL_REQUEST_TEMPLATE.md | 25 ++++ docs/SUPPORT.md | 25 ++++ docs/book/index.html | 9 ++ docs/book/index.md | 1 + docs/book/v1/index.md | 1 + docs/book/v1/intro.md | 51 +++++++ docs/book/v1/ruleset.md | 7 + docs/book/v2/index.md | 1 + docs/book/v2/intro.md | 51 +++++++ docs/book/v2/ruleset.md | 12 ++ mkdocs.yml | 17 +++ 19 files changed, 491 insertions(+), 16 deletions(-) create mode 100644 .travis.yml rename CONDUCT.md => docs/CODE_OF_CONDUCT.md (96%) create mode 100644 docs/CONTRIBUTING.md create mode 100644 docs/ISSUE_TEMPLATE.md create mode 100644 docs/PULL_REQUEST_TEMPLATE.md create mode 100644 docs/SUPPORT.md create mode 100644 docs/book/index.html create mode 100644 docs/book/index.md create mode 100644 docs/book/v1/index.md create mode 100644 docs/book/v1/intro.md create mode 100644 docs/book/v1/ruleset.md create mode 100644 docs/book/v2/index.md create mode 100644 docs/book/v2/intro.md create mode 100644 docs/book/v2/ruleset.md create mode 100644 mkdocs.yml diff --git a/.gitignore b/.gitignore index 46946e2b..b185393a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,10 @@ -vendor/ -phpcs.xml -composer.lock -phpcs.log +/clover.xml +/composer.lock +/coveralls-upload.json +/docs/html/ +/phpcs.log +/phpcs.xml +/phpunit.xml +/vendor/ +/zf-mkdoc-theme.tgz +/zf-mkdoc-theme/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..1aeaccab --- /dev/null +++ b/.travis.yml @@ -0,0 +1,55 @@ +sudo: false + +language: php + +cache: + directories: + - $HOME/.composer/cache + +env: + global: + - COMPOSER_ARGS="--no-interaction" + - COVERAGE_DEPS="php-coveralls/php-coveralls" + +matrix: + include: + - php: 7.1 + env: + - DEPS=lowest + - php: 7.1 + env: + - DEPS=locked + - CS_CHECK=true + - TEST_COVERAGE=true + - php: 7.1 + env: + - DEPS=latest + - php: 7.2 + env: + - DEPS=lowest + - php: 7.2 + env: + - DEPS=locked + - php: 7.2 + env: + - DEPS=latest + +before_install: + - if [[ $TEST_COVERAGE != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi + +install: + - travis_retry composer install $COMPOSER_ARGS + - if [[ $DEPS == 'latest' ]]; then travis_retry composer update $COMPOSER_ARGS ; fi + - if [[ $DEPS == 'lowest' ]]; then travis_retry composer update --prefer-lowest --prefer-stable $COMPOSER_ARGS ; fi + - if [[ $TEST_COVERAGE == 'true' ]]; then travis_retry composer require --dev $COMPOSER_ARGS $COVERAGE_DEPS ; fi + - stty cols 120 && composer show + +script: + - if [[ $TEST_COVERAGE == 'true' ]]; then composer test-coverage ; else composer test ; fi + - if [[ $CS_CHECK == 'true' ]]; then composer cs-check ; fi + +after_script: + - if [[ $TEST_COVERAGE == 'true' ]]; then travis_retry php vendor/bin/php-coveralls -v ; fi + +notifications: + email: false diff --git a/LICENSE.md b/LICENSE.md index badc26ea..67ba2104 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2016, Zend Technologies USA, Inc. +Copyright (c) 2016-2018, Zend Technologies USA, Inc. All rights reserved. diff --git a/README.md b/README.md index 4f0b2e13..c5aec180 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ -Zend Framework Coding Standard -============================== +# zend-coding-standard -Repository with all coding standard ruleset for Zend Framework repositories. +[![Build Status](https://secure.travis-ci.org/zendframework/zend-coding-standard.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-coding-standard) +The coding standard ruleset for Zend Framework components. -Installation ------------- +## Installation 1. Install the module via composer by running: @@ -27,7 +26,7 @@ Installation ```xml - + config @@ -39,9 +38,7 @@ Installation You can add or exclude some locations in that file. For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml - -Usage ------ +## Usage * To run checks only: diff --git a/composer.json b/composer.json index 1425db1e..052b3f43 100644 --- a/composer.json +++ b/composer.json @@ -2,11 +2,20 @@ "name": "zendframework/zend-coding-standard", "type": "phpcodesniffer-standard", "description": "Zend Framework Coding Standard", + "license": "BSD-3-Clause", "keywords": [ "zf", + "zendframework", "coding standard" ], - "license": "BSD-3-Clause", + "support": { + "docs": "https://docs.zendframework.com/zend-coding-standard/", + "issues": "https://github.com/zendframework/zend-coding-standard/issues", + "source": "https://github.com/zendframework/zend-coding-standard", + "rss": "https://github.com/zendframework/zend-coding-standard/releases.atom", + "chat": "https://zendframework-slack.herokuapp.com", + "forum": "https://discourse.zendframework.com/c/questions/components" + }, "require": { "php": "^7.1", "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", diff --git a/CONDUCT.md b/docs/CODE_OF_CONDUCT.md similarity index 96% rename from CONDUCT.md rename to docs/CODE_OF_CONDUCT.md index c663d2be..02fafcd1 100644 --- a/CONDUCT.md +++ b/docs/CODE_OF_CONDUCT.md @@ -1,6 +1,6 @@ # Contributor Code of Conduct -The Zend Framework project adheres to [The Code Manifesto](http://codemanifesto.com) +This project adheres to [The Code Manifesto](http://codemanifesto.com) as its guidelines for contributor interactions. ## The Code Manifesto diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 00000000..84009e8a --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,189 @@ +# CONTRIBUTING + +## RESOURCES + +If you wish to contribute to this project, please be sure to +read/subscribe to the following resources: + + - [Coding Standards](https://github.com/zendframework/zend-coding-standard) + - [Forums](https://discourse.zendframework.com/c/contributors) + - [Chat](https://zendframework-slack.herokuapp.com) + - [Code of Conduct](CODE_OF_CONDUCT.md) + +If you are working on new features or refactoring +[create a proposal](https://github.com/zendframework/zend-coding-standard/issues/new). + +## RUNNING TESTS + +To run tests: + +- Clone the repository: + + ```console + $ git clone git://github.com/zendframework/zend-coding-standard.git + $ cd zend-coding-standard + ``` + +- Install dependencies via composer: + + ```console + $ composer install + ``` + + If you don't have `composer` installed, please download it from https://getcomposer.org/download/ + +- Run the tests using the "test" command shipped in the `composer.json`: + + ```console + $ composer test + ``` + +You can turn on conditional tests with the `phpunit.xml` file. +To do so: + + - Copy `phpunit.xml.dist` file to `phpunit.xml` + - Edit `phpunit.xml` to enable any specific functionality you + want to test, as well as to provide test values to utilize. + +## Running Coding Standards Checks + +First, ensure you've installed dependencies via composer, per the previous +section on running tests. + +To run CS checks only: + +```console +$ composer cs-check +``` + +To attempt to automatically fix common CS issues: + +```console +$ composer cs-fix +``` + +If the above fixes any CS issues, please re-run the tests to ensure +they pass, and make sure you add and commit the changes after verification. + +## Recommended Workflow for Contributions + +Your first step is to establish a public repository from which we can +pull your work into the master repository. We recommend using +[GitHub](https://github.com), as that is where the component is already hosted. + +1. Setup a [GitHub account](https://github.com/), if you haven't yet +2. Fork the repository (https://github.com/zendframework/zend-coding-standard) +3. Clone the canonical repository locally and enter it. + + ```console + $ git clone git://github.com/zendframework/zend-coding-standard.git + $ cd zend-coding-standard + ``` + +4. Add a remote to your fork; substitute your GitHub username in the command + below. + + ```console + $ git remote add {username} git@github.com:{username}/zend-coding-standard.git + $ git fetch {username} + ``` + +### Keeping Up-to-Date + +Periodically, you should update your fork or personal repository to +match the canonical ZF repository. Assuming you have setup your local repository +per the instructions above, you can do the following: + + +```console +$ git checkout master +$ git fetch origin +$ git rebase origin/master +# OPTIONALLY, to keep your remote up-to-date - +$ git push {username} master:master +``` + +If you're tracking other branches -- for example, the "develop" branch, where +new feature development occurs -- you'll want to do the same operations for that +branch; simply substitute "develop" for "master". + +### Working on a patch + +We recommend you do each new feature or bugfix in a new branch. This simplifies +the task of code review as well as the task of merging your changes into the +canonical repository. + +A typical workflow will then consist of the following: + +1. Create a new local branch based off either your master or develop branch. +2. Switch to your new local branch. (This step can be combined with the + previous step with the use of `git checkout -b`.) +3. Do some work, commit, repeat as necessary. +4. Push the local branch to your remote repository. +5. Send a pull request. + +The mechanics of this process are actually quite trivial. Below, we will +create a branch for fixing an issue in the tracker. + +```console +$ git checkout -b hotfix/9295 +Switched to a new branch 'hotfix/9295' +``` + +... do some work ... + + +```console +$ git commit +``` + +... write your log message ... + + +```console +$ git push {username} hotfix/9295:hotfix/9295 +Counting objects: 38, done. +Delta compression using up to 2 threads. +Compression objects: 100% (18/18), done. +Writing objects: 100% (20/20), 8.19KiB, done. +Total 20 (delta 12), reused 0 (delta 0) +To ssh://git@github.com/{username}/zend-coding-standard.git + b5583aa..4f51698 HEAD -> master +``` + +To send a pull request, you have two options. + +If using GitHub, you can do the pull request from there. Navigate to +your repository, select the branch you just created, and then select the +"Pull Request" button in the upper right. Select the user/organization +"zendframework" (or whatever the upstream organization is) as the recipient. + +#### What branch to issue the pull request against? + +Which branch should you issue a pull request against? + +- For fixes against the stable release, issue the pull request against the + "master" branch. +- For new features, or fixes that introduce new elements to the public API (such + as new public methods or properties), issue the pull request against the + "develop" branch. + +### Branch Cleanup + +As you might imagine, if you are a frequent contributor, you'll start to +get a ton of branches both locally and on your remote. + +Once you know that your changes have been accepted to the master +repository, we suggest doing some cleanup of these branches. + +- Local branch cleanup + + ```console + $ git branch -d + ``` + +- Remote branch removal + + ```console + $ git push {username} : + ``` diff --git a/docs/ISSUE_TEMPLATE.md b/docs/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..03ff5a14 --- /dev/null +++ b/docs/ISSUE_TEMPLATE.md @@ -0,0 +1,19 @@ + - [ ] I was not able to find an [open](https://github.com/zendframework/zend-coding-standard/issues?q=is%3Aopen) or [closed](https://github.com/zendframework/zend-coding-standard/issues?q=is%3Aclosed) issue matching what I'm seeing. + - [ ] This is not a question. (Questions should be asked on [chat](https://zendframework.slack.com/) ([Signup here](https://zendframework-slack.herokuapp.com/)) or our [forums](https://discourse.zendframework.com/).) + +Provide a narrative description of what you are trying to accomplish. + +### Code to reproduce the issue + + + +```php +``` + +### Expected results + + + +### Actual results + + diff --git a/docs/PULL_REQUEST_TEMPLATE.md b/docs/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..f00d90c0 --- /dev/null +++ b/docs/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,25 @@ +Provide a narrative description of what you are trying to accomplish: + +- [ ] Are you fixing a bug? + - [ ] Detail how the bug is invoked currently. + - [ ] Detail the original, incorrect behavior. + - [ ] Detail the new, expected behavior. + - [ ] Base your feature on the `master` branch, and submit against that branch. + - [ ] Add a regression test that demonstrates the bug, and proves the fix. + - [ ] Add a `CHANGELOG.md` entry for the fix. + +- [ ] Are you creating a new feature? + - [ ] Why is the new feature needed? What purpose does it serve? + - [ ] How will users use the new feature? + - [ ] Base your feature on the `develop` branch, and submit against that branch. + - [ ] Add only one feature per pull request; split multiple features over multiple pull requests + - [ ] Add tests for the new feature. + - [ ] Add documentation for the new feature. + - [ ] Add a `CHANGELOG.md` entry for the new feature. + +- [ ] Is this related to quality assurance? + + +- [ ] Is this related to documentation? + + diff --git a/docs/SUPPORT.md b/docs/SUPPORT.md new file mode 100644 index 00000000..369891d2 --- /dev/null +++ b/docs/SUPPORT.md @@ -0,0 +1,25 @@ +# Getting Support + +Zend Framework offers three support channels: + +- For real-time questions, use our + [chat](https://zendframework-slack.herokuapp.com) +- For detailed questions (e.g., those requiring examples) use our + [forums](https://discourse.zendframework.com/c/questions/components) +- To report issues, use this repository's + [issue tracker](https://github.com/zendframework/zend-coding-standard/issues/new) + +**DO NOT** use the issue tracker to ask questions; use chat or the forums for +that. Questions posed to the issue tracker will be closed. + +When reporting an issue, please include the following details: + +- A narrative description of what you are trying to accomplish. +- The minimum code necessary to reproduce the issue. +- The expected results of exercising that code. +- The actual results received. + +We may ask for additional details: what version of the library you are using, +and what PHP version was used to reproduce the issue. + +You may also submit a failing test case as a pull request. diff --git a/docs/book/index.html b/docs/book/index.html new file mode 100644 index 00000000..ac90049e --- /dev/null +++ b/docs/book/index.html @@ -0,0 +1,9 @@ +
+
+

zend-coding-standard

+ +

The coding standard ruleset for Zend Framework components.

+ +
$ composer require zendframework/zend-coding-standard
+
+
diff --git a/docs/book/index.md b/docs/book/index.md new file mode 100644 index 00000000..fe840054 --- /dev/null +++ b/docs/book/index.md @@ -0,0 +1 @@ +../../README.md \ No newline at end of file diff --git a/docs/book/v1/index.md b/docs/book/v1/index.md new file mode 100644 index 00000000..97635fa6 --- /dev/null +++ b/docs/book/v1/index.md @@ -0,0 +1 @@ +# The coding standard ruleset for Zend Framework components diff --git a/docs/book/v1/intro.md b/docs/book/v1/intro.md new file mode 100644 index 00000000..4a512141 --- /dev/null +++ b/docs/book/v1/intro.md @@ -0,0 +1,51 @@ +# zend-coding-standard + +This component provides the coding standard ruleset for Zend Framework components. + +## Installation + +1. Install the module via composer by running: + + ```bash + $ composer require --dev zendframework/zend-coding-standard + ``` + +2. Add composer scripts into your `composer.json`: + + ```json + "scripts": { + "cs-check": "phpcs", + "cs-fix": "phpcbf" + } + ``` + +3. Create file `phpcs.xml` on base path of your repository with content: + + ```xml + + + + + + config + src + test + + ``` + +You can add or exclude some locations in that file. +For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml + +## Usage + +* To run checks only: + + ```bash + $ composer cs-check + ``` + +* To automatically fix many CS issues: + + ```bash + $ composer cs-fix + ``` diff --git a/docs/book/v1/ruleset.md b/docs/book/v1/ruleset.md new file mode 100644 index 00000000..a012f055 --- /dev/null +++ b/docs/book/v1/ruleset.md @@ -0,0 +1,7 @@ +# Ruleset + +- PSR-2 +- Disallow long array syntax +- Space after not operator +- Whitespace around operators +- Disallow superfluous whitespace diff --git a/docs/book/v2/index.md b/docs/book/v2/index.md new file mode 100644 index 00000000..97635fa6 --- /dev/null +++ b/docs/book/v2/index.md @@ -0,0 +1 @@ +# The coding standard ruleset for Zend Framework components diff --git a/docs/book/v2/intro.md b/docs/book/v2/intro.md new file mode 100644 index 00000000..f1f860fe --- /dev/null +++ b/docs/book/v2/intro.md @@ -0,0 +1,51 @@ +# zend-coding-standard + +This component provides the coding standard ruleset for Zend Framework components. + +## Installation + +1. Install the module via composer by running: + + ```bash + $ composer require --dev zendframework/zend-coding-standard + ``` + +2. Add composer scripts into your `composer.json`: + + ```json + "scripts": { + "cs-check": "phpcs", + "cs-fix": "phpcbf" + } + ``` + +3. Create file `phpcs.xml` on base path of your repository with content: + + ```xml + + + + + + config + src + test + + ``` + +You can add or exclude some locations in that file. +For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml + +## Usage + +* To run checks only: + + ```bash + $ composer cs-check + ``` + +* To automatically fix many CS issues: + + ```bash + $ composer cs-fix + ``` diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md new file mode 100644 index 00000000..cadc5dd6 --- /dev/null +++ b/docs/book/v2/ruleset.md @@ -0,0 +1,12 @@ +# Ruleset + +- PSR-2 +- Disallow long array syntax +- Space after not operator +- Whitespace around operators +- Disallow superfluous whitespace +- +- +- TODO +- +- diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 00000000..1121fa69 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,17 @@ +docs_dir: docs/book +site_dir: docs/html +pages: + - index.md + - 'Introduction': v2/intro.md + - Reference: + - 'Ruleset': v2/ruleset.md + - v1: + - v1/index.md + - 'Introduction': v1/intro.md + - Reference: + - 'Ruleset': v1/ruleset.md + +site_name: Zend Coding Standard +site_description: 'The coding standard ruleset for Zend Framework components.' +repo_url: 'https://github.com/zendframework/zend-coding-standard' +copyright: 'Copyright (c) 2016-2018 Zend Technologies USA Inc.' From 911065a40ad17a98eed229a7dd4d8a85efeb444f Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 22:28:07 +0200 Subject: [PATCH 08/60] Use xmllint to validate against schema --- .travis.yml | 66 +++++++++++++++++++---------------------------------- 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1aeaccab..ba5bda84 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,55 +1,37 @@ +dist: trusty sudo: false - language: php +php: +- 7.1 +- 7.2 +- nightly + cache: directories: - - $HOME/.composer/cache - -env: - global: - - COMPOSER_ARGS="--no-interaction" - - COVERAGE_DEPS="php-coveralls/php-coveralls" - -matrix: - include: - - php: 7.1 - env: - - DEPS=lowest - - php: 7.1 - env: - - DEPS=locked - - CS_CHECK=true - - TEST_COVERAGE=true - - php: 7.1 - env: - - DEPS=latest - - php: 7.2 - env: - - DEPS=lowest - - php: 7.2 - env: - - DEPS=locked - - php: 7.2 - env: - - DEPS=latest + - $HOME/.composer/cache before_install: - - if [[ $TEST_COVERAGE != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi +- phpenv config-rm xdebug.ini +- composer self-update + +install: travis_retry composer update --prefer-dist -install: - - travis_retry composer install $COMPOSER_ARGS - - if [[ $DEPS == 'latest' ]]; then travis_retry composer update $COMPOSER_ARGS ; fi - - if [[ $DEPS == 'lowest' ]]; then travis_retry composer update --prefer-lowest --prefer-stable $COMPOSER_ARGS ; fi - - if [[ $TEST_COVERAGE == 'true' ]]; then travis_retry composer require --dev $COMPOSER_ARGS $COVERAGE_DEPS ; fi - - stty cols 120 && composer show +stages: +- Validate against schema +- Test -script: - - if [[ $TEST_COVERAGE == 'true' ]]; then composer test-coverage ; else composer test ; fi - - if [[ $CS_CHECK == 'true' ]]; then composer cs-check ; fi +jobs: + allow_failures: + - php: nightly -after_script: - - if [[ $TEST_COVERAGE == 'true' ]]; then travis_retry php vendor/bin/php-coveralls -v ; fi + include: + - stage: Validate against schema + addons: + apt: + packages: + - libxml2-utils + script: xmllint --noout --schema vendor/squizlabs/php_codesniffer/phpcs.xsd src/ZendCodingStandard/ruleset.xml notifications: email: false From 365acdfdc42e2bc43220258fd5110424d185208a Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 22:33:49 +0200 Subject: [PATCH 09/60] Remove copyright in mkdocs config as it's not being used anymore --- mkdocs.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/mkdocs.yml b/mkdocs.yml index 1121fa69..2a3dffe7 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -14,4 +14,3 @@ pages: site_name: Zend Coding Standard site_description: 'The coding standard ruleset for Zend Framework components.' repo_url: 'https://github.com/zendframework/zend-coding-standard' -copyright: 'Copyright (c) 2016-2018 Zend Technologies USA Inc.' From b3146a6cc285013107ccceec83eea0420bd6c2d4 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 22:34:50 +0200 Subject: [PATCH 10/60] Remove index.html because it's generated by the theme --- docs/book/index.html | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 docs/book/index.html diff --git a/docs/book/index.html b/docs/book/index.html deleted file mode 100644 index ac90049e..00000000 --- a/docs/book/index.html +++ /dev/null @@ -1,9 +0,0 @@ -
-
-

zend-coding-standard

- -

The coding standard ruleset for Zend Framework components.

- -
$ composer require zendframework/zend-coding-standard
-
-
From 5c86655d6828803f2dff7d561b922ae282dac15a Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 5 Sep 2018 22:36:08 +0200 Subject: [PATCH 11/60] Disable phpunit tests until there is something to test --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ba5bda84..89443ac2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,7 +19,6 @@ install: travis_retry composer update --prefer-dist stages: - Validate against schema -- Test jobs: allow_failures: From ce7ae4af253be95899923f3e55a5bac61ae765e5 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 10:49:21 +0200 Subject: [PATCH 12/60] Use PSR-12 compatible imports --- src/ZendCodingStandard/ruleset.xml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 8c769ab1..abe8a7d5 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -82,7 +82,6 @@ - @@ -90,6 +89,7 @@ + @@ -170,7 +170,11 @@ - + + + + + @@ -206,7 +210,7 @@ - + From 3f602fa1573118579454a8a314689a0ef4240963 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 10:51:48 +0200 Subject: [PATCH 13/60] Add rules to documentation This is a very long list with a lot of useless info. Maybe a PHP-FIG PSR-2 style guide is better. --- docs/book/v1/ruleset.md | 19 ++- docs/book/v2/ruleset.md | 363 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 367 insertions(+), 15 deletions(-) diff --git a/docs/book/v1/ruleset.md b/docs/book/v1/ruleset.md index a012f055..0e39c371 100644 --- a/docs/book/v1/ruleset.md +++ b/docs/book/v1/ruleset.md @@ -1,7 +1,16 @@ # Ruleset -- PSR-2 -- Disallow long array syntax -- Space after not operator -- Whitespace around operators -- Disallow superfluous whitespace +## Use PSR-2 coding standard as a base +*PSR2* + +## Disallow long array syntax +*Generic.Arrays.DisallowLongArraySyntax* + +## Force whitespace after `!` +*Generic.Formatting.SpaceAfterNot* + +## Forbid spaces before semicolon `;` +*Squiz.WhiteSpace.SemicolonSpacing* + +## Forbid superfluous whitespaces +*Squiz.WhiteSpace.SuperfluousWhitespace, Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines* diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index cadc5dd6..e6a521d9 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -1,12 +1,355 @@ # Ruleset -- PSR-2 -- Disallow long array syntax -- Space after not operator -- Whitespace around operators -- Disallow superfluous whitespace -- -- -- TODO -- -- +## Use PSR-2 coding standard as a base +*PSR2* + +## Force array element indentation with 4 spaces +*Generic.Arrays.ArrayIndent* + +## Forbid `array(...)` +*Generic.Arrays.DisallowLongArraySyntax* + +## Forbid backtick operator +*Generic.PHP.BacktickOperator* + +## Forbid duplicate classes +*Generic.Classes.DuplicateClassName* + +## Forbid empty statements, but allow empty catch +*Generic.CodeAnalysis.EmptyStatement, Generic.CodeAnalysis.EmptyStatement.DetectedCatch* + +## Forbid final methods in final classes +*Generic.CodeAnalysis.UnnecessaryFinalModifier* + +## Forbid useless empty method overrides +*Generic.CodeAnalysis.UselessOverridingMethod* + +## Forbid short open tag, but allow short echo tags +*Generic.PHP.DisallowShortOpenTag* + +## Forbid inline HTML in PHP code +*Generic.Files.InlineHTML* + +## Align corresponding assignment statement tokens +*Generic.Formatting.MultipleStatementAlignment* + +## Force whitespace after a type cast +*Generic.Formatting.SpaceAfterCast* + +## Force whitespace after `!` +*Generic.Formatting.SpaceAfterNot* + +## Forbid PHP 4 constructors +*Generic.NamingConventions.ConstructorName* + +## Forbid any content before opening tag +*Generic.PHP.CharacterBeforePHPOpeningTag* + +## Forbid deprecated functions +*Generic.PHP.DeprecatedFunctions* + +## Forbid alias functions, i.e. `sizeof()`, `delete()` +*Generic.PHP.ForbiddenFunctions* + + ` operator +*Squiz.WhiteSpace.ObjectOperatorSpacing* + +## Forbid spaces before semicolon `;` +*Squiz.WhiteSpace.SemicolonSpacing* + +## Forbid superfluous whitespaces +*Squiz.WhiteSpace.SuperfluousWhitespace, Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines* From 39ba67a81de9f7bd3d5be59d0f9ecc3b2a61ad5e Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 13:33:27 +0200 Subject: [PATCH 14/60] Add some test cases --- .travis.yml | 27 +++++----- composer.json | 7 ++- docs/book/v2/ruleset.md | 2 +- phpcs.xml.dist | 16 ++++++ test/ArraysAndIndentation.php | 40 ++++++++++++++ test/Assets/AbstractFoo.php | 9 ++++ test/Assets/Foo.php | 17 ++++++ test/Assets/FooInterface.php | 12 +++++ test/ClassReferences.php | 28 ++++++++++ test/ExampleClass.php | 92 +++++++++++++++++++++++++++++++++ test/LowCaseTypes.php | 18 +++++++ test/PropertiesAndConstants.php | 27 ++++++++++ 12 files changed, 281 insertions(+), 14 deletions(-) create mode 100644 phpcs.xml.dist create mode 100644 test/ArraysAndIndentation.php create mode 100644 test/Assets/AbstractFoo.php create mode 100644 test/Assets/Foo.php create mode 100644 test/Assets/FooInterface.php create mode 100644 test/ClassReferences.php create mode 100644 test/ExampleClass.php create mode 100644 test/LowCaseTypes.php create mode 100644 test/PropertiesAndConstants.php diff --git a/.travis.yml b/.travis.yml index 89443ac2..c1ec680a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,3 @@ -dist: trusty sudo: false language: php @@ -9,28 +8,32 @@ php: cache: directories: - - $HOME/.composer/cache + - $HOME/.composer/cache before_install: -- phpenv config-rm xdebug.ini -- composer self-update + - phpenv config-rm xdebug.ini + - composer self-update install: travis_retry composer update --prefer-dist +script: + - vendor/bin/phpcs + stages: -- Validate against schema + - Validate against schema + - Test jobs: allow_failures: - - php: nightly + - php: nightly include: - - stage: Validate against schema - addons: - apt: - packages: - - libxml2-utils - script: xmllint --noout --schema vendor/squizlabs/php_codesniffer/phpcs.xsd src/ZendCodingStandard/ruleset.xml + - stage: Validate against schema + addons: + apt: + packages: + - libxml2-utils + script: xmllint --noout --schema vendor/squizlabs/php_codesniffer/phpcs.xsd src/ZendCodingStandard/ruleset.xml notifications: email: false diff --git a/composer.json b/composer.json index 052b3f43..97c8564d 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,12 @@ }, "autoload": { "psr-4": { - "ZendCodingStandard\\Sniffs\\": "src/ZendCodingStandard/Sniffs" + "ZendCodingStandard\\": "src/ZendCodingStandard" + } + }, + "autoload-dev": { + "psr-4": { + "ZendCodingStandardTest\\": "test/" } } } diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index e6a521d9..8f8c1289 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -50,6 +50,7 @@ ## Forbid alias functions, i.e. `sizeof()`, `delete()` *Generic.PHP.ForbiddenFunctions* + strstr * - ## Force PHP 7 param and return types to be lowercased *Generic.PHP.LowerCaseType* diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 00000000..8383b224 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,16 @@ + + + The coding standard for ZendCodingStandard itself. + + + + + + + + + src + test + diff --git a/test/ArraysAndIndentation.php b/test/ArraysAndIndentation.php new file mode 100644 index 00000000..747353db --- /dev/null +++ b/test/ArraysAndIndentation.php @@ -0,0 +1,40 @@ + 2]; + } + + public function multiArray() : array + { + return [ + '0' => [ + '2' => 2, + 1 => '1', + ], + 4 => [ + 7, + 8, + 9, + ], + ]; + } +} diff --git a/test/Assets/AbstractFoo.php b/test/Assets/AbstractFoo.php new file mode 100644 index 00000000..8cd6fd0f --- /dev/null +++ b/test/Assets/AbstractFoo.php @@ -0,0 +1,9 @@ +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('Error message'); + } + $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/LowCaseTypes.php b/test/LowCaseTypes.php new file mode 100644 index 00000000..3f6478fe --- /dev/null +++ b/test/LowCaseTypes.php @@ -0,0 +1,18 @@ +baz = $baz; + } + + public function bar() : bool + { + return $this->baz; + } +} From e9d9a2d696652e3f63e1606230aa3a73501709ed Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 14:12:42 +0200 Subject: [PATCH 15/60] Update docs for alias functions --- docs/book/v2/ruleset.md | 52 +++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 8f8c1289..32558058 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -51,34 +51,30 @@ ## Forbid alias functions, i.e. `sizeof()`, `delete()` *Generic.PHP.ForbiddenFunctions* - - - + From a0630513a28778db4580c24eca2ac10a864809f0 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 18:00:41 +0200 Subject: [PATCH 18/60] Add useful tests --- .gitignore | 2 + .travis.yml | 6 ++ composer.json | 10 +++ phpcs.xml.dist | 1 - test/ArraysAndIndentation.php | 40 ----------- test/Assets/AbstractFoo.php | 9 --- test/Assets/Foo.php | 17 ----- test/Assets/FooInterface.php | 12 ---- test/ClassReferences.php | 28 -------- test/fixable/EarlyReturn.php | 52 ++++++++++++++ test/fixable/LowCaseTypes.php | 18 +++++ test/fixable/UnusedVariables.php | 17 +++++ test/fixable/array_indentation.php | 28 ++++++++ test/fixable/assignment-operators.php | 11 +++ test/fixable/concatenation_spacing.php | 37 ++++++++++ test/fixable/example-class.php | 84 ++++++++++++++++++++++ test/fixable/forbidden-comments.php | 34 +++++++++ test/fixable/forbidden-functions.php | 30 ++++++++ test/fixable/namespaces-spacing.php | 18 +++++ test/fixable/new_with_parentheses.php | 28 ++++++++ test/fixable/not_spacing.php | 21 ++++++ test/fixable/null_coalesce_operator.php | 19 +++++ test/fixable/return_type_on_closures.php | 68 ++++++++++++++++++ test/fixable/return_type_on_methods.php | 73 +++++++++++++++++++ test/fixable/semicolon_spacing.php | 13 ++++ test/fixable/test-case.php | 41 +++++++++++ test/fixable/traits-uses.php | 25 +++++++ test/fixable/useless-semicolon.php | 15 ++++ test/fixed/EarlyReturn.php | 52 ++++++++++++++ test/{ => fixed}/LowCaseTypes.php | 2 +- test/fixed/UnusedVariables.php | 17 +++++ test/fixed/array_indentation.php | 26 +++++++ test/fixed/assignment-operators.php | 11 +++ test/fixed/concatenation_spacing.php | 37 ++++++++++ test/fixed/example-class.php | 89 ++++++++++++++++++++++++ test/fixed/forbidden-comments.php | 26 +++++++ test/fixed/forbidden-functions.php | 30 ++++++++ test/fixed/namespaces-spacing.php | 20 ++++++ test/fixed/new_with_parentheses.php | 28 ++++++++ test/fixed/not_spacing.php | 21 ++++++ test/fixed/null_coalesce_operator.php | 19 +++++ test/fixed/return_type_on_closures.php | 63 +++++++++++++++++ test/fixed/return_type_on_methods.php | 73 +++++++++++++++++++ test/fixed/semicolon_spacing.php | 11 +++ test/fixed/test-case.php | 39 +++++++++++ test/fixed/traits-uses.php | 24 +++++++ test/fixed/useless-semicolon.php | 15 ++++ 47 files changed, 1252 insertions(+), 108 deletions(-) delete mode 100644 test/ArraysAndIndentation.php delete mode 100644 test/Assets/AbstractFoo.php delete mode 100644 test/Assets/Foo.php delete mode 100644 test/Assets/FooInterface.php delete mode 100644 test/ClassReferences.php create mode 100644 test/fixable/EarlyReturn.php create mode 100644 test/fixable/LowCaseTypes.php create mode 100644 test/fixable/UnusedVariables.php create mode 100644 test/fixable/array_indentation.php create mode 100644 test/fixable/assignment-operators.php create mode 100644 test/fixable/concatenation_spacing.php create mode 100644 test/fixable/example-class.php create mode 100644 test/fixable/forbidden-comments.php create mode 100644 test/fixable/forbidden-functions.php create mode 100644 test/fixable/namespaces-spacing.php create mode 100644 test/fixable/new_with_parentheses.php create mode 100644 test/fixable/not_spacing.php create mode 100644 test/fixable/null_coalesce_operator.php create mode 100644 test/fixable/return_type_on_closures.php create mode 100644 test/fixable/return_type_on_methods.php create mode 100644 test/fixable/semicolon_spacing.php create mode 100644 test/fixable/test-case.php create mode 100644 test/fixable/traits-uses.php create mode 100644 test/fixable/useless-semicolon.php create mode 100644 test/fixed/EarlyReturn.php rename test/{ => fixed}/LowCaseTypes.php (87%) create mode 100644 test/fixed/UnusedVariables.php create mode 100644 test/fixed/array_indentation.php create mode 100644 test/fixed/assignment-operators.php create mode 100644 test/fixed/concatenation_spacing.php create mode 100644 test/fixed/example-class.php create mode 100644 test/fixed/forbidden-comments.php create mode 100644 test/fixed/forbidden-functions.php create mode 100644 test/fixed/namespaces-spacing.php create mode 100644 test/fixed/new_with_parentheses.php create mode 100644 test/fixed/not_spacing.php create mode 100644 test/fixed/null_coalesce_operator.php create mode 100644 test/fixed/return_type_on_closures.php create mode 100644 test/fixed/return_type_on_methods.php create mode 100644 test/fixed/semicolon_spacing.php create mode 100644 test/fixed/test-case.php create mode 100644 test/fixed/traits-uses.php create mode 100644 test/fixed/useless-semicolon.php diff --git a/.gitignore b/.gitignore index b185393a..b01fd1d7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,9 +2,11 @@ /composer.lock /coveralls-upload.json /docs/html/ +/mkdocs.site.yml /phpcs.log /phpcs.xml /phpunit.xml +/test/fix/ /vendor/ /zf-mkdoc-theme.tgz /zf-mkdoc-theme/ diff --git a/.travis.yml b/.travis.yml index c1ec680a..42478748 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,7 @@ script: stages: - Validate against schema - Test + - Validate fixes jobs: allow_failures: @@ -35,5 +36,10 @@ jobs: - libxml2-utils script: xmllint --noout --schema vendor/squizlabs/php_codesniffer/phpcs.xsd src/ZendCodingStandard/ruleset.xml + - stage: Validate fixes + before_script: + - cp -R test/fixable/ tests/fix/ + script: vendor/bin/phpcbf test/fix; diff test/fix test/fixed + notifications: email: false diff --git a/composer.json b/composer.json index 97c8564d..df843c0d 100644 --- a/composer.json +++ b/composer.json @@ -36,5 +36,15 @@ "psr-4": { "ZendCodingStandardTest\\": "test/" } + }, + "scripts": { + "check": [ + "@test-prepare", + "@test-fix", + "@test-diff" + ], + "test-prepare": "rm -rf test/fix/; cp -R test/fixable/ test/fix/;", + "test-fix": "phpcbf test/fix > /dev/null || true", + "test-diff": "diff test/fix test/fixed" } } diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 8383b224..818edf17 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -12,5 +12,4 @@ src - test
diff --git a/test/ArraysAndIndentation.php b/test/ArraysAndIndentation.php deleted file mode 100644 index 747353db..00000000 --- a/test/ArraysAndIndentation.php +++ /dev/null @@ -1,40 +0,0 @@ - 2]; - } - - public function multiArray() : array - { - return [ - '0' => [ - '2' => 2, - 1 => '1', - ], - 4 => [ - 7, - 8, - 9, - ], - ]; - } -} diff --git a/test/Assets/AbstractFoo.php b/test/Assets/AbstractFoo.php deleted file mode 100644 index 8cd6fd0f..00000000 --- a/test/Assets/AbstractFoo.php +++ /dev/null @@ -1,9 +0,0 @@ -isItem())) { + return 'There is an item that is not an item'; + } else { + continue; + } + } + + return null; + } + + public function baz() : string + { + if ($number > 0) { + return 'Number is grater then 0'; + } else { + exit; + } + } + + public function quoox() : bool + { + if (true === 'true') { + if (false === false) { + return true; + } + } else { + return false; + } + + return true; + } +} diff --git a/test/fixable/LowCaseTypes.php b/test/fixable/LowCaseTypes.php new file mode 100644 index 00000000..41f8803b --- /dev/null +++ b/test/fixable/LowCaseTypes.php @@ -0,0 +1,18 @@ + [ + '2' => 2, + 1 => '1', +], + 4 => [ + 7, + 8, + 9, + ], +]; + +$singleLine = [ + 1 => 2, +]; diff --git a/test/fixable/assignment-operators.php b/test/fixable/assignment-operators.php new file mode 100644 index 00000000..2136da78 --- /dev/null +++ b/test/fixable/assignment-operators.php @@ -0,0 +1,11 @@ +foo = $foo; + $this->bar = $bar; + $this->baz = $baz; + $this->baxBax = $baxBax; + } + + /** + * Description + * @return int|null + */ + 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/forbidden-comments.php b/test/fixable/forbidden-comments.php new file mode 100644 index 00000000..24112344 --- /dev/null +++ b/test/fixable/forbidden-comments.php @@ -0,0 +1,34 @@ + 1, + 'bar' => 2, + 'baz' => 3, +]; +extract($bar); + +compact('foo', 'bar'); diff --git a/test/fixable/namespaces-spacing.php b/test/fixable/namespaces-spacing.php new file mode 100644 index 00000000..430900ad --- /dev/null +++ b/test/fixable/namespaces-spacing.php @@ -0,0 +1,18 @@ +sub(new DateInterval('P1D')) + ->format(DATE_RFC3339) +); diff --git a/test/fixable/new_with_parentheses.php b/test/fixable/new_with_parentheses.php new file mode 100644 index 00000000..56ee8ea9 --- /dev/null +++ b/test/fixable/new_with_parentheses.php @@ -0,0 +1,28 @@ +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; diff --git a/test/fixable/not_spacing.php b/test/fixable/not_spacing.php new file mode 100644 index 00000000..78003e8f --- /dev/null +++ b/test/fixable/not_spacing.php @@ -0,0 +1,21 @@ + 0) { + echo 1; +} elseif ( !$test === 0) { + echo 0; +} else { + echo -1; +} + +while ( ! true) { + echo 1; +} + +do { + echo 1; +} while ( ! true); diff --git a/test/fixable/null_coalesce_operator.php b/test/fixable/null_coalesce_operator.php new file mode 100644 index 00000000..823b01c5 --- /dev/null +++ b/test/fixable/null_coalesce_operator.php @@ -0,0 +1,19 @@ +select() + ->from() + ->where() +; diff --git a/test/fixable/test-case.php b/test/fixable/test-case.php new file mode 100644 index 00000000..7f6521b4 --- /dev/null +++ b/test/fixable/test-case.php @@ -0,0 +1,41 @@ +isItem()) { + return 'There is an item that is not an item'; + } + + continue; + } + + return null; + } + + public function baz() : string + { + if ($number > 0) { + return 'Number is grater then 0'; + } + + exit; + } + + public function quoox() : bool + { + if (true !== 'true') { + return false; + } + + if (false === false) { + return true; + } + + return true; + } +} diff --git a/test/LowCaseTypes.php b/test/fixed/LowCaseTypes.php similarity index 87% rename from test/LowCaseTypes.php rename to test/fixed/LowCaseTypes.php index 3f6478fe..4782ba1c 100644 --- a/test/LowCaseTypes.php +++ b/test/fixed/LowCaseTypes.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace ZendCodingStandardTest; +namespace Types; class LowCaseTypes { diff --git a/test/fixed/UnusedVariables.php b/test/fixed/UnusedVariables.php new file mode 100644 index 00000000..67e8500e --- /dev/null +++ b/test/fixed/UnusedVariables.php @@ -0,0 +1,17 @@ + [ + '2' => 2, + 1 => '1', + ], + 4 => [ + 7, + 8, + 9, + ], +]; + +$singleLine = [1 => 2]; diff --git a/test/fixed/assignment-operators.php b/test/fixed/assignment-operators.php new file mode 100644 index 00000000..3a85cf89 --- /dev/null +++ b/test/fixed/assignment-operators.php @@ -0,0 +1,11 @@ +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/forbidden-comments.php b/test/fixed/forbidden-comments.php new file mode 100644 index 00000000..67029f24 --- /dev/null +++ b/test/fixed/forbidden-comments.php @@ -0,0 +1,26 @@ + 1, + 'bar' => 2, + 'baz' => 3, +]; +extract($bar); + +compact('foo', 'bar'); diff --git a/test/fixed/namespaces-spacing.php b/test/fixed/namespaces-spacing.php new file mode 100644 index 00000000..d42bbfef --- /dev/null +++ b/test/fixed/namespaces-spacing.php @@ -0,0 +1,20 @@ +sub(new DateInterval('P1D')) + ->format(DATE_RFC3339) +); diff --git a/test/fixed/new_with_parentheses.php b/test/fixed/new_with_parentheses.php new file mode 100644 index 00000000..6e81bbe6 --- /dev/null +++ b/test/fixed/new_with_parentheses.php @@ -0,0 +1,28 @@ +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(); diff --git a/test/fixed/not_spacing.php b/test/fixed/not_spacing.php new file mode 100644 index 00000000..0284b52a --- /dev/null +++ b/test/fixed/not_spacing.php @@ -0,0 +1,21 @@ + 0) { + echo 1; +} elseif (! $test === 0) { + echo 0; +} else { + echo -1; +} + +while (! true) { + echo 1; +} + +do { + echo 1; +} while (! true); diff --git a/test/fixed/null_coalesce_operator.php b/test/fixed/null_coalesce_operator.php new file mode 100644 index 00000000..8846dd12 --- /dev/null +++ b/test/fixed/null_coalesce_operator.php @@ -0,0 +1,19 @@ +select() + ->from() + ->where(); diff --git a/test/fixed/test-case.php b/test/fixed/test-case.php new file mode 100644 index 00000000..9158171e --- /dev/null +++ b/test/fixed/test-case.php @@ -0,0 +1,39 @@ + Date: Thu, 6 Sep 2018 18:06:22 +0200 Subject: [PATCH 19/60] Fix typo in ci script --- .travis.yml | 2 +- test/ExampleClass.php | 92 --------------------------------- test/PropertiesAndConstants.php | 27 ---------- 3 files changed, 1 insertion(+), 120 deletions(-) delete mode 100644 test/ExampleClass.php delete mode 100644 test/PropertiesAndConstants.php diff --git a/.travis.yml b/.travis.yml index 42478748..feca5882 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ jobs: - stage: Validate fixes before_script: - - cp -R test/fixable/ tests/fix/ + - cp -R test/fixable/ test/fix/ script: vendor/bin/phpcbf test/fix; diff test/fix test/fixed notifications: diff --git a/test/ExampleClass.php b/test/ExampleClass.php deleted file mode 100644 index b106e501..00000000 --- a/test/ExampleClass.php +++ /dev/null @@ -1,92 +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('Error message'); - } - $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/PropertiesAndConstants.php b/test/PropertiesAndConstants.php deleted file mode 100644 index c158eb8d..00000000 --- a/test/PropertiesAndConstants.php +++ /dev/null @@ -1,27 +0,0 @@ -baz = $baz; - } - - public function bar() : bool - { - return $this->baz; - } -} From d35d34ed202720e73e8355f49ba6043f5de594d6 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 18:12:12 +0200 Subject: [PATCH 20/60] Don't remove xdebug as php nightly doesn't have it --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index feca5882..718410dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,6 @@ cache: - $HOME/.composer/cache before_install: - - phpenv config-rm xdebug.ini - composer self-update install: travis_retry composer update --prefer-dist From b4d915d785653ed7ad5a90893ec1465b05034bee Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 18:27:30 +0200 Subject: [PATCH 21/60] Test expected violations for fixable code --- .travis.yml | 1 + composer.json | 1 + test/expected-report.txt | 31 +++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 test/expected-report.txt diff --git a/.travis.yml b/.travis.yml index 718410dd..95d5cb2c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,6 +17,7 @@ install: travis_retry composer update --prefer-dist script: - vendor/bin/phpcs + - vendor/bin/phpcs $(find test/fixable/* | sort) --report=summary --report-file=phpcs.log; diff test/expected-report.txt phpcs.log stages: - Validate against schema diff --git a/composer.json b/composer.json index df843c0d..da23c181 100644 --- a/composer.json +++ b/composer.json @@ -43,6 +43,7 @@ "@test-fix", "@test-diff" ], + "create-report": "phpcs $(find test/fixable/* | sort) --report=summary --report-file=test/expected-report.txt", "test-prepare": "rm -rf test/fix/; cp -R test/fixable/ test/fix/;", "test-fix": "phpcbf test/fix > /dev/null || true", "test-diff": "diff test/fix test/fixed" diff --git a/test/expected-report.txt b/test/expected-report.txt new file mode 100644 index 00000000..48e5b54e --- /dev/null +++ b/test/expected-report.txt @@ -0,0 +1,31 @@ + +PHP CODE SNIFFER REPORT SUMMARY +---------------------------------------------------------------------- +FILE ERRORS WARNINGS +---------------------------------------------------------------------- +test/fixable/array_indentation.php 11 0 +test/fixable/assignment-operators.php 4 0 +test/fixable/concatenation_spacing.php 24 0 +test/fixable/EarlyReturn.php 5 0 +test/fixable/example-class.php 21 0 +test/fixable/forbidden-comments.php 4 0 +test/fixable/forbidden-functions.php 6 0 +test/fixable/LowCaseTypes.php 2 0 +test/fixable/namespaces-spacing.php 3 0 +test/fixable/new_with_parentheses.php 18 0 +test/fixable/not_spacing.php 7 0 +test/fixable/null_coalesce_operator.php 3 0 +test/fixable/return_type_on_closures.php 21 0 +test/fixable/return_type_on_methods.php 17 0 +test/fixable/semicolon_spacing.php 3 0 +test/fixable/test-case.php 4 0 +test/fixable/traits-uses.php 10 0 +test/fixable/UnusedVariables.php 1 0 +test/fixable/useless-semicolon.php 2 0 +---------------------------------------------------------------------- +A TOTAL OF 166 ERRORS AND 0 WARNINGS WERE FOUND IN 19 FILES +---------------------------------------------------------------------- +PHPCBF CAN FIX 148 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +---------------------------------------------------------------------- + + From 45d14bd6650a700874726b300ea91ba9a3621300 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 22:24:40 +0200 Subject: [PATCH 22/60] Require ? when default value is null --- docs/book/v2/ruleset.md | 14 ++++++++++++++ src/ZendCodingStandard/ruleset.xml | 2 ++ test/expected-report.txt | 6 +++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 32558058..a8834065 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -215,6 +215,20 @@ Use `$foo = $bar['id'] ?? '1';` where possbile. ## Require use of short versions of scalar types (i.e. int instead of integer) *SlevomatCodingStandard.TypeHints.LongTypeHints* +## Require ? when default value is null +*SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue* + +Checks whether the nullablity ? symbol is present before each nullable and optional parameter +(which are marked as = null): +```php +function foo( + int $foo = null, // ? missing + ?int $bar = null // correct +) { + +} +``` + ## Require one space between typehint and variable, require no space between nullability sign and typehint *SlevomatCodingStandard.TypeHints.ParameterTypeHintSpacing* diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 6212138b..df25a730 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -244,6 +244,8 @@ + + diff --git a/test/expected-report.txt b/test/expected-report.txt index 48e5b54e..57d000e1 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -7,7 +7,7 @@ test/fixable/array_indentation.php 11 0 test/fixable/assignment-operators.php 4 0 test/fixable/concatenation_spacing.php 24 0 test/fixable/EarlyReturn.php 5 0 -test/fixable/example-class.php 21 0 +test/fixable/example-class.php 22 0 test/fixable/forbidden-comments.php 4 0 test/fixable/forbidden-functions.php 6 0 test/fixable/LowCaseTypes.php 2 0 @@ -23,9 +23,9 @@ test/fixable/traits-uses.php 10 0 test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 ---------------------------------------------------------------------- -A TOTAL OF 166 ERRORS AND 0 WARNINGS WERE FOUND IN 19 FILES +A TOTAL OF 167 ERRORS AND 0 WARNINGS WERE FOUND IN 19 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 148 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 149 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- From 5b009740478e0bb93670f1e4ea3d06a15cf49f64 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 6 Sep 2018 22:41:42 +0200 Subject: [PATCH 23/60] Improve documentation formatting --- docs/book/v2/ruleset.md | 48 ++++++----------------------------------- 1 file changed, 7 insertions(+), 41 deletions(-) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index a8834065..04c75952 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -79,16 +79,16 @@ Alias functions should not be used. This can't be fixed automatically and need t ## Force PHP 7 param and return types to be lowercased *Generic.PHP.LowerCaseType* -## Forbid `php_sapi_name()` function, use PHP_SAPI +## Forbid `php_sapi_name()` function, use `PHP_SAPI` *Generic.PHP.SAPIUsage* ## Forbid inline string concatenation, unless used in multiline for readability *Generic.Strings.UnnecessaryStringConcat* -## Forbid comments starting with # +## Forbid comments starting with `#` *PEAR.Commenting.InlineComment* -## Disallow else if in favor of elseif +## Disallow `else if` in favor of `elseif` *PSR2.ControlStructures.ElseIfDeclaration.NotAllowed* ## Require comma after last element in multi-line array @@ -118,7 +118,7 @@ Git commits provide accurate information for these forbidden annotations: @api, Forbidden comments words: private, protected, static, constructor, deconstructor, Created by, getter, setter. -## report invalid format of inline phpDocs with @var +## Report invalid format of inline phpDocs with `@var` *SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration* ## Require comments with single line written as one-liners @@ -197,13 +197,13 @@ Use `$foo = $bar['id'] ?? '1';` where possbile. ## Require the usage of assignment operators, eg `+=`, `.=` when possible *SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator* -## Forbid `list(...)` syntax, use [...] instead +## Forbid `list(...)` syntax, use `[...]` instead *SlevomatCodingStandard.PHP.ShortList* ## Forbid use of longhand cast operators *SlevomatCodingStandard.PHP.TypeCast* -## Require presence of declare(strict_types=1) +## Require presence of `declare(strict_types=1)` *SlevomatCodingStandard.TypeHints.DeclareStrictTypes* ## Forbid useless parentheses @@ -215,7 +215,7 @@ Use `$foo = $bar['id'] ?? '1';` where possbile. ## Require use of short versions of scalar types (i.e. int instead of integer) *SlevomatCodingStandard.TypeHints.LongTypeHints* -## Require ? when default value is null +## Require `?` when default value is `null` *SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue* Checks whether the nullablity ? symbol is present before each nullable and optional parameter @@ -282,40 +282,6 @@ $foo = self::fromPayload($payload); ## Force rules for function phpDoc *Squiz.Commenting.FunctionComment* - ## Allow `@throws` without description - Date: Fri, 7 Sep 2018 18:53:14 +0200 Subject: [PATCH 28/60] Add phpcs cache for speed improvement --- .gitignore | 1 + phpcs.xml.dist | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index b01fd1d7..adb2b52c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/.phpcs-cache /clover.xml /composer.lock /coveralls-upload.json diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 818edf17..c13f0a96 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -5,11 +5,12 @@ The coding standard for ZendCodingStandard itself. - + - - - + + src + + From c15e28eb06111ea8a023e4dae046d3bddc997052 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Fri, 7 Sep 2018 18:59:24 +0200 Subject: [PATCH 29/60] Document the coding standard and all rules All used rules are documented in ruleset.md. coding-style-guide.md contains extends the PSR-1 and PSR-12 documentation and only mentions the differences/extras. Links to the PSR-12 documentation is added for easy reference. I've left plenty of typo's, inconsistencies and mistakes for others to discover. Some rules in the ruleset.md file need examples. --- docs/book/v2/coding-style-guide.md | 384 ++++++++++++++++ docs/book/v2/intro.md | 42 +- docs/book/v2/ruleset.md | 715 ++++++++++++++++++++++------- 3 files changed, 956 insertions(+), 185 deletions(-) create mode 100644 docs/book/v2/coding-style-guide.md diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md new file mode 100644 index 00000000..41020a36 --- /dev/null +++ b/docs/book/v2/coding-style-guide.md @@ -0,0 +1,384 @@ +# 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. + +> 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. + +## General + +### 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 os a standard. + +### Indenting and Alignment + +- There should be one space on either side of an equals sign used to assign a value to a variable. In the case of a + block of related assignments, more space may be inserted before the equal sign to promote readability. + [*](ruleset.md#genericformattingmultiplestatementalignment) + +```php + 'value1', + 'key2' => 'value2', + 'keyTwenty' => 'value3', +]; + +$var = [ + 'one' => function() { + $foo = [1,2,3]; + $barBar = [ + 1, + 2, + 3, + ]; + }, + 'longer' => 2, + /* 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 not start with `#`. [*](ruleset.md#pearcommentinginlinecomment) +- Comments may not be empty. [*](ruleset.md#slevomatcodingstandardcommentingemptycomment) +- To keep comments clean, specific words in comments may not be used: _private_, _protected_, _static_, _constructor_, + _deconstructor_, _Created by_, _getter_, _setter_. [*](ruleset.md#slevomatcodingstandardcommentingforbiddencomments) +- Comments may not contain useless annotations: `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage`, + `@version`. 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) +- If a function throws any exceptions, they should be documented in a `@throws` tag. + [*](ruleset.md#squizcommentingfunctioncomment) +- Use valid format of inline phpDocs with `@var`. [*](ruleset.md#slevomatcodingstandardcommentinginlinedoccommentdeclaration) +- Comments with single-line content should be written as one-liners. [*](ruleset.md#slevomatcodingstandardcommentingrequireonelinepropertydoccomment) +- Shorthand scalar typehint variants must be used in docblocks: `bool` instead of `boolean`, `int` instead of `integer`, + etc. [*](ruleset.md#slevomatcodingstandardtypehintslongtypehints) + +## Declare Statements, Namespace, and Import Statements + +In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#3-declare-statements-namespace-and-import-statements): + +- Each php file should have a page level docblock with `@see`, `@copyright` and `@license`. The copyright date should + only be adjusted if the file has changed. +- Each PHP file should have a strict type declaration at the top after the page level docblock. [*](ruleset.md#slevomatcodingstandardtypehintsdeclarestricttypes) +- Import statements should be alphabetically sorted. [*](ruleset.md#slevomatcodingstandardnamespacesalphabeticallysorteduses) +- Import statements should not be grouped. [*](ruleset.md#slevomatcodingstandardnamespacesdisallowgroupuse) +- Each import statement should be on its own line. [*](ruleset.md#slevomatcodingstandardnamespacesmultipleusesperline) +- Absolute class name references, functions and constants should be imported. [*](ruleset.md#slevomatcodingstandardnamespacesreferenceusednamesonly) +- Unused import statements are not allowed. [*](ruleset.md#slevomatcodingstandardnamespacesunuseduses) +- Classes and function within the same namespace should not be imported. [*](ruleset.md#slevomatcodingstandardnamespacesusefromsamenamespace) +- Imports should not have an alias with the same name. [*](ruleset.md#slevomatcodingstandardnamespacesuselessalias) +- A class should not have unused private constants, (or write-only) properties and methods. [*](ruleset.md#slevomatcodingstandardclassesunusedprivateelements) + +```php + $value) { + // foreach body +} +``` + +### try, catch, finally + +- Catch blocks may be empty. [*](ruleset.md#genericcodeanalysisemptystatementdetectedcatch) +- Catch blocks should be reachable. [*](ruleset.md#slevomatcodingstandardexceptionsdeadcatch) +- Catch blocks must use `Throwable` instead of `Exception`. [*](ruleset.md#slevomatcodingstandardexceptionsreferencethrowableonly) + +```php + $c) { + $variable = $foo ? 'foo' : 'bar'; +} + +$var = 'foo'; +$aVeryLongName = 'bar'; +$function = function ($arg1, $arg2) {}; +``` + +## Closures + +In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#7-closures): + +- Unused variables should not be passed to closures via `use`. [*](ruleset.md#slevomatcodingstandardfunctionsunusedinheritedvariablepassedtoclosure) + +```php +`) should not have any space around it. [*](ruleset.md#squizwhitespaceobjectoperatorspacing) +- Semicolons should not have spaces before them. [*](ruleset.md#squizwhitespacesemicolonspacing) +- The code should not superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. [*](ruleset.md#squizwhitespacesuperfluouswhitespace) diff --git a/docs/book/v2/intro.md b/docs/book/v2/intro.md index 3ac8244b..4200c27b 100644 --- a/docs/book/v2/intro.md +++ b/docs/book/v2/intro.md @@ -2,6 +2,22 @@ This component provides the coding standard ruleset for Zend Framework components. +PSR-1, PSR-2 and PSR-12 are _minimal_ sets and don't address a lot of factors, including things like: + +- whitespace around operators +- alignment of array keys and operators +- alignment of object operations +- how to format multi-line conditionals +- what and what not to import, and how +- etc. + +Contributors have different coding styles and so do the maintainers. During code reviews there are regularly +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: @@ -19,22 +35,34 @@ This component provides the coding standard ruleset for Zend Framework component } ``` -3. Create file `phpcs.xml` on base path of your repository with content: +3. Create file `phpcs.xml.dist` on base path of your repository with content: ```xml - - - + + + + + + + + + + + config src test + + + ``` -You can add or exclude some locations in that file. -For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml +You can add your own rules or exclude rules. For a reference please see: +[PHP_CodeSniffer Annotated Ruleset](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset) ## Usage @@ -53,7 +81,7 @@ For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/An ## Ignoring parts of a File > Note: Before PHP_CodeSniffer version 3.2.0, `// @codingStandardsIgnoreStart` and `// @codingStandardsIgnoreEnd` were -> used. These will be removed in PHP_CodeSniffer version 4.0. +> used. These are deprecated and will be removed in PHP_CodeSniffer version 4.0. Disable parts of a file: ```php diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 04c75952..fb84fee0 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -1,57 +1,156 @@ # Ruleset -## Use PSR-2 coding standard as a base -*PSR2* +## PSR2 +Use PSR-2 coding standard as a base -## Force array element indentation with 4 spaces -*Generic.Arrays.ArrayIndent* +### 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. -## Forbid `array(...)` -*Generic.Arrays.DisallowLongArraySyntax* -## Forbid backtick operator -*Generic.PHP.BacktickOperator* -## Forbid duplicate classes -*Generic.Classes.DuplicateClassName* +## Generic -## Forbid empty statements, but allow empty catch -*Generic.CodeAnalysis.EmptyStatement, Generic.CodeAnalysis.EmptyStatement.DetectedCatch* +### Generic.Arrays.ArrayIndent +All values in multiline arrays must be indented with 4 spaces. -## Forbid final methods in final classes -*Generic.CodeAnalysis.UnnecessaryFinalModifier* +### Generic.Arrays.DisallowLongArraySyntax +Short array syntax must be used to define arrays. +```php +$foo = [...]; +``` + +### Generic.PHP.BacktickOperator +The backtick operator may not be used for execution of shell commands. + +### Generic.Classes.DuplicateClassName +Class and Interface names should be unique in a project. They should never be duplicated. + +### Generic.CodeAnalysis.EmptyStatement +Control Structures must have at least one statement inside of the body. + +#### Generic.CodeAnalysis.EmptyStatement.DetectedCatch +Catch blocks may be empty. +```php +try { + // Try block +} catch (SomeThrowableType $e) { +} +``` + +### Generic.CodeAnalysis.UnnecessaryFinalModifier +Methods may not have the final declaration classes declared as final. + +### Generic.CodeAnalysis.UselessOverridingMethod +Methods should not be defined that only call the parent method. + +```php +// Valid: A method that extends functionality on a parent method. +final class Foo +{ + public function bar() : void + { + parent::bar(); + $this->doSomethingElse(); + } +} + +// Invalid: An overriding method that only calls the parent. +final class Foo +{ + public function bar() : void + { + parent::bar(); + } +} +``` + +### Generic.Files.InlineHTML +Files that contain php code should only have php code and should not have any _"inline html"_. +```php + +some string here +__construct() + { + } +} -## Force whitespace after `!` -*Generic.Formatting.SpaceAfterNot* +// Invalid: The old style class name constructor is used. +class Foo +{ + function Foo() + { + } +} +``` -## Forbid PHP 4 constructors -*Generic.NamingConventions.ConstructorName* +### Generic.PHP.CharacterBeforePHPOpeningTag +The opening php tag should be the first item in the file. +```php +Beginning content +` tags or the short-echo `` tags; it must not use the other tag +variations. -Alias functions should not be used. This can't be fixed automatically and need to be done by hand. +### 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 | | ------------ | ---------------- | @@ -76,181 +175,334 @@ Alias functions should not be used. This can't be fixed automatically and need t | sizeof | count | | strchr | strstr | -## Force PHP 7 param and return types to be lowercased -*Generic.PHP.LowerCaseType* +### Generic.PHP.LowerCaseType +_PSR-12:_ Any new types and keywords added to future PHP versions must be in lower case. -## Forbid `php_sapi_name()` function, use `PHP_SAPI` -*Generic.PHP.SAPIUsage* +### Generic.PHP.SAPIUsage +The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` function. -## Forbid inline string concatenation, unless used in multiline for readability -*Generic.Strings.UnnecessaryStringConcat* +### Generic.Strings.UnnecessaryStringConcat +Strings should not be concatenated together, unless used in multiline for readability. +```php +// Valid: A string can be concatenated with an expression. +echo '5 + 2 = ' . (5 + 2); -## Forbid comments starting with `#` -*PEAR.Commenting.InlineComment* +// Invalid: Strings should not be concatenated together. +echo 'Hello' . ' ' . 'World'; +``` -## Disallow `else if` in favor of `elseif` -*PSR2.ControlStructures.ElseIfDeclaration.NotAllowed* +## PEAR -## Require comma after last element in multi-line array -*SlevomatCodingStandard.Arrays.TrailingArrayComma* +### PEAR.Commenting.InlineComment +Comments may not start with `#`. -## Require presence of constant visibility -*SlevomatCodingStandard.Classes.ClassConstantVisibility* -## Forbid uses of multiple traits separated by comma -*SlevomatCodingStandard.Classes.TraitUseDeclaration* -## Require no spaces before trait use, between trait uses and one space after trait uses +## SlevomatCodingStandard -## Forbid dead code -*SlevomatCodingStandard.Classes.UnusedPrivateElements* +### SlevomatCodingStandard.Arrays.TrailingArrayComma +All array values must be followed by a comma, including the final value. Commas after last element in an array make +adding a new element easier and result in a cleaner versioning diff. -## Forbid useless annotations -*SlevomatCodingStandard.Commenting.ForbiddenAnnotations* +### SlevomatCodingStandard.Classes.ClassConstantVisibility +_PSR-12:_ Visibility MUST be declared on all constants if your project PHP minimum version supports constant visibilities +(PHP 7.1 or later). -Git commits provide accurate information for these forbidden annotations: @api, @author, @category, @created, @package, @subpackage, @version. +### SlevomatCodingStandard.Classes.TraitUseDeclaration +_PSR-12:_ Each individual Trait that is imported into a class MUST be included one-per-line. -## Forbid empty comments -*SlevomatCodingStandard.Commenting.EmptyComment* +### SlevomatCodingStandard.Classes.UnusedPrivateElements +A class should not have unused private constants, (or write-only) properties and methods. -## Forbid useless comments -*SlevomatCodingStandard.Commenting.ForbiddenComments* +### SlevomatCodingStandard.Commenting.ForbiddenAnnotations +Comments may not contain useless annotations: `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage`, +`@version`. Git commits provide accurate information. -Forbidden comments words: private, protected, static, constructor, deconstructor, Created by, getter, setter. +### SlevomatCodingStandard.Commenting.EmptyComment +Comments may not be empty. -## Report invalid format of inline phpDocs with `@var` -*SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration* +### SlevomatCodingStandard.Commenting.ForbiddenComments +To keep comments clean, specific words in comments may not be used: _private_, _protected_, _static_, _constructor_, +_deconstructor_, _Created by_, _getter_, _setter_. -## Require comments with single line written as one-liners -*SlevomatCodingStandard.Commenting.RequireOneLinePropertyDocComment* +### SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration +Use valid format of inline phpDocs with `@var`. +### SlevomatCodingStandard.Commenting.RequireOneLinePropertyDocComment +Comments with single-line content should be written as one-liners. ``` /** * @var array */ private $foo; ``` - Should be written as - ``` /** @var array */ private $foo; ``` -## Forbid weak comparisons -*SlevomatCodingStandard.ControlStructures.DisallowEqualOperators* +### SlevomatCodingStandard.ControlStructures.DisallowEqualOperators +Loose `==` and `!=` comparison operators should not be used. Use `===` and `!==` instead, they are much more secure +and predictable. -## Require usage of early exit -*SlevomatCodingStandard.ControlStructures.EarlyExit* +### SlevomatCodingStandard.ControlStructures.EarlyExit +An early exit strategy should be used where possible to reduce the level of control structures. +```php +// Valid: Exit early. +function () : bool { + if (! true) { + return false; + } + // Do something +}; + +// Invalid: unneeded control structure +function () : bool { + if (true) { + // Do something + } else { + return false; + } +}; +``` -## Require language constructs without parentheses -*SlevomatCodingStandard.ControlStructures.LanguageConstructWithParentheses* +### SlevomatCodingStandard.ControlStructures.LanguageConstructWithParentheses +Language constructs must be used without parentheses where possible. -## Require new instances with parentheses -*SlevomatCodingStandard.ControlStructures.NewWithParentheses* +```php +// Valid: Use language constructs without parentheses. +continue 1; +break 1; +echo 'a'; +print 'b'; +include 'file.php'; +return 'foo'; +yield []; +throw new Exception(); +exit; + +// Invalid: Language constructs with parentheses. +continue(1); +break(1); +echo('a'); +print('b'); +include('file.php'); +return('foo'); +yield([]); +throw(new Exception()); +exit(); +``` -## Require usage of null coalesce operator when possible -*SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator* +### SlevomatCodingStandard.ControlStructures.NewWithParentheses +_PSR-12:_ When instantiating a new class, parenthesis MUST always be present even when there are no arguments passed to +the constructor. +```php +new Foo(); +``` -Use `$foo = $bar['id'] ?? '1';` where possbile. +### SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator +The null coalesce operator should be used when possible. +```php +$foo = $bar['id'] ?? '1'; +``` -## Forbid useless unreachable catch blocks -*SlevomatCodingStandard.Exceptions.DeadCatch* +### SlevomatCodingStandard.Exceptions.DeadCatch +Catch blocks should be reachable. +```php +try { + doStuff(); +} catch (Throwable $e) { + log($e); +} catch (InvalidArgumentException $e) { + // Unreachable because `Throwable` catches everything! +} +``` -## Require using Throwable instead of Exception -*SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly* +### SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly +Catch blocks must use `Throwable` instead of `Exception`. +```php +try { + // ... +} catch (Throwable $e) { -## Forbid unused variables passed to closures via `use` -*SlevomatCodingStandard.Functions.UnusedInheritedVariablePassedToClosure* +} +``` -## Require use statements to be alphabetically sorted -*SlevomatCodingStandard.Namespaces.AlphabeticallySortedUses* +### SlevomatCodingStandard.Functions.UnusedInheritedVariablePassedToClosure +Unused variables should not be passed to closures via `use`. -## Forbid fancy group uses -*SlevomatCodingStandard.Namespaces.DisallowGroupUse* +### SlevomatCodingStandard.Namespaces.AlphabeticallySortedUses +Import statements should be alphabetically sorted. -## Forbid multiple use statements on same line -*SlevomatCodingStandard.Namespaces.MultipleUsesPerLine* +### SlevomatCodingStandard.Namespaces.DisallowGroupUse +Import statements should not be grouped. -## Require newlines around namespace declaration -*SlevomatCodingStandard.Namespaces.NamespaceSpacing* +### SlevomatCodingStandard.Namespaces.MultipleUsesPerLine +Each import statement should be on its own line. -## Forbid using absolute class name references (except global ones) -*SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly* +### SlevomatCodingStandard.Namespaces.NamespaceSpacing +Require newlines around namespace declaration -## Forbid unused use statements -*SlevomatCodingStandard.Namespaces.UnusedUses* +### SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly +Absolute class name references, functions and constants should be imported. -## Forbid superfluous leading backslash in use statements -*SlevomatCodingStandard.Namespaces.UseDoesNotStartWithBackslash* +### SlevomatCodingStandard.Namespaces.UnusedUses +Unused import statements are not allowed. -## Forbid useless uses of the same namespace -*SlevomatCodingStandard.Namespaces.UseFromSameNamespace* +### SlevomatCodingStandard.Namespaces.UseDoesNotStartWithBackslash +_PSR-12:_ Import statements MUST never begin with a leading backslash as they must always be fully qualified. -## Require empty newlines before and after uses -*SlevomatCodingStandard.Namespaces.UseSpacing* +### SlevomatCodingStandard.Namespaces.UseFromSameNamespace +Classes and function within the same namespace should not be imported. +```php +use Foo\Bar as Bar; // Same name as imported class +use Foo\Bar; // Correct +``` -## Forbid useless alias for classes, constants and functions -*SlevomatCodingStandard.Namespaces.UselessAlias* +### SlevomatCodingStandard.Namespaces.UseSpacing +_PSR-12:_ Require empty newlines before and after uses -## Require the usage of assignment operators, eg `+=`, `.=` when possible -*SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator* +### SlevomatCodingStandard.Namespaces.UselessAlias +Imports should not have an alias with the same name. -## Forbid `list(...)` syntax, use `[...]` instead -*SlevomatCodingStandard.PHP.ShortList* +### SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator +Assignment operators (eg `+=`, `.=`) should be used when possible. -## Forbid use of longhand cast operators -*SlevomatCodingStandard.PHP.TypeCast* +```php +self::$a &= 2; +static::$a |= 4; +self::$$parameter .= ''; +parent::${'a'} /= 10; +self::${'a'}[0] -= 100; +Anything::$a **= 2; +Something\Anything::$a %= 2; +\Something\Anything::$a *= 1000; +self::$a::$b += 4; +$this::$a <<= 2; +$this->a >>= 2; +$this->$$parameter ^= 10; +$this->{'a'} += 10; +``` -## Require presence of `declare(strict_types=1)` -*SlevomatCodingStandard.TypeHints.DeclareStrictTypes* +### SlevomatCodingStandard.PHP.ShortList +Short list syntax `[...]` should be used instead of `list(...)`. -## Forbid useless parentheses -*SlevomatCodingStandard.PHP.UselessParentheses* +### SlevomatCodingStandard.PHP.TypeCast +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. -## Forbid useless semicolon `;` -*SlevomatCodingStandard.PHP.UselessSemicolon* +### SlevomatCodingStandard.TypeHints.DeclareStrictTypes +_PSR-12:_ Declare statements MUST contain no spaces and MUST be exactly `declare(strict_types=1)`. +Each PHP file should have a strict type declaration at the top after the page level docblock. +```php + true, @@ -266,66 +518,173 @@ return [ ]; ``` -## Forbid class being in a file with different name -*Squiz.Classes.ClassFileName* +### 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. -## Force `self::` for self-reference, force lower-case self, forbid spaces around `::` -*Squiz.Classes.SelfMemberReference* +### Squiz.Classes.SelfMemberReference +The self keyword should be used instead of the current class name, and should not have spaces around `::`. +```php +class Foo +{ + public static function bar() + { + } + + public static function baz() + { + self::bar(); + } +} +``` +### Squiz.Commenting.DocCommentAlignment +The asterisks in a doc comment should align, and there should be one space between the asterisk and tag. ```php -$foo = self::fromPayload($payload); +/** + * These lines are aligned. + * + * @var array + */ ``` -## Force phpDoc alignment -*Squiz.Commenting.DocCommentAlignment* +### Squiz.Commenting.FunctionComment +If a function throws any exceptions, they should be documented in a `@throws` tag. +```php +/** @throws Exception all the time */ +function foo() : void +{ + throw new Exception('Danger!'); +} +``` +### Squiz.Functions.GlobalFunction +Global functions should not be used. -## Force rules for function phpDoc -*Squiz.Commenting.FunctionComment* +### Squiz.Operators.ValidLogicalOperators +The `&&` and `||` operators must be used instead of `&&` and `||`. -## Forbid global functions -*Squiz.Functions.GlobalFunction* +### Squiz.PHP.GlobalKeyword +The `global` keyword may not be used. -## Forbid `AND` and `OR`, require `&&` and `||` -*Squiz.Operators.ValidLogicalOperators* +### Squiz.PHP.LowercasePHPFunctions +PHP function calls must be in lowercase. -## Forbid `global` -*Squiz.PHP.GlobalKeyword* +### Squiz.PHP.NonExecutableCode +The code may not contain unreachable code. -## Require PHP function calls in lowercase -*Squiz.PHP.LowercasePHPFunctions* +### Squiz.Scope.StaticThisUsage +Static methods should not use $this. +```php +// Valid: Using self:: to access static variables. +class Foo +{ + public static function bar() + { + return self::$staticMember; + } +} -## Forbid dead code -*Squiz.PHP.NonExecutableCode* +// Invalid: Using $this-> to access static variables. +class Foo +{ + public static function bar() + { + return $this->$staticMember; + } +} +``` -## Forbid `$this` inside static function -*Squiz.Scope.StaticThisUsage* +### Squiz.Strings.ConcatenationSpacing +Force whitespace before and after concatenation -## Force whitespace before and after concatenation -*Squiz.Strings.ConcatenationSpacing* +### Squiz.Strings.DoubleQuoteUsage +#### Squiz.Strings.DoubleQuoteUsage.ContainsVar +Double quote strings may only be used if it contains variables. +```php +// Valid: Double quote strings are only used when it contains a variable. +$string = "Hello There\r\n"; +$string = "Hello $there"; +$string = 'Hello There'; +$string = 'Hello'.' There'."\n"; +$string = '\$var'; + +// Invalid: There are no variables inside double quote strings. +$string = "Hello There"; +$string = "Hello"." There"."\n"; +$string = "\$var"; +``` -## Forbid strings in `"` unless necessary -*Squiz.Strings.DoubleQuoteUsage, Squiz.Strings.DoubleQuoteUsage.ContainsVar* +### Squiz.Strings.EchoedStrings +Simple strings should not be enclosed in parentheses when being echoed. +```php +// "Valid: Using echo without parentheses. +echo 'Hello'; -## Forbid braces around string in `echo` -*Squiz.Strings.EchoedStrings* +// Invalid: Using echo with parentheses. +echo('Hello'); +``` -## Forbid spaces in type casts -*Squiz.WhiteSpace.CastSpacing* +### Squiz.WhiteSpace.CastSpacing +Casts should not have whitespace inside the parentheses. +```php +// Valid: No spaces. +$foo = (int) '42'; -## Forbid blank line after function opening brace -*Squiz.WhiteSpace.FunctionOpeningBraceSpace* +// Invalid: Whitespace used inside parentheses. +$foo = ( int ) '42'; +``` -## Require space after language constructs -*Squiz.WhiteSpace.LanguageConstructSpacing* +### Squiz.WhiteSpace.FunctionOpeningBraceSpace +The opening brace for functions should be on a new line with no blank lines surrounding it. +```php +// Valid: Opening brace is on a new line. +function foo() : int +{ + return 42; +} -## Require space around logical operators -*Squiz.WhiteSpace.LogicalOperatorSpacing* +// Invalid: Opening brace is on the same line as the function declaration and a blank line after the opening brace. +function foo() { -## Forbid spaces around `->` operator -*Squiz.WhiteSpace.ObjectOperatorSpacing* + return 42; +} +``` + +### Squiz.WhiteSpace.LanguageConstructSpacing +The php constructs `echo`, `print`, `return`, `include`, `include_once`, `require`, `require_once`, and `new` should +have one space after them. + +```php +// Valid: echo statement with a single space after it. +echo 'hi'; + +// Invalid: echo statement with no space after it. +echo'hi'; +``` + +### Squiz.WhiteSpace.LogicalOperatorSpacing +_PSR-12:_ There must be one space around logical operators. -## Forbid spaces before semicolon `;` -*Squiz.WhiteSpace.SemicolonSpacing* +### Squiz.WhiteSpace.ObjectOperatorSpacing +The object operator (`->`) should not have any space around it. +```php +// Valid: No spaces around the object operator. +$foo->bar(); + +// Invalid: Whitespace surrounding the object operator. +$foo -> bar(); +``` + +### Squiz.WhiteSpace.SemicolonSpacing +Semicolons should not have spaces before them. +```php +// Valid: No space before the semicolon. +echo 'hi'; + +// Valid: Invalid: Space before the semicolon. +echo 'hi' ; +``` -## Forbid superfluous whitespaces -*Squiz.WhiteSpace.SuperfluousWhitespace, Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines* +### Squiz.WhiteSpace.SuperfluousWhitespace +#### Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines +The code should not superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. From d044763fd16490499d887f96363814ff032eac3f Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Fri, 7 Sep 2018 22:41:27 +0200 Subject: [PATCH 30/60] First set of documentation improvements and fixes --- docs/book/v2/coding-style-guide.md | 53 ++++++++++++------------ docs/book/v2/ruleset.md | 65 +++++++++++++++++++----------- 2 files changed, 67 insertions(+), 51 deletions(-) diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 41020a36..2b95efda 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -13,11 +13,11 @@ We will change these rules, and, when PSR-12 is finalized, adapt them. 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 os a standard. +specific cases outlined in this specification, until PSR-12 is accepted as a standard. ### Indenting and Alignment -- There should be one space on either side of an equals sign used to assign a value to a variable. In the case of a +- 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) @@ -31,7 +31,7 @@ $var = foo($bar, $baz, $quux); - 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 final value. [*](ruleset.md#slevomatcodingstandardarraystrailingarraycomma) +- 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) @@ -69,20 +69,20 @@ $var = [ ### 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) -- To keep comments clean, specific words in comments may not be used: _private_, _protected_, _static_, _constructor_, - _deconstructor_, _Created by_, _getter_, _setter_. [*](ruleset.md#slevomatcodingstandardcommentingforbiddencomments) -- Comments may not contain useless annotations: `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage`, - `@version`. Git commits provide accurate information. [*](ruleset.md#slevomatcodingstandardcommentingforbiddenannotations) +- 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) -- If a function throws any exceptions, they should be documented in a `@throws` tag. +- If a function throws any exceptions, they should be documented in `@throws` tags. [*](ruleset.md#squizcommentingfunctioncomment) -- Use valid format of inline phpDocs with `@var`. [*](ruleset.md#slevomatcodingstandardcommentinginlinedoccommentdeclaration) +- The `@var` tag may be used in inline comments to document the _Type_ of properties. [*](ruleset.md#slevomatcodingstandardcommentinginlinedoccommentdeclaration) - Comments with single-line content should be written as one-liners. [*](ruleset.md#slevomatcodingstandardcommentingrequireonelinepropertydoccomment) -- Shorthand scalar typehint variants must be used in docblocks: `bool` instead of `boolean`, `int` instead of `integer`, - etc. [*](ruleset.md#slevomatcodingstandardtypehintslongtypehints) +- Shorthand scalar typehint variants must be used in docblocks. [*](ruleset.md#slevomatcodingstandardtypehintslongtypehints) ## Declare Statements, Namespace, and Import Statements @@ -135,7 +135,7 @@ class FooBar In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#4-classes-properties-and-methods): -- Methods may not have the final declaration classes declared as final. [*](ruleset.md#genericcodeanalysisunnecessaryfinalmodifier) +- Methods may not have the final declaration in classes declared as final. [*](ruleset.md#genericcodeanalysisunnecessaryfinalmodifier) - The colon used with return type declarations MUST be surrounded with 1 space. [*](ruleset.md#slevomatcodingstandardtypehintsreturntypehintspacing) - Nullable and optional arguments, which are marked as `= null`, must have the nullablity `?` symbol present. [*](ruleset.md#slevomatcodingstandardtypehintsnullabletypefornulldefaultvalue) @@ -254,7 +254,7 @@ foreach ($iterable as $key => $value) { ### try, catch, finally - Catch blocks may be empty. [*](ruleset.md#genericcodeanalysisemptystatementdetectedcatch) -- Catch blocks should be reachable. [*](ruleset.md#slevomatcodingstandardexceptionsdeadcatch) +- Catch blocks must be reachable. [*](ruleset.md#slevomatcodingstandardexceptionsdeadcatch) - Catch blocks must use `Throwable` instead of `Exception`. [*](ruleset.md#slevomatcodingstandardexceptionsreferencethrowableonly) ```php @@ -275,7 +275,7 @@ try { In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#6-operators): - The not (`!`) operator must be followed by exactly one space. [*](ruleset.md#genericformattingspaceafternot) -- The `&&` and `||` operators must be used instead of `&&` and `||`. [*](ruleset.md#squizoperatorsvalidlogicaloperators) +- The `&&` and `||` operators must be used instead of `AND` and `OR`. [*](ruleset.md#squizoperatorsvalidlogicaloperators) - The null coalesce operator should be used when possible. [*](ruleset.md#slevomatcodingstandardcontrolstructuresrequirenullcoalesceoperator) - Assignment operators (eg `+=`, `.=`) should be used when possible. [*](ruleset.md#slevomatcodingstandardoperatorsrequirecombinedassignmentoperator) @@ -352,33 +352,32 @@ $instance = new class extends Foo implements - The code may not contain unreachable code. [*](ruleset.md#squizphpnonexecutablecode) - The backtick operator may not be used for execution of shell commands. [*](ruleset.md#genericphpbacktickoperator) - Class and Interface names should be unique in a project. They should never be duplicated. [*](ruleset.md#genericclassesduplicateclassname) -- Methods should not be defined that only call the parent method. [*](ruleset.md#genericcodeanalysisuselessoverridingmethod) +- Methods that only call the parent method should not be defined. [*](ruleset.md#genericcodeanalysisuselessoverridingmethod) - Files that contain php code should only have php code and should not have any _"inline html"_. [*](ruleset.md#genericfilesinlinehtml) -- There must be exactly one space after a cast. [*](ruleset.md#genericformattingspaceaftercast) +- There must be exactly one space after a type cast. [*](ruleset.md#genericformattingspaceaftercast) - Constructors should be named `__construct`, not after the class. [*](ruleset.md#genericnamingconventionsconstructorname) - The opening php tag should be the first item in the file. [*](ruleset.md#genericphpcharacterbeforephpopeningtag) - Strings should not be concatenated together, unless used in multiline for readability. [*](ruleset.md#genericstringsunnecessarystringconcat) -- Loose `==` and `!=` comparison operators should not be used. Use `===` and `!==` instead, they are much more secure - and predictable. [*](ruleset.md#slevomatcodingstandardcontrolstructuresdisallowequaloperators) +- Loose `==` and `!=` comparison operators should not be used. Use `===` and `!==` instead. [*](ruleset.md#slevomatcodingstandardcontrolstructuresdisallowequaloperators) - An early exit strategy should be used where possible to reduce the level of control structures. [*](ruleset.md#slevomatcodingstandardcontrolstructuresearlyexit) - Language constructs must be used without parentheses where possible. [*](ruleset.md#slevomatcodingstandardcontrolstructureslanguageconstructwithparentheses) - Short list syntax `[...]` should be used instead of `list(...)`. [*](ruleset.md#slevomatcodingstandardphpshortlist) - 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. [*](ruleset.md#slevomatcodingstandardphptypecast) -- Unneeded parentheses should not be used. [*](ruleset.md#slevomatcodingstandardphpuselessparentheses) -- Semicolons `;` should not be used if they are not needed. [*](ruleset.md#slevomatcodingstandardphpuselesssemicolon) +- Parentheses should not be used if they can be omitted. [*](ruleset.md#slevomatcodingstandardphpuselessparentheses) +- Semicolons `;` should not be used if they can be omitted. [*](ruleset.md#slevomatcodingstandardphpuselesssemicolon) - Variables should be returned directly instead of assigned to a variable which is not used. [*](ruleset.md#slevomatcodingstandardvariablesuselessvariable) - The self keyword should be used instead of the current class name, and should not have spaces around `::`. [*](ruleset.md#squizclassesselfmemberreference) - Global functions should not be used. [*](ruleset.md#squizfunctionsglobalfunction) -- Static methods should not use $this. [*](ruleset.md#squizscopestaticthisusage) -- Double quote strings may only be used if it contains variables. [*](ruleset.md#squizstringsdoublequoteusage) -- Simple strings should not be enclosed in parentheses when being echoed. [*](ruleset.md#squizstringsechoedstrings) -- Casts should not have whitespace inside the parentheses. [*](ruleset.md#squizwhitespacecastspacing) +- Static methods should not use `$this`. [*](ruleset.md#squizscopestaticthisusage) +- Double quote strings may only be used if they contain variables. [*](ruleset.md#squizstringsdoublequoteusage) +- Strings should not be enclosed in parentheses when being echoed. [*](ruleset.md#squizstringsechoedstrings) +- Type casts should not have whitespace inside the parentheses. [*](ruleset.md#squizwhitespacecastspacing) - The opening brace for functions should be on a new line with no blank lines surrounding it. [*](ruleset.md#squizwhitespacefunctionopeningbracespace) -- The php constructs `echo`, `print`, `return`, `include`, `include_once`, `require`, `require_once`, and `new` should +- The php constructs `echo`, `print`, `return`, `include`, `include_once`, `require`, `require_once`, and `new`, should have one space after them. [*](ruleset.md#squizwhitespacelanguageconstructspacing) -- The object operator (`->`) should not have any space around it. [*](ruleset.md#squizwhitespaceobjectoperatorspacing) +- The object operator `->` should not have any spaces around it. [*](ruleset.md#squizwhitespaceobjectoperatorspacing) - Semicolons should not have spaces before them. [*](ruleset.md#squizwhitespacesemicolonspacing) -- The code should not superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. [*](ruleset.md#squizwhitespacesuperfluouswhitespace) +- The code should not contain superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. [*](ruleset.md#squizwhitespacesuperfluouswhitespace) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index fb84fee0..7522cb6e 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -41,7 +41,7 @@ try { Methods may not have the final declaration classes declared as final. ### Generic.CodeAnalysis.UselessOverridingMethod -Methods should not be defined that only call the parent method. +Methods that only call the parent method should not be defined. ```php // Valid: A method that extends functionality on a parent method. @@ -82,7 +82,7 @@ echo $foo . 'baz'; ``` ### Generic.Formatting.MultipleStatementAlignment -There should be one space on either side of an equals sign used to assign a value to a variable. In the case of a +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. ```php __construct() + function __construct() { } } @@ -121,7 +121,7 @@ class Foo // Invalid: The old style class name constructor is used. class Foo { - function Foo() + function Foo() { } } @@ -201,7 +201,7 @@ Comments may not start with `#`. ## SlevomatCodingStandard ### SlevomatCodingStandard.Arrays.TrailingArrayComma -All array values must be followed by a comma, including the final value. Commas after last element in an array make +All array values must be followed by a comma, including the last value. Commas after last element in an array make adding a new element easier and result in a cleaner versioning diff. ### SlevomatCodingStandard.Classes.ClassConstantVisibility @@ -215,29 +215,47 @@ _PSR-12:_ Each individual Trait that is imported into a class MUST be included o A class should not have unused private constants, (or write-only) properties and methods. ### SlevomatCodingStandard.Commenting.ForbiddenAnnotations -Comments may not contain useless annotations: `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage`, -`@version`. Git commits provide accurate information. +The annotations `@api`, `@author`, `@category`, `@created`, `@package`, `@subpackage` and `@version` may not +be used in comments. Git commits provide accurate information. ### SlevomatCodingStandard.Commenting.EmptyComment Comments may not be empty. ### SlevomatCodingStandard.Commenting.ForbiddenComments -To keep comments clean, specific words in comments may not be used: _private_, _protected_, _static_, _constructor_, -_deconstructor_, _Created by_, _getter_, _setter_. +To keep comments clean, the words _private_, _protected_, _static_, _constructor_, _deconstructor_, _Created by_, +_getter_ and _setter_ may not be used in comments ### SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration -Use valid format of inline phpDocs with `@var`. +The `@var` tag may be used in inline comments to document the _Type_ of properties, sometimes called class variables. +```php +class Foo +{ + /** @var string */ + private $foo; + + public function __construct() + { + /** @var string $f */ + foreach ($e as $f) { + // ... + } + + /** @var string[] $a */ + $a = $this->get(); + } +} +``` ### SlevomatCodingStandard.Commenting.RequireOneLinePropertyDocComment Comments with single-line content should be written as one-liners. -``` +```php /** * @var array */ private $foo; ``` Should be written as -``` +```php /** @var array */ private $foo; ``` @@ -308,7 +326,7 @@ $foo = $bar['id'] ?? '1'; ``` ### SlevomatCodingStandard.Exceptions.DeadCatch -Catch blocks should be reachable. +Catch blocks must be reachable. ```php try { doStuff(); @@ -409,8 +427,7 @@ declare(strict_types=1); ``` ### SlevomatCodingStandard.PHP.UselessParentheses -Unneeded parentheses should not be used. - +Parentheses should not be used if they can be omitted. ```php // Valid: No parentheses used. $x = $y !== null ? true : false; @@ -430,7 +447,7 @@ $x = (self::$a::$b); ``` ### SlevomatCodingStandard.PHP.UselessSemicolon -Semicolons `;` should not be used if they are not needed. +Semicolons `;` should not be used if they can be omitted. ```php // Valid: Semicolon used where needed. foo(); @@ -549,7 +566,7 @@ The asterisks in a doc comment should align, and there should be one space betwe ``` ### Squiz.Commenting.FunctionComment -If a function throws any exceptions, they should be documented in a `@throws` tag. +If a function throws any exceptions, they should be documented in `@throws` tags. ```php /** @throws Exception all the time */ function foo() : void @@ -573,7 +590,7 @@ PHP function calls must be in lowercase. The code may not contain unreachable code. ### Squiz.Scope.StaticThisUsage -Static methods should not use $this. +Static methods should not use `$this`. ```php // Valid: Using self:: to access static variables. class Foo @@ -599,7 +616,7 @@ Force whitespace before and after concatenation ### Squiz.Strings.DoubleQuoteUsage #### Squiz.Strings.DoubleQuoteUsage.ContainsVar -Double quote strings may only be used if it contains variables. +Double quote strings may only be used if they contain variables. ```php // Valid: Double quote strings are only used when it contains a variable. $string = "Hello There\r\n"; @@ -615,7 +632,7 @@ $string = "\$var"; ``` ### Squiz.Strings.EchoedStrings -Simple strings should not be enclosed in parentheses when being echoed. +Strings should not be enclosed in parentheses when being echoed. ```php // "Valid: Using echo without parentheses. echo 'Hello'; @@ -625,7 +642,7 @@ echo('Hello'); ``` ### Squiz.WhiteSpace.CastSpacing -Casts should not have whitespace inside the parentheses. +Type casts should not have whitespace inside the parentheses. ```php // Valid: No spaces. $foo = (int) '42'; @@ -666,7 +683,7 @@ echo'hi'; _PSR-12:_ There must be one space around logical operators. ### Squiz.WhiteSpace.ObjectOperatorSpacing -The object operator (`->`) should not have any space around it. +The object operator `->` should not have any spaces around it. ```php // Valid: No spaces around the object operator. $foo->bar(); @@ -687,4 +704,4 @@ echo 'hi' ; ### Squiz.WhiteSpace.SuperfluousWhitespace #### Squiz.WhiteSpace.SuperfluousWhitespace.EmptyLines -The code should not superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. +The code should not contain superfluous whitespaces. e.g. multiple empty lines, trailing spaces, etc. From f722edd207f11bdc54d8ac625e08b890f0fb8a3f Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 8 Sep 2018 07:16:26 +0200 Subject: [PATCH 31/60] More grammar fixes --- docs/book/v2/coding-style-guide.md | 18 +++++++++--------- docs/book/v2/ruleset.md | 14 +++++++------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 2b95efda..4a613f44 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -4,7 +4,7 @@ This specification extends and expands [PSR-12](https://github.com/php-fig/fig-s the extended coding style guide and requires adherence to [PSR-1](https://www.php-fig.org/psr/psr-1), the basic coding standard. -> Note: PSR-12 is not finalized. e.g. The `!` operator and `:` placement for return values are still under discussion. +> 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. ## General @@ -88,7 +88,7 @@ $var = [ In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#3-declare-statements-namespace-and-import-statements): -- Each php file should have a page level docblock with `@see`, `@copyright` and `@license`. The copyright date should +- Each PHP file should have a page level docblock with `@see`, `@copyright` and `@license`. The copyright date should only be adjusted if the file has changed. - Each PHP file should have a strict type declaration at the top after the page level docblock. [*](ruleset.md#slevomatcodingstandardtypehintsdeclarestricttypes) - Import statements should be alphabetically sorted. [*](ruleset.md#slevomatcodingstandardnamespacesalphabeticallysorteduses) @@ -137,7 +137,7 @@ In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/pro - Methods may not have the final declaration in classes declared as final. [*](ruleset.md#genericcodeanalysisunnecessaryfinalmodifier) - The colon used with return type declarations MUST be surrounded with 1 space. [*](ruleset.md#slevomatcodingstandardtypehintsreturntypehintspacing) -- Nullable and optional arguments, which are marked as `= null`, must have the nullablity `?` symbol present. [*](ruleset.md#slevomatcodingstandardtypehintsnullabletypefornulldefaultvalue) +- Nullable and optional arguments, which are marked as `= null`, must have the `?` symbol present. [*](ruleset.md#slevomatcodingstandardtypehintsnullabletypefornulldefaultvalue) ```php ` should not have any spaces around it. [*](ruleset.md#squizwhitespaceobjectoperatorspacing) - Semicolons should not have spaces before them. [*](ruleset.md#squizwhitespacesemicolonspacing) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 7522cb6e..743fff17 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -65,7 +65,7 @@ final class Foo ``` ### Generic.Files.InlineHTML -Files that contain php code should only have php code and should not have any _"inline html"_. +Files that contain PHP code should only have PHP code and should not have any _"inline HTML"_. ```php Date: Sat, 8 Sep 2018 07:17:30 +0200 Subject: [PATCH 32/60] Reorder rules and disable double rules --- src/ZendCodingStandard/ruleset.xml | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index df25a730..8c52be8a 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -5,14 +5,17 @@ The ZendFramework coding standard. - + + + + + + - - @@ -24,11 +27,6 @@ - - - - - @@ -43,10 +41,17 @@ + + + + + + + @@ -172,6 +177,7 @@ + From 2702288f7ff24e5738e208249a771b382ce92d96 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 8 Sep 2018 07:42:52 +0200 Subject: [PATCH 33/60] Add missing rule: Class name resolution via ::class --- docs/book/v2/coding-style-guide.md | 2 ++ docs/book/v2/ruleset.md | 4 +++ src/ZendCodingStandard/ruleset.xml | 6 ++-- test/expected-report.txt | 5 ++-- test/fixable/class-name-resolution.php | 40 ++++++++++++++++++++++++++ test/fixed/class-name-resolution.php | 40 ++++++++++++++++++++++++++ 6 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 test/fixable/class-name-resolution.php create mode 100644 test/fixed/class-name-resolution.php diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 4a613f44..81f29621 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -135,6 +135,8 @@ class FooBar In addition to [PSR-12](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md#4-classes-properties-and-methods): +- Class name resolution via `::class` should be used instead of `__CLASS__`, `get_class()`, `get_class($this)`, + `get_called_class()` and `get_parent_class()`. [*](ruleset.md#slevomatcodingstandardclassesmodernclassnamereference) - Methods may not have the final declaration in classes declared as final. [*](ruleset.md#genericcodeanalysisunnecessaryfinalmodifier) - The colon used with return type declarations MUST be surrounded with 1 space. [*](ruleset.md#slevomatcodingstandardtypehintsreturntypehintspacing) - Nullable and optional arguments, which are marked as `= null`, must have the `?` symbol present. [*](ruleset.md#slevomatcodingstandardtypehintsnullabletypefornulldefaultvalue) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 743fff17..4ed1d9ce 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -208,6 +208,10 @@ adding a new element easier and result in a cleaner versioning diff. _PSR-12:_ Visibility MUST be declared on all constants if your project PHP minimum version supports constant visibilities (PHP 7.1 or later). +### SlevomatCodingStandard.Classes.ModernClassNameReference +Class name resolution via `::class` should be used instead of `__CLASS__`, `get_class()`, `get_class($this)`, +`get_called_class()` and `get_parent_class()`. + ### SlevomatCodingStandard.Classes.TraitUseDeclaration _PSR-12:_ Each individual Trait that is imported into a class MUST be included one-per-line. diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 8c52be8a..d49bacfa 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -6,9 +6,9 @@ - + - + @@ -108,6 +108,8 @@ + + diff --git a/test/expected-report.txt b/test/expected-report.txt index 942d16e3..50740dd0 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -5,6 +5,7 @@ FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 test/fixable/array-indentation.php 11 0 +test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/concatenation-spacing.php 18 0 test/fixable/EarlyReturn.php 5 0 @@ -28,9 +29,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 209 ERRORS AND 0 WARNINGS WERE FOUND IN 24 FILES +A TOTAL OF 221 ERRORS AND 0 WARNINGS WERE FOUND IN 25 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 188 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 195 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/class-name-resolution.php b/test/fixable/class-name-resolution.php new file mode 100644 index 00000000..5d228873 --- /dev/null +++ b/test/fixable/class-name-resolution.php @@ -0,0 +1,40 @@ + Date: Sat, 8 Sep 2018 07:50:13 +0200 Subject: [PATCH 34/60] Add coding-style-guide to mkdocs config --- mkdocs.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mkdocs.yml b/mkdocs.yml index 2a3dffe7..fe94352d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -3,12 +3,13 @@ site_dir: docs/html pages: - index.md - 'Introduction': v2/intro.md - - Reference: + - 'Coding Style Guide': v2/coding-style-guide.md + - 'Reference': - 'Ruleset': v2/ruleset.md - v1: - v1/index.md - 'Introduction': v1/intro.md - - Reference: + - 'Reference': - 'Ruleset': v1/ruleset.md site_name: Zend Coding Standard From 4da57721d1ad71891544aa930f3cb4a414119b67 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 8 Sep 2018 08:17:47 +0200 Subject: [PATCH 35/60] Add changelog for #5 --- CHANGELOG.md | 138 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7fd6df6..76f59fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,144 @@ All notable changes to this project will be documented in this file, in reverse chronological order by release. +## 2.0.0 - TBD + +### Added + +- [#5](https://github.com/zendframework/zend-coding-standard/pull/5) adds + online documentation: https://docs.zendframework.com/zend-coding-standard/ +- [#5](https://github.com/zendframework/zend-coding-standard/pull/5) adds + PSR-12 rules. + + *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. +- [#5](https://github.com/zendframework/zend-coding-standard/pull/5) extends + PSR-12 with ZendFramework specific rules: + + *NOTE:* Most of these rules should look familiar as they are already being + used in components rewritten for PHP 7.1. + + - 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. + - 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. + - Whitespace is not allowed 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 `global` keyword may not be used. + - The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` + function. + - PHP function calls must be in lowercase. + - PHP functions which are an alias may not be used. + - Deprecated functions should not be used. + - Comments may be omitted and should not be used for typehinted arguments. + - Comments may not start with `#`. + - Comments may not be empty. + - The words _private_, _protected_, _static_, _constructor_, _deconstructor_, + _Created by_, _getter_ and _setter_, may not be used in comments. + - The annotations `@api`, `@author`, `@category`, `@created`, `@package`, + `@subpackage` and `@version` may not be used in comments. Git commits + provide accurate information. + - The asterisks in a doc comment should align, and there should be one space + between the asterisk and tag. + - If a function throws any exceptions, they should be documented in `@throws` + tags. + - The `@var` tag may be used in inline comments to document the _Type_ of + properties. + - Comments with single-line content should be written as one-liners. + - Shorthand scalar typehint variants must be used in docblocks. + - Each PHP file should have a page level docblock with `@see`, `@copyright` + and `@license`. The copyright date should only be adjusted if the file has + changed. + - Each PHP file should have a strict type declaration at the top after the + page level docblock. + - Import statements should be alphabetically sorted. + - Import statements should not be grouped. + - Each import statement should be on its own line. + - Absolute class name references, functions and constants should be imported. + - Unused import statements are not allowed. + - Classes and function within the same namespace should not be imported. + - Imports should not have an alias with the same name. + - A class should not have unused private constants, (or write-only) + properties and methods. + - Class name resolution via `::class` should be used instead of + `__CLASS__`, `get_class()`, `get_class($this)`, `get_called_class()` and + `get_parent_class()`. + - Methods may not have the final declaration in classes declared as final. + - The colon used with return type declarations MUST be surrounded with 1 + space. + - Nullable and optional arguments, which are marked as `= null`, must have + the `?` symbol present. + - Control Structures must have at least one statement inside of the body. + - Catch blocks may be empty. + - Catch blocks must be reachable. + - Catch blocks must use `Throwable` instead of `Exception`. + - The not (`!`) operator must be followed by exactly one space. + - The `&&` and `||` operators must be used instead of `AND` and `OR`. + - The null coalescing operator `??` should be used when possible. + - Assignment operators (eg `+=`, `.=`) should be used when possible. + - Unused variables should not be passed to closures via `use`. + - The code may not contain unreachable code. + - The backtick operator may not be used for execution of shell commands. + - Class and Interface names should be unique in a project. They should + never be duplicated. + - Methods that only call the parent method should not be defined. + - Files that contain PHP code should only have PHP code and should not have + any _"inline HTML"_. + - There must be exactly one space after a type cast. + - Constructors should be named `__construct`, not after the class. + - The opening PHP tag should be the first item in the file. + - Strings should not be concatenated together unless used in multiline for + readability. + - Loose `==` and `!=` comparison operators should not be used. Use `===` + and `!==` instead. + - An early exit strategy should be used where possible to reduce the level + of control structures. + - Language constructs must be used without parentheses where possible. + - Short list syntax `[...]` should be used instead of `list(...)`. + - 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. + - Parentheses should not be used if they can be omitted. + - Semicolons `;` should not be used if they can be omitted. + - Variables should be returned directly instead of assigned to a variable + which is not used. + - The `self` keyword should be used instead of the current class name, and + should not have spaces around `::`. + - Global functions should not be used. + - Static methods should not use `$this`. + - Double quote strings may only be used if they contain variables. + - Strings should not be enclosed in parentheses when being echoed. + - Type casts should not have whitespace inside the parentheses. + - The opening brace for functions should be on a new line with no blank + lines surrounding it. + - The PHP constructs `echo`, `print`, `return`, `include`, `include_once`, + `require`, `require_once`, and `new`, should have one space after them. + - The object operator `->` should not have any spaces around it. + - Semicolons should not have spaces before them. + - The code should not contain superfluous whitespaces. e.g. multiple empty + lines, trailing spaces, etc. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + ## 1.0.0 - 2016-11-09 Initial public release. Incorporates rules for: From 9737c95af244f4c2b0c4bee6268ad97fd6a3577f Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 8 Sep 2018 08:50:00 +0200 Subject: [PATCH 36/60] Improve wording and add example for Generic.Classes.DuplicateClassName --- CHANGELOG.md | 4 ++-- docs/book/v2/coding-style-guide.md | 2 +- docs/book/v2/ruleset.md | 36 +++++++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76f59fd1..30e8390a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,8 +85,8 @@ All notable changes to this project will be documented in this file, in reverse - Unused variables should not be passed to closures via `use`. - The code may not contain unreachable code. - The backtick operator may not be used for execution of shell commands. - - Class and Interface names should be unique in a project. They should - never be duplicated. + - Class and Interface names should be unique in a project and must have a + unique fully qualified name. - Methods that only call the parent method should not be defined. - Files that contain PHP code should only have PHP code and should not have any _"inline HTML"_. diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 81f29621..a76dcda6 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -353,7 +353,7 @@ $instance = new class extends Foo implements - The code may not contain unreachable code. [*](ruleset.md#squizphpnonexecutablecode) - The backtick operator may not be used for execution of shell commands. [*](ruleset.md#genericphpbacktickoperator) -- Class and Interface names should be unique in a project. They should never be duplicated. [*](ruleset.md#genericclassesduplicateclassname) +- Class and Interface names should be unique in a project and must have a unique fully qualified name. [*](ruleset.md#genericclassesduplicateclassname) - Methods that only call the parent method should not be defined. [*](ruleset.md#genericcodeanalysisuselessoverridingmethod) - Files that contain PHP code should only have PHP code and should not have any _"inline HTML"_. [*](ruleset.md#genericfilesinlinehtml) - There must be exactly one space after a type cast. [*](ruleset.md#genericformattingspaceaftercast) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 4ed1d9ce..7cc7347c 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -23,7 +23,41 @@ $foo = [...]; The backtick operator may not be used for execution of shell commands. ### Generic.Classes.DuplicateClassName -Class and Interface names should be unique in a project. They should never be duplicated. +Class and Interface names should be unique in a project and must have a unique fully qualified name. They should never +be duplicated. +```php + Date: Sat, 8 Sep 2018 10:47:42 +0200 Subject: [PATCH 37/60] It's raining outside, so more examples and improved formatting --- docs/book/v2/ruleset.md | 561 +++++++++++++++++++++++++++++++++++----- 1 file changed, 493 insertions(+), 68 deletions(-) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 7cc7347c..3eecff17 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -15,18 +15,28 @@ All values in multiline arrays must be indented with 4 spaces. ### Generic.Arrays.DisallowLongArraySyntax Short array syntax must be used to define arrays. + ```php -$foo = [...]; + 'bar']; ``` ### Generic.PHP.BacktickOperator The backtick operator may not be used for execution of shell commands. +*Invalid: Using the backtick operator.* +```php + 0; $i--) { + echo 'hello'; +} +``` + +*Invalid:* +```php +doSomethingElse(); } } +``` -// Invalid: An overriding method that only calls the parent. +*Invalid: An overriding method that only calls the parent.* +```php + -some string here +some string here Beginning content +Beginning content ` tags or the short-echo `` tags; it must not use the other tag @@ -215,22 +317,53 @@ _PSR-12:_ Any new types and keywords added to future PHP versions must be in low ### Generic.PHP.SAPIUsage The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` function. +*Valid: PHP_SAPI is used.* +```php +{'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 -Short form of type keywords must be used. i.e. `bool` instead of `boolean`, `int` instead of `integer`, etc. +_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 -_PSR-12:_ Declare statements MUST contain no spaces and MUST be exactly `declare(strict_types=1)`. 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, @@ -573,13 +930,33 @@ return [ ]; ``` +*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. +*Invalid: Using `$this->` to access static variables.* +```php +` should not have any spaces around it. + +*Valid: No spaces around the object operator.* ```php -// Valid: No spaces around the object operator. +bar(); +``` -// Invalid: Whitespace surrounding the object operator. +*Invalid: Whitespace surrounding the object operator.* +```php + bar(); ``` ### Squiz.WhiteSpace.SemicolonSpacing Semicolons should not have spaces before them. + +*Valid: No space before the semicolon.* ```php -// Valid: No space before the semicolon. + Date: Sat, 8 Sep 2018 15:43:22 +0200 Subject: [PATCH 38/60] Update phpcs config in readme --- README.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c5aec180..9a63374b 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,25 @@ The coding standard ruleset for Zend Framework components. ```xml - - - + + + + + + + + + + + config src test + + + ``` From f93740be2b4dd5d7ed61f6f958c01d8739998a9c Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sun, 9 Sep 2018 09:20:04 +0200 Subject: [PATCH 39/60] Update array indentation test --- test/expected-report.txt | 6 +++--- test/fixable/array-indentation.php | 29 +++++++++++++++++------------ test/fixed/array-indentation.php | 27 ++++++++++++++++----------- 3 files changed, 36 insertions(+), 26 deletions(-) diff --git a/test/expected-report.txt b/test/expected-report.txt index 50740dd0..07210a0c 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,7 +4,7 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 11 0 +test/fixable/array-indentation.php 8 0 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/concatenation-spacing.php 18 0 @@ -29,9 +29,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 221 ERRORS AND 0 WARNINGS WERE FOUND IN 25 FILES +A TOTAL OF 218 ERRORS AND 0 WARNINGS WERE FOUND IN 25 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 195 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 192 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/array-indentation.php b/test/fixable/array-indentation.php index 5866c10d..fbf5794b 100644 --- a/test/fixable/array-indentation.php +++ b/test/fixable/array-indentation.php @@ -11,18 +11,23 @@ 5, ]; -$multiArray = [ -'0' => [ - '2' => 2, - 1 => '1', -], - 4 => [ - 7, - 8, - 9, - ], -]; - $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"}', +]; diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index 7c7245a8..468b1229 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -11,16 +11,21 @@ 5, ]; -$multiArray = [ - '0' => [ - '2' => 2, - 1 => '1', - ], - 4 => [ - 7, - 8, - 9, +$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"}', ]; - -$singleLine = [1 => 2]; From c531490b1f7bdccd7569cfd28d3b6faeed014f1a Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 08:39:08 +0200 Subject: [PATCH 40/60] Don't align equal statements, double arrow arrays or phpdoc comment tags --- docs/book/v2/coding-style-guide.md | 4 +- docs/book/v2/ruleset.md | 56 ++++++++---- src/ZendCodingStandard/ruleset.xml | 15 +++- test/expected-report.txt | 12 +-- test/fixable/commenting.php | 118 +++++++++++++++++++++++++ test/fixable/concatenation-spacing.php | 6 +- test/fixable/example-class.php | 16 +++- test/fixable/not-spacing.php | 2 +- test/fixable/semicolon-spacing.php | 2 +- test/fixable/statement-alignment.php | 16 ++++ test/fixed/array-indentation.php | 4 +- test/fixed/commenting.php | 112 +++++++++++++++++++++++ test/fixed/concatenation-spacing.php | 6 +- test/fixed/example-class.php | 6 +- test/fixed/new-with-parentheses.php | 8 +- test/fixed/not-spacing.php | 2 +- test/fixed/semicolon-spacing.php | 2 +- test/fixed/statement-alignment.php | 16 ++++ 18 files changed, 357 insertions(+), 46 deletions(-) create mode 100644 test/fixable/commenting.php create mode 100644 test/fixable/statement-alignment.php create mode 100644 test/fixed/commenting.php create mode 100644 test/fixed/statement-alignment.php diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index a76dcda6..eb37cdd8 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -78,10 +78,12 @@ $var = [ 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) -- Comments with single-line content should be written as one-liners. [*](ruleset.md#slevomatcodingstandardcommentingrequireonelinepropertydoccomment) +- 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) ## Declare Statements, Namespace, and Import Statements diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 3eecff17..ca0edbf6 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -169,26 +169,25 @@ echo $foo . 'baz'; ``` ### Generic.Formatting.MultipleStatementAlignment -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. +There should be one space on either side of an equals sign used to assign a value to a variable. -*Valid: Equal signs are aligned in related blocks.* +*Valid: Equal signs are surrounded by one space.* ```php bar(); $foo -> bar(); ``` +### Squiz.WhiteSpace.ObjectOperatorSpacing +There should be one space before and after an operators. + +*Valid: One space around the operator.* +```php + - + + @@ -158,7 +159,7 @@ - + @@ -327,6 +328,10 @@ + + + + @@ -373,6 +378,12 @@ + + + + + + diff --git a/test/expected-report.txt b/test/expected-report.txt index 07210a0c..4d4477ab 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -7,9 +7,10 @@ test/fixable/anonymous-classes.php 9 0 test/fixable/array-indentation.php 8 0 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 -test/fixable/concatenation-spacing.php 18 0 +test/fixable/commenting.php 9 0 +test/fixable/concatenation-spacing.php 16 0 test/fixable/EarlyReturn.php 5 0 -test/fixable/example-class.php 22 0 +test/fixable/example-class.php 29 0 test/fixable/extends-and-implements-multiline.php 10 0 test/fixable/extends-and-implements.php 5 0 test/fixable/forbidden-comments.php 4 0 @@ -18,20 +19,21 @@ test/fixable/LowCaseTypes.php 2 0 test/fixable/method-and-function-arguments.php 11 0 test/fixable/method-and-function-calls.php 14 0 test/fixable/namespaces-spacing.php 3 0 -test/fixable/new-with-parentheses.php 18 0 +test/fixable/new-with-parentheses.php 14 0 test/fixable/not-spacing.php 7 0 test/fixable/operators.php 7 0 test/fixable/return-type-on-methods.php 17 0 test/fixable/semicolon-spacing.php 3 0 +test/fixable/statement-alignment.php 18 0 test/fixable/test-case.php 4 0 test/fixable/traits-uses.php 10 0 test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 218 ERRORS AND 0 WARNINGS WERE FOUND IN 25 FILES +A TOTAL OF 246 ERRORS AND 0 WARNINGS WERE FOUND IN 27 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 192 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 213 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/commenting.php b/test/fixable/commenting.php new file mode 100644 index 00000000..53453dc2 --- /dev/null +++ b/test/fixable/commenting.php @@ -0,0 +1,118 @@ + 2]; -$singleLine2 = [ 'foo' => 'bar' ]; +$singleLine = [1 => 2]; +$singleLine2 = [ 'foo' => 'bar' ]; $serializedRequest = [ 'method' => 'POST', diff --git a/test/fixed/commenting.php b/test/fixed/commenting.php new file mode 100644 index 00000000..adb93849 --- /dev/null +++ b/test/fixed/commenting.php @@ -0,0 +1,112 @@ +foo = $foo; - $this->bar = $bar; - $this->baz = $baz; + $this->foo = $foo; + $this->bar = $bar; + $this->baz = $baz; $this->baxBax = $baxBax; } diff --git a/test/fixed/new-with-parentheses.php b/test/fixed/new-with-parentheses.php index 6e81bbe6..17ddde8f 100644 --- a/test/fixed/new-with-parentheses.php +++ b/test/fixed/new-with-parentheses.php @@ -5,14 +5,14 @@ $foo = new DateTimeImmutable(); $barClassName = 'Bar'; -$bar = new $barClassName(); +$bar = new $barClassName(); $classNamesInArray = ['Baz']; -$foo = new $classNamesInArray[0](); +$foo = new $classNamesInArray[0](); -$classNamesInObject = new stdClass(); +$classNamesInObject = new stdClass(); $classNamesInObject->foo = 'Foo'; -$foo = new $classNamesInObject->foo(); +$foo = new $classNamesInObject->foo(); $whitespaceBetweenClassNameAndParentheses = new stdClass(); diff --git a/test/fixed/not-spacing.php b/test/fixed/not-spacing.php index 0284b52a..b0942488 100644 --- a/test/fixed/not-spacing.php +++ b/test/fixed/not-spacing.php @@ -9,7 +9,7 @@ } elseif (! $test === 0) { echo 0; } else { - echo -1; + echo 2; } while (! true) { diff --git a/test/fixed/semicolon-spacing.php b/test/fixed/semicolon-spacing.php index fa6c43ab..3b198671 100644 --- a/test/fixed/semicolon-spacing.php +++ b/test/fixed/semicolon-spacing.php @@ -2,7 +2,7 @@ declare(strict_types=1); -echo -1; +echo 1; echo 'foo'; diff --git a/test/fixed/statement-alignment.php b/test/fixed/statement-alignment.php new file mode 100644 index 00000000..52d7fa97 --- /dev/null +++ b/test/fixed/statement-alignment.php @@ -0,0 +1,16 @@ + Date: Tue, 11 Sep 2018 08:44:23 +0200 Subject: [PATCH 41/60] Remove early exit rule as it is overly aggressive when "fixing" the code --- docs/book/v2/coding-style-guide.md | 2 -- docs/book/v2/ruleset.md | 26 --------------- src/ZendCodingStandard/ruleset.xml | 2 -- test/expected-report.txt | 5 ++- test/fixable/EarlyReturn.php | 52 ------------------------------ test/fixed/EarlyReturn.php | 52 ------------------------------ 6 files changed, 2 insertions(+), 137 deletions(-) delete mode 100644 test/fixable/EarlyReturn.php delete mode 100644 test/fixed/EarlyReturn.php diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index eb37cdd8..822e56d8 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -363,8 +363,6 @@ $instance = new class extends Foo implements - The opening PHP tag should be the first item in the file. [*](ruleset.md#genericphpcharacterbeforephpopeningtag) - Strings should not be concatenated together unless used in multiline for readability. [*](ruleset.md#genericstringsunnecessarystringconcat) - Loose `==` and `!=` comparison operators should not be used. Use `===` and `!==` instead. [*](ruleset.md#slevomatcodingstandardcontrolstructuresdisallowequaloperators) -- An early exit strategy should be used where possible to reduce the level of control structures. - [*](ruleset.md#slevomatcodingstandardcontrolstructuresearlyexit) - Language constructs must be used without parentheses where possible. [*](ruleset.md#slevomatcodingstandardcontrolstructureslanguageconstructwithparentheses) - Short list syntax `[...]` should be used instead of `list(...)`. [*](ruleset.md#slevomatcodingstandardphpshortlist) - Short form of type keywords must be used. i.e. `bool` instead of `boolean`, `int` instead of `integer`, etc. diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index ca0edbf6..6aa3a0b3 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -457,32 +457,6 @@ if ($a == $b || $c != $d) { } ``` -### SlevomatCodingStandard.ControlStructures.EarlyExit -An early exit strategy should be used where possible to reduce the level of control structures. - -*Valid: Exit early.* -```php - - - diff --git a/test/expected-report.txt b/test/expected-report.txt index 4d4477ab..c5ae8a56 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -9,7 +9,6 @@ test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/commenting.php 9 0 test/fixable/concatenation-spacing.php 16 0 -test/fixable/EarlyReturn.php 5 0 test/fixable/example-class.php 29 0 test/fixable/extends-and-implements-multiline.php 10 0 test/fixable/extends-and-implements.php 5 0 @@ -31,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 246 ERRORS AND 0 WARNINGS WERE FOUND IN 27 FILES +A TOTAL OF 241 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 213 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 208 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/EarlyReturn.php b/test/fixable/EarlyReturn.php deleted file mode 100644 index 04998cd5..00000000 --- a/test/fixable/EarlyReturn.php +++ /dev/null @@ -1,52 +0,0 @@ -isItem())) { - return 'There is an item that is not an item'; - } else { - continue; - } - } - - return null; - } - - public function baz() : string - { - if ($number > 0) { - return 'Number is grater then 0'; - } else { - exit; - } - } - - public function quoox() : bool - { - if (true === 'true') { - if (false === false) { - return true; - } - } else { - return false; - } - - return true; - } -} diff --git a/test/fixed/EarlyReturn.php b/test/fixed/EarlyReturn.php deleted file mode 100644 index da856545..00000000 --- a/test/fixed/EarlyReturn.php +++ /dev/null @@ -1,52 +0,0 @@ -isItem()) { - return 'There is an item that is not an item'; - } - - continue; - } - - return null; - } - - public function baz() : string - { - if ($number > 0) { - return 'Number is grater then 0'; - } - - exit; - } - - public function quoox() : bool - { - if (true !== 'true') { - return false; - } - - if (false === false) { - return true; - } - - return true; - } -} From a276b18df81731e862e7ff0059075326dd2d5939 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 08:49:52 +0200 Subject: [PATCH 42/60] Add references --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 9a63374b..3cdd64a7 100644 --- a/README.md +++ b/README.md @@ -63,3 +63,10 @@ For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/An ```bash $ composer cs-fix ``` + +## Reference + +- [Coding Standard Tutorial](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Coding-Standard-Tutorial) +- [Configuration Options](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options) +- [Customisable Sniff Properties](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties) +- [Slevomat Coding Standard](https://github.com/slevomat/coding-standard) From bf0d951f4dda2caa1936d739e074ea637fec9c8c Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 08:55:17 +0200 Subject: [PATCH 43/60] Update changelog with latest changes --- CHANGELOG.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e8390a..8b72b4ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,8 +28,6 @@ All notable changes to this project will be documented in this file, in reverse - All array values must be followed by a comma, including the last value. - Whitespace is not allowed 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 `global` keyword may not be used. - The `PHP_SAPI` constant must be used instead of the `php_sapi_name()` function. @@ -46,11 +44,13 @@ All notable changes to this project will be documented in this file, in reverse provide accurate information. - The asterisks in a doc comment should align, and there should be one space between the asterisk and tag. + - Comment tags `@param`, `@throws` and `@return` should not be aligned or + contain multiple spaces between the tag, type and description. - If a function throws any exceptions, they should be documented in `@throws` tags. - The `@var` tag may be used in inline comments to document the _Type_ of properties. - - Comments with single-line content should be written as one-liners. + - Single-line comments with a `@var` tag should be written as one-liners. - Shorthand scalar typehint variants must be used in docblocks. - Each PHP file should have a page level docblock with `@see`, `@copyright` and `@license`. The copyright date should only be adjusted if the file has @@ -97,8 +97,6 @@ All notable changes to this project will be documented in this file, in reverse readability. - Loose `==` and `!=` comparison operators should not be used. Use `===` and `!==` instead. - - An early exit strategy should be used where possible to reduce the level - of control structures. - Language constructs must be used without parentheses where possible. - Short list syntax `[...]` should be used instead of `list(...)`. - Short form of type keywords must be used. i.e. `bool` instead of From 3386b02298d3081f6c12e902c0fd20ce5ab01bb1 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 15:48:59 +0200 Subject: [PATCH 44/60] Update intro and readme --- README.md | 69 ++++++++++++++++++++++++++++++++++++++++++- docs/book/v2/intro.md | 45 ++++++++++++++++++++++++---- 2 files changed, 107 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3cdd64a7..8ca9125d 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,24 @@ The coding standard ruleset for Zend Framework components. +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. These are minimal specifications and don't address all factors, including things like: + +- whitespace around operators +- alignment of array keys and operators +- alignment of object operations +- how to format multi-line conditionals +- what and what not to import, and how +- etc. + +Contributors have different coding styles and so do the maintainers. During code reviews there are regularly +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: @@ -21,7 +39,7 @@ The coding standard ruleset for Zend Framework components. } ``` -3. Create file `phpcs.xml` on base path of your repository with content: +3. Create file `phpcs.xml` on base path of your repository with this content: ```xml @@ -64,9 +82,58 @@ For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/An $ composer cs-fix ``` +## Ignoring parts of a File + +> Note: Before PHP_CodeSniffer version 3.2.0, `// @codingStandardsIgnoreStart` and `// @codingStandardsIgnoreEnd` were +> used. These are deprecated and will be removed in PHP_CodeSniffer version 4.0. + +Disable parts of a file: +```php +$xmlPackage = new XMLPackage; +// phpcs:disable +$xmlPackage['error_code'] = get_default_error_code_value(); +$xmlPackage->send(); +// phpcs:enable +``` + +Disable a specific rule: +```php +// phpcs:disable Generic.Commenting.Todo.Found +$xmlPackage = new XMLPackage; +$xmlPackage['error_code'] = get_default_error_code_value(); +// TODO: Add an error message here. +$xmlPackage->send(); +// phpcs:enable +``` + +## Development + +> **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 +zend-coding-standard globally with composer: +```bash +$ composer global config repositories.zend-coding-standard vcs git@github.com:/zend-coding-standard.git +$ composer global require --dev zendframework/zend-coding-standard:dev- + +# For this to work, add this to your path: ~/.composer/vendor/bin +# Using `-s` prints the rules that triggered the errors so they can be reviewed easily. `-p` is for progress display. +$ phpcs -sp --standard=ZendCodingStandard src test +``` +Make sure you remove the global installation after testing from your global composer.json file!!! + +Documentation can be previewed locally by installing [MkDocs](https://www.mkdocs.org/#installation) and run +`mkdocs serve`. This will start a server where you can read the docs. + ## Reference +Rules can be added, excluded or tweaked locally, depending on your preferences. More information on how to do this can +be found here: + - [Coding Standard Tutorial](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Coding-Standard-Tutorial) - [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/intro.md b/docs/book/v2/intro.md index 4200c27b..7e19599f 100644 --- a/docs/book/v2/intro.md +++ b/docs/book/v2/intro.md @@ -1,8 +1,10 @@ # zend-coding-standard -This component provides the coding standard ruleset for Zend Framework components. +The coding standard ruleset for Zend Framework components. -PSR-1, PSR-2 and PSR-12 are _minimal_ sets and don't address a lot of factors, including things like: +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. These are minimal specifications and don't address all factors, including things like: - whitespace around operators - alignment of array keys and operators @@ -35,7 +37,7 @@ We will change these rules, and, when PSR-12 is finalized, adapt them. } ``` -3. Create file `phpcs.xml.dist` on base path of your repository with content: +3. Create file `phpcs.xml` on base path of your repository with this content: ```xml @@ -61,8 +63,8 @@ We will change these rules, and, when PSR-12 is finalized, adapt them. ``` -You can add your own rules or exclude rules. For a reference please see: -[PHP_CodeSniffer Annotated Ruleset](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-Ruleset) +You can add or exclude some locations in that file. +For a reference please see: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml ## Usage @@ -92,7 +94,7 @@ $xmlPackage->send(); // phpcs:enable ``` -Disable a specific rule +Disable a specific rule: ```php // phpcs:disable Generic.Commenting.Todo.Found $xmlPackage = new XMLPackage; @@ -101,3 +103,34 @@ $xmlPackage['error_code'] = get_default_error_code_value(); $xmlPackage->send(); // phpcs:enable ``` + +## Development + +> **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 +zend-coding-standard globally with composer: +```bash +$ composer global config repositories.zend-coding-standard vcs git@github.com:/zend-coding-standard.git +$ composer global require --dev zendframework/zend-coding-standard:dev- + +# For this to work, add this to your path: ~/.composer/vendor/bin +# Using `-s` prints the rules that triggered the errors so they can be reviewed easily. `-p` is for progress display. +$ phpcs -sp --standard=ZendCodingStandard src test +``` +Make sure you remove the global installation after testing from your global composer.json file!!! + +Documentation can be previewed locally by installing [MkDocs](https://www.mkdocs.org/#installation) and run +`mkdocs serve`. This will start a server where you can read the docs. + +## Reference + +Rules can be added, excluded or tweaked locally, depending on your preferences. More information on how to do this can +be found here: + +- [Coding Standard Tutorial](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Coding-Standard-Tutorial) +- [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) From 300e6134c6936bc80e252ceaf0d3ee8e1723a061 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 19:24:46 +0200 Subject: [PATCH 45/60] Fix creation of double trailing commas on specific arrays --- src/ZendCodingStandard/ruleset.xml | 17 +++++++++++++---- test/expected-report.txt | 6 +++--- test/fixable/array-indentation.php | 9 +++++++++ test/fixed/array-indentation.php | 11 +++++++++++ 4 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 687f5847..fd0a3654 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -13,7 +13,10 @@ - + + + + @@ -271,21 +274,27 @@ - + + + + + + - - + + + diff --git a/test/expected-report.txt b/test/expected-report.txt index c5ae8a56..9ba2e449 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,7 +4,7 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 8 0 +test/fixable/array-indentation.php 12 0 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/commenting.php 9 0 @@ -30,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 241 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES +A TOTAL OF 245 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 208 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 212 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixable/array-indentation.php b/test/fixable/array-indentation.php index fbf5794b..bb79d14d 100644 --- a/test/fixable/array-indentation.php +++ b/test/fixable/array-indentation.php @@ -31,3 +31,12 @@ ], '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', +]]; diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index a9e684ef..c05da8af 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -29,3 +29,14 @@ ], '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', + ], +]; From 61f3bc5e0f56d6ca4e7c126fcd4a794f29e85ba1 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 19:33:18 +0200 Subject: [PATCH 46/60] PSR-12: Force Unix LF (linefeed) line ending Rule: All PHP files MUST use the Unix LF (linefeed) line ending only. --- docs/book/v2/ruleset.md | 3 +++ src/ZendCodingStandard/ruleset.xml | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index 6aa3a0b3..ee190565 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -168,6 +168,9 @@ $foo = 'bar'; echo $foo . 'baz'; ``` +### Generic.Files.LineEndings +_PSR-12:_ All PHP files MUST use the Unix LF (linefeed) line ending only. + ### Generic.Formatting.MultipleStatementAlignment There should be one space on either side of an equals sign used to assign a value to a variable. diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index fd0a3654..74a82517 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -32,6 +32,12 @@ + + + + + + From ea3de201619e9ac96201f37ad6bd62e6b117fa26 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Tue, 11 Sep 2018 19:36:53 +0200 Subject: [PATCH 47/60] Allow global functions Caused warnings in zend-diactoros like: `Consider putting global function "parseCookieHeader" in a static class.` --- CHANGELOG.md | 1 - docs/book/v2/coding-style-guide.md | 1 - docs/book/v2/ruleset.md | 3 --- src/ZendCodingStandard/ruleset.xml | 2 -- 4 files changed, 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b72b4ce..2508c7df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,7 +108,6 @@ All notable changes to this project will be documented in this file, in reverse which is not used. - The `self` keyword should be used instead of the current class name, and should not have spaces around `::`. - - Global functions should not be used. - Static methods should not use `$this`. - Double quote strings may only be used if they contain variables. - Strings should not be enclosed in parentheses when being echoed. diff --git a/docs/book/v2/coding-style-guide.md b/docs/book/v2/coding-style-guide.md index 822e56d8..aa23087b 100644 --- a/docs/book/v2/coding-style-guide.md +++ b/docs/book/v2/coding-style-guide.md @@ -372,7 +372,6 @@ $instance = new class extends Foo implements - Variables should be returned directly instead of assigned to a variable which is not used. [*](ruleset.md#slevomatcodingstandardvariablesuselessvariable) - The `self` keyword should be used instead of the current class name, and should not have spaces around `::`. [*](ruleset.md#squizclassesselfmemberreference) -- Global functions should not be used. [*](ruleset.md#squizfunctionsglobalfunction) - Static methods should not use `$this`. [*](ruleset.md#squizscopestaticthisusage) - Double quote strings may only be used if they contain variables. [*](ruleset.md#squizstringsdoublequoteusage) - Strings should not be enclosed in parentheses when being echoed. [*](ruleset.md#squizstringsechoedstrings) diff --git a/docs/book/v2/ruleset.md b/docs/book/v2/ruleset.md index ee190565..b470c39e 100644 --- a/docs/book/v2/ruleset.md +++ b/docs/book/v2/ruleset.md @@ -983,9 +983,6 @@ There should be no multiple spaces between the tag, type and description. */ ``` -### Squiz.Functions.GlobalFunction -Global functions should not be used. - ### Squiz.Operators.ValidLogicalOperators The `&&` and `||` operators must be used instead of `AND` and `OR`. diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 74a82517..54f17502 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -351,8 +351,6 @@ - - From 53a7dcdb5402c0f0e7d416ca49fdd5709dfa716f Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 19 Sep 2018 16:02:56 +0200 Subject: [PATCH 48/60] Align comments, statements and arrays Doing open source while sitting on the backseat with 200 kmh on the Autobahn :) --- src/ZendCodingStandard/ruleset.xml | 8 +------- test/expected-report.txt | 16 ++++++++-------- test/fixed/array-indentation.php | 18 +++++++++--------- test/fixed/commenting.php | 14 +++++++------- test/fixed/concatenation-spacing.php | 2 +- test/fixed/example-class.php | 7 ++++--- test/fixed/new-with-parentheses.php | 8 ++++---- test/fixed/statement-alignment.php | 8 ++++---- 8 files changed, 38 insertions(+), 43 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 54f17502..a37119cd 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -42,7 +42,7 @@ - + @@ -290,8 +290,6 @@ - - @@ -341,10 +339,6 @@ - - - - diff --git a/test/expected-report.txt b/test/expected-report.txt index 9ba2e449..c69c19e3 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,21 +4,21 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 12 0 +test/fixable/array-indentation.php 27 0 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 -test/fixable/commenting.php 9 0 -test/fixable/concatenation-spacing.php 16 0 -test/fixable/example-class.php 29 0 +test/fixable/commenting.php 17 0 +test/fixable/concatenation-spacing.php 15 0 +test/fixable/example-class.php 26 0 test/fixable/extends-and-implements-multiline.php 10 0 test/fixable/extends-and-implements.php 5 0 test/fixable/forbidden-comments.php 4 0 -test/fixable/forbidden-functions.php 6 0 +test/fixable/forbidden-functions.php 9 0 test/fixable/LowCaseTypes.php 2 0 test/fixable/method-and-function-arguments.php 11 0 test/fixable/method-and-function-calls.php 14 0 test/fixable/namespaces-spacing.php 3 0 -test/fixable/new-with-parentheses.php 14 0 +test/fixable/new-with-parentheses.php 18 0 test/fixable/not-spacing.php 7 0 test/fixable/operators.php 7 0 test/fixable/return-type-on-methods.php 17 0 @@ -30,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 245 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES +A TOTAL OF 271 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 212 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 238 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index c05da8af..408ec45e 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -11,23 +11,23 @@ 5, ]; -$singleLine = [1 => 2]; -$singleLine2 = [ 'foo' => 'bar' ]; +$singleLine = [1 => 2]; +$singleLine2 = ['foo' => 'bar']; $serializedRequest = [ - 'method' => 'POST', - 'request_target' => '/foo/bar?baz=bat', - 'uri' => 'http://example.com/foo/bar?baz=bat', + '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'], + 'headers' => [ + 'Host' => ['example.com'], + 'Accept' => ['application/json'], 'X-Foo-Bar' => [ 'Baz', 'Bat', ], ], - 'body' => '{"test":"value"}', + 'body' => '{"test":"value"}', ]; // https://github.com/zendframework/zend-diactoros/blob/69dc20275fb8b9f7f8e05d556f6c0da5f36cac64/test/ServerRequestFactoryTest.php#L392-L398 diff --git a/test/fixed/commenting.php b/test/fixed/commenting.php index adb93849..db40a2b3 100644 --- a/test/fixed/commenting.php +++ b/test/fixed/commenting.php @@ -32,9 +32,9 @@ class Commenting private $uriString; /** - * @param string|resource|StreamInterface $body Stream identifier and/or actual stream resource - * @param int $status Status code for the response, if any. - * @param array $headers Headers for the response, if any. + * @param string|resource|StreamInterface $body Stream identifier and/or actual stream resource + * @param int $status Status code for the response, if any. + * @param array $headers Headers for the response, if any. * @throws Exception\InvalidArgumentException on any invalid element. */ public function __construct($body = 'php://memory', int $status = 200, array $headers = []) @@ -52,11 +52,11 @@ public function __construct($body = 'php://memory', int $status = 200, array $he * order to marshal the request URI and headers. * * @see fromServer() - * @param array $server $_SERVER superglobal - * @param array $query $_GET superglobal - * @param array $body $_POST superglobal + * @param array $server $_SERVER superglobal + * @param array $query $_GET superglobal + * @param array $body $_POST superglobal * @param array $cookies $_COOKIE superglobal - * @param array $files $_FILES superglobal + * @param array $files $_FILES superglobal * @return ServerRequest */ public static function fromGlobals( diff --git a/test/fixed/concatenation-spacing.php b/test/fixed/concatenation-spacing.php index 43850232..90b46036 100644 --- a/test/fixed/concatenation-spacing.php +++ b/test/fixed/concatenation-spacing.php @@ -11,7 +11,7 @@ $foo = 'foo'; $bar = 'bar'; -$string = $foo . $bar . 'baz' . 'quux' . $string; +$string = $foo . $bar . 'baz' . 'quux' . $string; $string .= $foo; $string .= $foo; $string .= $foo; diff --git a/test/fixed/example-class.php b/test/fixed/example-class.php index 6e35bbc2..a47c9907 100644 --- a/test/fixed/example-class.php +++ b/test/fixed/example-class.php @@ -38,9 +38,9 @@ class Example implements IteratorAggregate public function __construct(?int $foo = null, array $bar = [], bool $baz = false, $baxBax = 'unused') { - $this->foo = $foo; - $this->bar = $bar; - $this->baz = $baz; + $this->foo = $foo; + $this->bar = $bar; + $this->baz = $baz; $this->baxBax = $baxBax; } @@ -58,6 +58,7 @@ public function getFoo() : ?int public function getIterator() : array { assert($this->bar !== null); + return new ArrayIterator($this->bar); } diff --git a/test/fixed/new-with-parentheses.php b/test/fixed/new-with-parentheses.php index 17ddde8f..6e81bbe6 100644 --- a/test/fixed/new-with-parentheses.php +++ b/test/fixed/new-with-parentheses.php @@ -5,14 +5,14 @@ $foo = new DateTimeImmutable(); $barClassName = 'Bar'; -$bar = new $barClassName(); +$bar = new $barClassName(); $classNamesInArray = ['Baz']; -$foo = new $classNamesInArray[0](); +$foo = new $classNamesInArray[0](); -$classNamesInObject = new stdClass(); +$classNamesInObject = new stdClass(); $classNamesInObject->foo = 'Foo'; -$foo = new $classNamesInObject->foo(); +$foo = new $classNamesInObject->foo(); $whitespaceBetweenClassNameAndParentheses = new stdClass(); diff --git a/test/fixed/statement-alignment.php b/test/fixed/statement-alignment.php index 52d7fa97..018efa9e 100644 --- a/test/fixed/statement-alignment.php +++ b/test/fixed/statement-alignment.php @@ -2,15 +2,15 @@ declare(strict_types=1); -$shortVar = (1 + 2); +$shortVar = (1 + 2); $veryLongVarName = 'string'; -$value = (string) $value; +$value = (string) $value; $length = strlen($value); $string = ''; $headerNames[$normalized] = $header; -$headers[$header] = $value; +$headers[$header] = $value; $normalized = strtolower($header); -$original = $headerNames[$normalized]; +$original = $headerNames[$normalized]; From 850f481d17a49de9c94d96d7bfc7cbe305248d25 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 19 Sep 2018 16:16:57 +0200 Subject: [PATCH 49/60] Align array double arrows --- src/ZendCodingStandard/ruleset.xml | 2 -- test/expected-report.txt | 6 +++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index a37119cd..815cb773 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -288,8 +288,6 @@ - - diff --git a/test/expected-report.txt b/test/expected-report.txt index c69c19e3..99693d8f 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,7 +4,7 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 27 0 +test/fixable/array-indentation.php 34 0 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/commenting.php 17 0 @@ -30,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 271 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES +A TOTAL OF 278 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 238 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 245 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- From 5eaa798f049dba4be43572b412865ca7141b83f9 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 19 Sep 2018 16:22:36 +0200 Subject: [PATCH 50/60] Validate fixes before running tests --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 95d5cb2c..bd9d5fec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,8 +21,8 @@ script: stages: - Validate against schema - - Test - Validate fixes + - Test jobs: allow_failures: From 41d35b98bdbab11405252ba46ab638087f9d04f1 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Wed, 19 Sep 2018 16:24:39 +0200 Subject: [PATCH 51/60] Fix single arrow indention test --- test/fixed/array-indentation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index 408ec45e..5597fb35 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -12,7 +12,7 @@ ]; $singleLine = [1 => 2]; -$singleLine2 = ['foo' => 'bar']; +$singleLine2 = [ 'foo' => 'bar' ]; $serializedRequest = [ 'method' => 'POST', From 3974380803cba4b98425151ea7a5d539c74897da Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 20 Sep 2018 12:29:11 +0200 Subject: [PATCH 52/60] Reset array alignment and start from scratch Using Squiz, Slevomat, General rules or a combination of those doesn't work and it becomes a mess really fast. The WebimpressCodingStandard has better rules for this, however they need some improvements. --- README.md | 1 - composer.json | 3 ++- src/ZendCodingStandard/ruleset.xml | 31 ++++++------------------------ test/fixable/array-indentation.php | 23 ++++++++++++++-------- test/fixed/array-indentation.php | 11 +++++++++-- test/fixed/example-class.php | 1 - 6 files changed, 32 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 8ca9125d..5922b094 100644 --- a/README.md +++ b/README.md @@ -136,4 +136,3 @@ be found here: - [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 da23c181..85963ccf 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,8 @@ "php": "^7.1", "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", "slevomat/coding-standard": "^4.7.3", - "squizlabs/php_codesniffer": "^3.3.1" + "squizlabs/php_codesniffer": "^3.3.1", + "webimpress/coding-standard": "dev-master" }, "extra": { "branch-alias": { diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 815cb773..00d2f0a3 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -13,12 +13,14 @@ - - - - + + + + + + @@ -110,8 +112,6 @@ error - - @@ -279,25 +279,6 @@ - - - - - - - - - - - - - - - - - - - diff --git a/test/fixable/array-indentation.php b/test/fixable/array-indentation.php index bb79d14d..3118f7f1 100644 --- a/test/fixable/array-indentation.php +++ b/test/fixable/array-indentation.php @@ -11,6 +11,12 @@ 5, ]; +$bar = [ +'foo' => 1, + 'bar' => 2, + 'baz' => 3, +]; + $singleLine = [ 1 => 2, ]; @@ -22,21 +28,22 @@ 'uri' => 'http://example.com/foo/bar?baz=bat', 'protocol_version' => '1.1', 'headers' => [ - 'Host' => ['example.com'], - 'Accept' => ['application/json'], - 'X-Foo-Bar' => [ + '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', + 'tmp_name' => 'php://temp', + 'size' => 0, + 'error' => 0, + 'name' => 'foo.bar', + 'type' => 'text/plain', ]]; diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index 5597fb35..9fa74554 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -11,8 +11,14 @@ 5, ]; +$bar = [ + 'foo' => 1, + 'bar' => 2, + 'baz' => 3, +]; + $singleLine = [1 => 2]; -$singleLine2 = [ 'foo' => 'bar' ]; +$singleLine2 = ['foo' => 'bar']; $serializedRequest = [ 'method' => 'POST', @@ -27,7 +33,8 @@ 'Bat', ], ], - 'body' => '{"test":"value"}', + + 'body' => '{"test":"value"}', ]; // https://github.com/zendframework/zend-diactoros/blob/69dc20275fb8b9f7f8e05d556f6c0da5f36cac64/test/ServerRequestFactoryTest.php#L392-L398 diff --git a/test/fixed/example-class.php b/test/fixed/example-class.php index a47c9907..99512a56 100644 --- a/test/fixed/example-class.php +++ b/test/fixed/example-class.php @@ -58,7 +58,6 @@ public function getFoo() : ?int public function getIterator() : array { assert($this->bar !== null); - return new ArrayIterator($this->bar); } From 137dc8a6bd80ebf8f08ce62433658f5d208f5788 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 20 Sep 2018 13:04:44 +0200 Subject: [PATCH 53/60] Update slevomat/coding-standard requirement and add regression test for fixed issues --- composer.json | 2 +- test/fixable/new-with-parentheses.php | 6 ++++++ test/fixed/new-with-parentheses.php | 6 ++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 85963ccf..e87aa99f 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "require": { "php": "^7.1", "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", - "slevomat/coding-standard": "^4.7.3", + "slevomat/coding-standard": "^4.8.0", "squizlabs/php_codesniffer": "^3.3.1", "webimpress/coding-standard": "dev-master" }, diff --git a/test/fixable/new-with-parentheses.php b/test/fixable/new-with-parentheses.php index 56ee8ea9..5bdcbb0e 100644 --- a/test/fixable/new-with-parentheses.php +++ b/test/fixable/new-with-parentheses.php @@ -26,3 +26,9 @@ $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'); diff --git a/test/fixed/new-with-parentheses.php b/test/fixed/new-with-parentheses.php index 6e81bbe6..4684f85c 100644 --- a/test/fixed/new-with-parentheses.php +++ b/test/fixed/new-with-parentheses.php @@ -26,3 +26,9 @@ $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'); From 61f6b4b2d795d9b6097247d71bfb65c145999f1d Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Thu, 20 Sep 2018 16:57:15 +0200 Subject: [PATCH 54/60] Add test for constant aligning --- test/fixable/example-class.php | 2 ++ test/fixed/example-class.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/test/fixable/example-class.php b/test/fixable/example-class.php index 69c0dd00..70f746e1 100644 --- a/test/fixable/example-class.php +++ b/test/fixable/example-class.php @@ -15,6 +15,8 @@ class Example implements \IteratorAggregate { private const VERSION = \PHP_VERSION - (PHP_MINOR_VERSION * 100) - PHP_PATCH_VERSION; + public const ID = 'id'; + public const SKU = 'sku'; /** * @var null|int diff --git a/test/fixed/example-class.php b/test/fixed/example-class.php index 99512a56..dcfe0644 100644 --- a/test/fixed/example-class.php +++ b/test/fixed/example-class.php @@ -23,6 +23,8 @@ class Example implements IteratorAggregate { private const VERSION = PHP_VERSION - (PHP_MINOR_VERSION * 100) - PHP_PATCH_VERSION; + public const ID = 'id'; + public const SKU = 'sku'; /** @var null|int */ private $foo; From 5f2280dda700606b41151500e87251339cf46f75 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Fri, 21 Sep 2018 09:05:40 +0200 Subject: [PATCH 55/60] Align double arrows in multiline arrays --- src/ZendCodingStandard/ruleset.xml | 6 ++++++ test/fixable/array-indentation.php | 16 ++++++++++++++++ test/fixed/array-indentation.php | 21 ++++++++++++++++++++- 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 00d2f0a3..84270b03 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -16,6 +16,12 @@ + + + + + + diff --git a/test/fixable/array-indentation.php b/test/fixable/array-indentation.php index 3118f7f1..fd7811ca 100644 --- a/test/fixable/array-indentation.php +++ b/test/fixable/array-indentation.php @@ -47,3 +47,19 @@ '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/array-indentation.php b/test/fixed/array-indentation.php index 9fa74554..2b5ec6a4 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -17,7 +17,9 @@ 'baz' => 3, ]; -$singleLine = [1 => 2]; +$singleLine = [ + 1 => 2, +]; $singleLine2 = ['foo' => 'bar']; $serializedRequest = [ @@ -47,3 +49,20 @@ '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, + ], + ], +]; From a3d45d7319daa0d321988743a23ac5e92222bdc9 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Fri, 21 Sep 2018 09:08:10 +0200 Subject: [PATCH 56/60] Update expected errors report --- test/expected-report.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/expected-report.txt b/test/expected-report.txt index 99693d8f..35517cc9 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,19 +4,19 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 34 0 +test/fixable/array-indentation.php 38 1 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/commenting.php 17 0 test/fixable/concatenation-spacing.php 15 0 -test/fixable/example-class.php 26 0 +test/fixable/example-class.php 28 0 test/fixable/extends-and-implements-multiline.php 10 0 test/fixable/extends-and-implements.php 5 0 test/fixable/forbidden-comments.php 4 0 -test/fixable/forbidden-functions.php 9 0 +test/fixable/forbidden-functions.php 6 0 test/fixable/LowCaseTypes.php 2 0 test/fixable/method-and-function-arguments.php 11 0 -test/fixable/method-and-function-calls.php 14 0 +test/fixable/method-and-function-calls.php 13 0 test/fixable/namespaces-spacing.php 3 0 test/fixable/new-with-parentheses.php 18 0 test/fixable/not-spacing.php 7 0 @@ -30,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 278 ERRORS AND 0 WARNINGS WERE FOUND IN 26 FILES +A TOTAL OF 280 ERRORS AND 1 WARNING WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 245 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 248 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ---------------------------------------------------------------------- From 27b735fca2ade4deac593b5031716a54a9a437b6 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 6 Oct 2018 18:59:58 +0200 Subject: [PATCH 57/60] Require php_codesniffer 3.3.2 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index e87aa99f..024cd1b5 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "php": "^7.1", "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", "slevomat/coding-standard": "^4.8.0", - "squizlabs/php_codesniffer": "^3.3.1", + "squizlabs/php_codesniffer": "^3.3.2", "webimpress/coding-standard": "dev-master" }, "extra": { From 95213b5905ffc6f0b60a084c11b152f0c9f0f1a8 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 6 Oct 2018 19:18:41 +0200 Subject: [PATCH 58/60] Update array indentation tests --- test/fixable/array-indentation.php | 6 +++--- test/fixed/array-indentation.php | 13 ++++++------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/test/fixable/array-indentation.php b/test/fixable/array-indentation.php index fd7811ca..765756f8 100644 --- a/test/fixable/array-indentation.php +++ b/test/fixable/array-indentation.php @@ -54,12 +54,12 @@ '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\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, + App\Http\HomePageHandler::class => App\Http\HomePageHandlerFactory::class, + App\Http\StaticPageHandler::class => App\Http\StaticPageHandlerFactory::class, ], ], ]; diff --git a/test/fixed/array-indentation.php b/test/fixed/array-indentation.php index 2b5ec6a4..4ccaa3d8 100644 --- a/test/fixed/array-indentation.php +++ b/test/fixed/array-indentation.php @@ -50,19 +50,18 @@ ], ]; - // 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\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, + => App\Infrastructure\View\TemplateDefaultsMiddlewareFactory::class, + App\Http\HomePageHandler::class => App\Http\HomePageHandlerFactory::class, + App\Http\StaticPageHandler::class => App\Http\StaticPageHandlerFactory::class, ], ], ]; From 38a2deaf1ac04dbe6b9a4f1fc3b4f666096a6348 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 6 Oct 2018 19:29:23 +0200 Subject: [PATCH 59/60] Use new format to declare array properties --- src/ZendCodingStandard/ruleset.xml | 103 ++++++++++++----------------- 1 file changed, 42 insertions(+), 61 deletions(-) diff --git a/src/ZendCodingStandard/ruleset.xml b/src/ZendCodingStandard/ruleset.xml index 84270b03..43dd2702 100644 --- a/src/ZendCodingStandard/ruleset.xml +++ b/src/ZendCodingStandard/ruleset.xml @@ -50,7 +50,7 @@ - + @@ -73,32 +73,29 @@ - + + + + + + + + + + + + + + + + + + + + + + + @@ -142,19 +139,15 @@ - + + + + + + + + + @@ -162,14 +155,11 @@ - + + + + + @@ -246,18 +236,9 @@ - - - + + + @@ -371,7 +352,7 @@ - + From 7dc2f7862f468b78127353e951f15a6e1edb1d69 Mon Sep 17 00:00:00 2001 From: Geert Eltink Date: Sat, 6 Oct 2018 19:41:18 +0200 Subject: [PATCH 60/60] Update phpcs report --- test/expected-report.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/expected-report.txt b/test/expected-report.txt index 35517cc9..84d85f92 100644 --- a/test/expected-report.txt +++ b/test/expected-report.txt @@ -4,7 +4,7 @@ PHP CODE SNIFFER REPORT SUMMARY FILE ERRORS WARNINGS ---------------------------------------------------------------------- test/fixable/anonymous-classes.php 9 0 -test/fixable/array-indentation.php 38 1 +test/fixable/array-indentation.php 39 1 test/fixable/class-name-resolution.php 12 0 test/fixable/closures.php 19 0 test/fixable/commenting.php 17 0 @@ -30,9 +30,9 @@ test/fixable/UnusedVariables.php 1 0 test/fixable/useless-semicolon.php 2 0 test/fixable/visibility-declaration.php 1 0 ---------------------------------------------------------------------- -A TOTAL OF 280 ERRORS AND 1 WARNING WERE FOUND IN 26 FILES +A TOTAL OF 281 ERRORS AND 1 WARNING WERE FOUND IN 26 FILES ---------------------------------------------------------------------- -PHPCBF CAN FIX 248 OF THESE SNIFF VIOLATIONS AUTOMATICALLY +PHPCBF CAN FIX 249 OF THESE SNIFF VIOLATIONS AUTOMATICALLY ----------------------------------------------------------------------