38 Commits
0.2.1 ... 1.0.1

Author SHA1 Message Date
ca58c15e3f Prepare 1.0.1 release 2023-07-21 06:12:46 +02:00
e6bac9d44b Adjust comment_to_phpdoc fixer to exclude PHPStan error supression tags 2023-07-21 05:37:25 +02:00
7c4ed0f859 Prepare 1.0.0 release 2023-05-17 23:35:51 +02:00
ee30eaf4ad Update missing CHANGELOG entry 2023-05-17 23:21:40 +02:00
e86f8ed2cc Remove class_definition::space_before_parenthesis param to keep the same behavior as before 2023-05-17 23:21:05 +02:00
c794507936 Update rules 2023-05-17 23:01:23 +02:00
5373d05c91 Depend on a stable version of the erickskrauch/php-cs-fixer-custom-fixers 2023-05-17 20:08:37 +02:00
62932ec0f7 Resolves #16. Split repository and move all custom fixers to separate repository 2023-05-17 19:54:10 +02:00
84dd1184b8 Prepare 0.5.0 release 2023-04-08 21:37:10 +02:00
7d36ce912c Fixes #13. Implemented Ely\multiline_if_statement_braces fixer 2023-04-08 21:07:39 +02:00
e9ad4a94ab Fix Unreleased changelog link 2023-03-28 22:15:20 +02:00
6d572ae421 Add fixer to place promoted properties on a new line when there is more than 1 parameter 2023-03-24 01:13:24 +01:00
050dfe6399 Revisit BlackLineAroundClassBodyFixer 2023-03-24 00:40:48 +01:00
b85d0d5c01 Cover properties promotion cases for Ely\align_multiple_parameters fixer 2023-03-23 17:09:01 +01:00
5ae374f6cd Fix build shield 2023-03-23 03:44:14 +01:00
6956e0271e Fixes #12. Implemented Ely\align_multiline_parameters 2023-03-23 03:36:47 +01:00
4a4f556d7b Update LICENSE year 2023-03-22 20:41:26 +01:00
6e9d815a1f Fixes #9. Add space before next meaningful line of code and skip comments 2023-03-22 20:41:04 +01:00
22dcb418fb Update CHANGELOG 2023-03-22 20:39:19 +01:00
2d215dc761 Fixes #10. Don't count string interpolation as a scope beginning 2023-03-22 18:42:39 +01:00
6f14beec28 Fix PHPUnit configuration 2023-03-22 14:03:19 +01:00
de3a1f841c Fix GitHub Actions deprecation 2022-12-06 22:31:30 +01:00
243db94429 Prepare Readme 2022-12-06 22:27:18 +01:00
251ebc529c Fix fn spacing rule, upgrade to the latest PHP-CS-Fixer and add a new rule 2022-12-06 22:21:28 +01:00
2db4af0180 Adjust rules after production projects checks 2022-10-12 21:58:27 +02:00
f2d1b6164e Set correct minimal version of PHP-CS-Fixer 2022-10-06 04:34:17 +02:00
793b156b17 Remove const param from class_attributes_separation rule to allow grouping of consts with the same context 2022-10-05 17:10:11 +02:00
c3a8b869d1 Fix README.md 2022-09-22 18:02:19 +02:00
137a89820c Merge branch 'php-cs-fixer-3' 2022-09-20 02:51:02 +02:00
d4092c6e92 Add composer normalizer 2022-09-20 02:50:21 +02:00
5865b15c88 Introduce Github Actions as a replacement of the Travis CI 2022-09-20 02:50:21 +02:00
18806e41e2 Migrate to PHP-CS-Fixer 3. Upgrade custom rules. Upgrade ruleset. 2022-09-20 02:50:21 +02:00
ad25ce897b Allow PHP 8.0. There is no release since I need to go over the new rules, drop the old PHP versions and reimplement the CI 2021-05-13 16:18:57 +02:00
f327f14347 Bump minimal php-cs-fixer version to 2.15.0. Add additional rules. 2019-10-12 01:17:25 +03:00
bb403214d9 disable self_accessor rule 2019-04-30 17:30:49 +03:00
2140798d0a Update CHANGELOG 2019-02-23 20:29:08 +03:00
d8eafd4505 First set of fixes 2019-02-23 02:26:51 +03:00
714a38d53e Bump minimal php-cs-fixer version to 2.13.0. Add additional rules. 2019-02-23 02:05:20 +03:00
25 changed files with 2378 additions and 4426 deletions

51
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,51 @@
name: CI
on:
push:
pull_request:
jobs:
Build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-versions:
- '7.4'
- '8.0'
- '8.1'
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
extensions: ctype, mbstring
tools: cs2pr
- name: Get Composer's cache directory
id: composer-cache-path
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache Composer dependencies
uses: actions/cache@v3
id: composer-cache
with:
path: ${{ steps.composer-cache-path.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install dependencies
run: composer install
- name: Normalize composer.json
if: matrix.php-versions == '8.1'
run: composer normalize --dry-run
- name: PHP-CS-Fixer
if: matrix.php-versions == '8.1'
run: vendor/bin/php-cs-fixer fix --dry-run --format=checkstyle | cs2pr

7
.gitignore vendored
View File

@ -1,3 +1,4 @@
/vendor/
.php_cs
.php_cs.cache
vendor
dist
.php-cs-fixer
.php-cs-fixer.cache

12
.php-cs-fixer.dist.php Normal file
View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
$finder = PhpCsFixer\Finder::create()
->in(__DIR__);
return Ely\CS\Config::create([
// Disable "parameters" and "match" to keep compatibility with PHP 7.4
'trailing_comma_in_multiline' => [
'elements' => ['arrays', 'arguments'],
],
])->setFinder($finder);

View File

@ -1,9 +0,0 @@
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__);
return \Ely\CS\Config::create([
// Disable it for const, 'cause ^7.0 compatibility
'visibility_required' => ['property', 'method'],
])->setFinder($finder);

View File

@ -1,35 +0,0 @@
language: php
php:
- '7.0'
- '7.1'
- '7.2'
- '7.3'
cache:
directories:
- vendor
- $HOME/.composer
env:
global:
- DEFAULT_COMPOSER_FLAGS="--optimize-autoloader --no-interaction --no-progress"
before_script:
- composer global show hirak/prestissimo -q || travis_retry composer global require $DEFAULT_COMPOSER_FLAGS hirak/prestissimo
- composer install --no-interaction
stages:
- Static Code Analysis
- Test
jobs:
include:
- stage: Static Code Analysis
php: 7.3
script:
- vendor/bin/php-cs-fixer fix -v --dry-run
allow_failures:
- php: nightly
script:
- vendor/bin/phpunit

View File

@ -6,6 +6,143 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [Unreleased]
## [1.0.1] - 2023-07-21
### Changed
- `comment_to_phpdoc` no longer fixes PHPStan error suppression and the `todo` tag.
## [1.0.0] - 2023-05-17
### Added
- `single_space_around_construct` fixer.
- `no_extra_blank_lines` fixer.
### Changed
- `friendsofphp/php-cs-fixer` version bumped to `^3.16`.
### Removed
- Iss #16: All custom fixers have been moved to the [separate repository](https://github.com/erickskrauch/php-cs-fixer-custom-fixers).
- Usage of the `braces_fixer` since it's deprecated.
## [0.5.0] - 2023-04-08
### Added
- Enh #12: Implemented `Ely\align_multiline_parameters` fixer.
- Enh #13: Implemented `Ely\multiline_if_statement_braces` fixer.
- Enabled `Ely\align_multiline_parameters` for Ely.by codestyle in `['types' => false, 'defaults' => false]` mode.
- Enabled `Ely\multiline_if_statement_braces` for Ely.by codestyle in `['keep_on_own_line' => true]` mode.
- Enabled
[`PhpCsFixerCustomFixers/multiline_promoted_properties`](https://github.com/kubawerlos/php-cs-fixer-custom-fixers#multilinepromotedpropertiesfixer)
fixer for Ely.by codestyle in 2+ parameters mode.
### Fixed
- Bug #10: `Ely/blank_line_before_return` don't treat interpolation curly bracket as beginning of the scope.
- Bug #9: `Ely/line_break_after_statements` add space before next meaningful line of code and skip comments.
## [0.4.0] - 2022-12-06
### Added
- `simple_to_complex_string_variable` fixer.
- `single_trait_insert_per_statement` fixer.
- `native_function_type_declaration_casing` fixer.
- `php_unit_mock_short_will_return` fixer.
- `php_unit_dedicate_assert_internal_type` fixer.
- `php_unit_no_expectation_annotation` fixer.
- `modernize_strpos` fixer.
- `no_multiple_statements_per_line` fixer.
- `octal_notation` fixer.
- `class_reference_name_casing` fixer.
- `integer_literal_case` fixer.
- `no_unset_cast` fixer.
- `no_null_property_initialization` fixer.
- `comment_to_phpdoc` fixer.
- `multiline_comment_opening_closing` fixer.
- `no_empty_comment` fixer.
- `single_line_comment_spacing` fixer.
- `single_line_comment_style` fixer.
- `empty_loop_body` fixer.
- `empty_loop_condition` fixer.
- `switch_continue_to_break` fixer.
- `yoda_style` fixer in non-yoda mode.
- `function_typehint_space` fixer.
- `lambda_not_used_import` fixer.
- `no_unneeded_import_alias` fixer.
- `combine_consecutive_unsets` fixer.
- `declare_parentheses` fixer.
- `clean_namespace` fixer.
- `assign_null_coalescing_to_coalesce_equal` fixer.
- `no_useless_nullsafe_operator` fixer.
- `operator_linebreak` fixer.
- `php_unit_fqcn_annotation` fixer.
- `php_unit_test_case_static_method_calls` fixer.
- `simplified_null_return` fixer.
- `no_empty_statement` fixer.
- `no_singleline_whitespace_before_semicolons` fixer.
- `semicolon_after_instruction` fixer.
- `types_spaces` fixer.
- `no_trailing_comma_in_singleline` fixer.
- `no_useless_concat_operator` fixer.
### Changed
- `friendsofphp/php-cs-fixer` version bumped to `^3`.
- `braces` fixer now enables rule `allow_single_line_anonymous_class_with_empty_body`.
- `class_attributes_separation` fixer now fixes `const` in the `only_if_meta` mode.
### Removed
- `Ely/new_with_braces` since all its functionality is now included in the original fixer.
- `self_accessor` fixer because it leads to errors in interfaces, that returns self.
## [0.3.0] - 2019-02-23
### Added
- `array_indentation` fixer.
- `combine_consecutive_issets` fixer.
- `combine_nested_dirname` fixer.
- `dir_constant` fixer.
- `ereg_to_preg` fixer.
- `explicit_string_variable` fixer.
- `implode_call` fixer.
- `is_null` fixer.
- `list_syntax` fixer.
- `logical_operators` fixer.
- `lowercase_cast` fixer.
- `lowercase_static_reference` fixer.
- `magic_constant_casing` fixer.
- `magic_method_casing` fixer.
- `multiline_whitespace_before_semicolons` fixer.
- `native_function_casing` fixer.
- `no_alternative_syntax` fixer.
- `no_homoglyph_names` fixer.
- `no_leading_import_slash` fixer.
- `no_leading_namespace_whitespace` fixer.
- `no_mixed_echo_print` fixer.
- `no_multiline_whitespace_around_double_arrow` fixer.
- `no_php4_constructor` fixer.
- `no_spaces_around_offset` fixer.
- `no_superfluous_elseif` fixer.
- `no_unneeded_control_parentheses` fixer.
- `no_useless_return` fixer.
- `php_unit_construct` fixer.
- `php_unit_expectation` fixer.
- `php_unit_method_casing` fixer.
- `php_unit_mock` fixer.
- `php_unit_namespaced` fixer.
- `php_unit_set_up_tear_down_visibility` fixer.
- `php_unit_strict` fixer.
- `pow_to_exponentiation` fixer.
- `psr4` fixer.
- `return_assignment` fixer.
- `random_api_migration` fixer.
- `self_accessor` fixer.
- `set_type_to_cast` fixer.
- `short_scalar_cast` fixer.
- `space_after_semicolon` fixer.
- `standardize_increment` fixer.
- `standardize_not_equals` fixer.
- `trim_array_spaces` fixer.
- `unary_operator_spaces` fixer.
### Changed
- `friendsofphp/php-cs-fixer` version bumped to `^2.13.0`.
### Fixed
- `ordered_imports` now has fixed order of import types.
## [0.2.1] - 2019-02-22
### Fixed
- Compatibility with the `friendsofphp/php-cs-fixer` version 2.13.3 and above.
@ -28,5 +165,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
- First release
[Unreleased]: https://github.com/olivierlacan/keep-a-changelog/compare/0.2.0...HEAD
[Unreleased]: https://github.com/elyby/php-code-style/compare/1.0.1...HEAD
[1.0.1]: https://github.com/elyby/php-code-style/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/elyby/php-code-style/compare/0.5.0...1.0.0
[0.5.0]: https://github.com/elyby/php-code-style/compare/0.4.0...0.5.0
[0.4.0]: https://github.com/elyby/php-code-style/compare/0.3.0...0.4.0
[0.3.0]: https://github.com/elyby/php-code-style/compare/0.2.1...0.3.0
[0.2.1]: https://github.com/elyby/php-code-style/compare/0.2.0...0.2.1
[0.2.0]: https://github.com/elyby/php-code-style/compare/0.1.0...0.2.0

View File

@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Ely.by (http://ely.by)
Copyright 2023 Ely.by (https://ely.by)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

162
README.md
View File

@ -1,7 +1,6 @@
# Ely.by PHP-CS-Fixer rules
Set of PHP-CS-Fixer rules used in development of Ely.by PHP projects. It's suited for PHP 7.1 and above.
You can use it as a ready-made set of rules or [just some of them](#using-our-fixers).
Set of PHP-CS-Fixer rules used in development of Ely.by PHP projects. It's suited for PHP 7.4 and above.
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Total Downloads][ico-downloads]][link-downloads]
@ -17,7 +16,7 @@ First of all install Ely.by PHP-CS-Fixer rules via composer with
composer require --dev friendsofphp/php-cs-fixer ely/php-code-style
```
Then create file `.php_cs` with following contents:
Then create a file `.php-cs-fixer.php` with the following contents:
```php
<?php
@ -43,12 +42,14 @@ vendor/bin/php-cs-fixer fix
### Configuration
You can pass a custom set of rules to the `\Ely\CS\Config::create()` call. For example, it can be used to validate a
project with PHP 7.0 compatibility:
project with PHP 7.4 compatibility:
```php
<?php
return \Ely\CS\Config::create([
'visibility_required' => ['property', 'method'],
'trailing_comma_in_multiline' => [
'elements' => ['arrays', 'arguments'],
],
])->setFinder($finder);
```
@ -76,12 +77,15 @@ class Foo extends Bar implements FooInterface {
private const SAMPLE_1 = 123;
private const SAMPLE_2 = 321;
public $field1;
public Typed $field1;
public $field2;
public function sampleFunction(int $a, int $b = null): array {
if ($a === $b) {
public function sampleFunction(
int $a,
private readonly int $b = null,
): array {
if ($a === $this->b) {
$result = bar();
} else {
$result = BazClass::bar($this->field1, $this->field2);
@ -89,7 +93,7 @@ class Foo extends Bar implements FooInterface {
return $result;
}
public function setToNull(): self {
$this->field1 = null;
return $this;
@ -154,141 +158,21 @@ class Foo extends Bar implements FooInterface {
echo 'the next statement is here';
```
## Using our fixers
First of all, you must install Ely.by PHP-CS-Fixer package as described in the [installation chapter](#installation).
After that you can enable our custom fixers with `registerCustomFixers` method:
```php
<?php
// Your Finder configuration
return \PhpCsFixer\Config::create()
->registerCustomFixers(new \Ely\CS\Fixers());
```
And then you'll be able to use our custom rules.
### `Ely/blank_line_around_class_body`
Ensure that a class body contains one blank line after its definition and before its end:
```diff
--- Original
+++ New
@@ @@
<?php
class Test {
+
public function func() {
$obj = new class extends Foo {
+
public $prop;
+
}
}
+
}
```
**Configuration:**
* `apply_to_anonymous_classes` - should this fixer be applied to anonymous classes? If it is set to `false`, than
anonymous classes will be fixed to don't have empty lines around body. **Default**: `true`.
* `blank_lines_count` - adjusts an amount of the blank lines. **Default**: `1`.
### `Ely/blank_line_before_return`
This is extended version of the original `blank_line_before_statement` fixer. It applies only to `return` statements
and only in cases, when on the current nesting level more than one statements.
```diff
--- Original
+++ New
@@ @@
<?php
public function foo() {
$a = 'this';
$b = 'is';
+
return "$a $b awesome";
}
public function bar() {
$this->foo();
return 'okay';
}
```
### `Ely/line_break_after_statements`
Ensures that there is one blank line above the next statements: `if`, `switch`, `for`, `foreach`, `while`
and `do-while`.
```diff
--- Original
+++ New
@@ @@
<?php
$a = 123;
if ($a === 123) {
// Do something here
}
+
$b = [1, 2, 3];
foreach ($b as $number) {
if ($number === 3) {
echo 'it is three!';
}
}
+
$c = 'next statement';
```
### `Ely/new_with_braces`
This is the extended version of the original `new_with_braces` fixer. It allows you to remove braces around
an anonymous class declaration in a case when said class constructor doesn't contain any arguments.
```diff
--- Original
+++ New
@@ @@
<?php
-$a = new Foo;
+$a = new Foo();
-$b = new class() extends Foo {};
+$b = new class extends Foo {};
```
**Configuration:**
* `remove_for_anonymous_classes` - if its set to `true`, then braces for anonymous classes without constructor
arguments will be removed. **Default**: `false`.
### `Ely/remove_class_name_method_usages` (Yii2)
Replaces Yii2 [`BaseObject::className()`](https://github.com/yiisoft/yii2/blob/e53fc0ded1/framework/base/BaseObject.php#L84)
usages with native `::class` keyword, introduced in PHP 5.5.
```diff
--- Original
+++ New
@@ @@
<?php
use common\models\User;
* There MUST be no alignment around multiline function parameters.
- $className = User::className();
+ $className = User::class;
```
```php
<?php
function foo(
string $input,
int $key = 0,
): void {}
```
[ico-version]: https://img.shields.io/packagist/v/ely/php-code-style.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-Apache-green.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/ely/php-code-style.svg?style=flat-square
[ico-build-status]: https://img.shields.io/travis/elyby/php-code-style/master.svg?style=flat-square
[ico-build-status]: https://img.shields.io/github/actions/workflow/status/elyby/php-code-style/ci.yml?branch=master&style=flat-square
[link-packagist]: https://packagist.org/packages/ely/php-code-style
[link-contributors]: ../../contributors
[link-downloads]: https://packagist.org/packages/ely/php-code-style/stats
[link-build-status]: https://travis-ci.org/elyby/php-code-style
[link-build-status]: https://github.com/elyby/php-code-style/actions

View File

@ -1,8 +1,12 @@
{
"name": "ely/php-code-style",
"description": "Set of PHP-CS-Fixer rules used in the development of Ely.by PHP projects",
"keywords": ["php-cs-fixer", "code style"],
"homepage": "https://github.com/elyby/php-code-style",
"license": "Apache-2.0",
"type": "library",
"keywords": [
"php-cs-fixer",
"code style"
],
"authors": [
{
"name": "Ely.by team",
@ -13,28 +17,29 @@
"email": "erickskrauch@ely.by"
}
],
"license": "Apache-2.0",
"type": "library",
"homepage": "https://github.com/elyby/php-code-style",
"require": {
"php": "^7.0",
"friendsofphp/php-cs-fixer": "^2.12.2"
"php": "^7.4 || ^8.0",
"erickskrauch/php-cs-fixer-custom-fixers": "^1.0.1",
"friendsofphp/php-cs-fixer": "^3.16",
"kubawerlos/php-cs-fixer-custom-fixers": "^3.13",
"symfony/polyfill-php80": "^1.15"
},
"require-dev": {
"phpunit/phpunit": "^6.5.1"
"ergebnis/composer-normalize": "^2.28"
},
"autoload": {
"psr-4": {
"Ely\\CS\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Ely\\CS\\Test\\": "tests/"
}
},
"config": {
"platform": {
"php": "7.0.8"
}
"allow-plugins": {
"ergebnis/composer-normalize": true
},
"preferred-install": {
"friendsofphp/php-cs-fixer": "source"
},
"sort-packages": true
}
}

3642
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestSize="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
bootstrap="./vendor/autoload.php"
colors="true"
columns="max"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
verbose="true"
>
<testsuites>
<testsuite>
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
<php>
<ini name="zend.enable_gc" value="0"/>
<ini name="memory_limit" value="1G"/>
</php>
</phpunit>

View File

@ -3,14 +3,18 @@ declare(strict_types=1);
namespace Ely\CS;
use ErickSkrauch\PhpCsFixer\Fixers as ErickSkrauchFixers;
use PhpCsFixer\Config as PhpCsFixerConfig;
use PhpCsFixer\ConfigInterface as PhpCsFixerConfigInterface;
use PhpCsFixerCustomFixers\Fixers as KubawerlosFixers;
class Config {
final class Config {
public static function create(array $overwrittenRules = []): PhpCsFixerConfig {
return PhpCsFixerConfig::create()
public static function create(array $overwrittenRules = []): PhpCsFixerConfigInterface {
return (new PhpCsFixerConfig())
->setRiskyAllowed(true)
->registerCustomFixers(new Fixers())
->registerCustomFixers(new ErickSkrauchFixers())
->registerCustomFixers(new KubawerlosFixers())
->setRules(Rules::create($overwrittenRules));
}

View File

@ -1,13 +0,0 @@
<?php
namespace Ely\CS\Fixer;
abstract class AbstractFixer extends \PhpCsFixer\AbstractFixer {
/**
* {@inheritdoc}
*/
public function getName() {
return sprintf('Ely/%s', parent::getName());
}
}

View File

@ -1,123 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Fixer\LanguageConstruct;
use Ely\CS\Fixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use SplFileInfo;
/**
* Replaces Yii2 BaseObject::className() usages with native ::class keyword, introduced in PHP 5.5.
*
* @author ErickSkrauch <erickskrauch@ely.by>
*/
final class RemoveClassNameMethodUsagesFixer extends AbstractFixer {
/**
* @inheritdoc
*/
public function getDefinition() {
return new FixerDefinition(
'Converts Yii2 `BaseObject::className()` method usage into `::class` keyword.',
[
new CodeSample(
'<?php
use Foo\Bar\Baz;
$className = Baz::className();
'
),
]
);
}
/**
* @inheritdoc
*/
public function isCandidate(Tokens $tokens) {
return $tokens->isTokenKindFound(T_STRING);
}
/**
* {@inheritdoc}
*/
public function isRisky() {
return true;
}
/**
* {@inheritdoc}
*/
protected function applyFix(SplFileInfo $file, Tokens $tokens) {
for ($index = $tokens->count() - 4; $index > 0; --$index) {
$candidate = $this->getReplaceCandidate($tokens, $index);
if ($candidate === null) {
continue;
}
$this->fixClassNameMethodUsage(
$tokens,
$index,
$candidate[0], // brace open
$candidate[1] // brace close
);
}
}
/**
* @param Tokens $tokens
* @param int $index
*
* @return null|array
*/
private function getReplaceCandidate(Tokens $tokens, $index) {
if (!$tokens[$index]->isGivenKind(T_STRING)) {
return null;
}
$braceOpenIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$braceOpenIndex]->equals('(')) {
return null;
}
$braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex);
if (!$tokens[$braceCloseIndex]->equals(')')) {
return null;
}
$doubleColon = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$doubleColon]->isGivenKind([T_DOUBLE_COLON])) {
return null;
}
$methodName = $tokens[$index]->getContent();
if ($methodName !== 'className') {
return null;
}
return [
$braceOpenIndex,
$braceCloseIndex,
];
}
/**
* @param Tokens $tokens
* @param int $index
* @param int $braceOpenIndex
* @param int $braceCloseIndex
*/
private function fixClassNameMethodUsage(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($braceOpenIndex);
$tokens->clearAt($index);
$tokens->insertAt($index, new Token([CT::T_CLASS_CONSTANT, 'class']));
}
}

View File

@ -1,179 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Fixer\Operator;
use Ely\CS\Fixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* This is the extended version of the original new_with_braces fixer.
* It allows you to remove braces around an anonymous class declaration in a case
* when said class constructor doesn't contain any arguments.
*
* @url https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/5c5de791ab/src/Fixer/Operator/NewWithBracesFixer.php
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*/
final class NewWithBracesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface {
/**
* {@inheritdoc}
*/
public function getDefinition() {
return new FixerDefinition(
'All instances created with new keyword must be followed by braces.',
[
new CodeSample("<?php \$x = new X;\n"),
]
);
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens) {
return $tokens->isTokenKindFound(T_NEW);
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens) {
static $nextTokenKinds = null;
if ($nextTokenKinds === null) {
$nextTokenKinds = [
'?',
';',
',',
'(',
')',
'[',
']',
':',
'<',
'>',
'+',
'-',
'*',
'/',
'%',
'&',
'^',
'|',
[T_CLASS],
[T_IS_SMALLER_OR_EQUAL],
[T_IS_GREATER_OR_EQUAL],
[T_IS_EQUAL],
[T_IS_NOT_EQUAL],
[T_IS_IDENTICAL],
[T_IS_NOT_IDENTICAL],
[T_CLOSE_TAG],
[T_LOGICAL_AND],
[T_LOGICAL_OR],
[T_LOGICAL_XOR],
[T_BOOLEAN_AND],
[T_BOOLEAN_OR],
[T_SL],
[T_SR],
[T_INSTANCEOF],
[T_AS],
[T_DOUBLE_ARROW],
[T_POW],
[CT::T_ARRAY_SQUARE_BRACE_OPEN],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_BRACE_CLASS_INSTANTIATION_OPEN],
[CT::T_BRACE_CLASS_INSTANTIATION_CLOSE],
];
if (defined('T_SPACESHIP')) {
$nextTokenKinds[] = [T_SPACESHIP];
}
}
for ($index = $tokens->count() - 3; $index > 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_NEW)) {
continue;
}
$nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds);
$nextToken = $tokens[$nextIndex];
// new anonymous class definition
if ($nextToken->isGivenKind(T_CLASS)) {
if ($this->configuration['remove_for_anonymous_classes']) {
$nextTokenIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextNextTokenIndex = $tokens->getNextMeaningfulToken($nextTokenIndex);
if ($tokens[$nextTokenIndex]->equals('(') && $tokens[$nextNextTokenIndex]->equals(')')) {
$this->removeBracesAfter($tokens, $nextIndex);
}
} else {
if (!$tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals('(')) {
$this->insertBracesAfter($tokens, $nextIndex);
}
}
continue;
}
// entrance into array index syntax - need to look for exit
while ($nextToken->equals('[')) {
$nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $nextIndex) + 1;
$nextToken = $tokens[$nextIndex];
}
// new statement has a gap in it - advance to the next token
if ($nextToken->isWhitespace()) {
$nextIndex = $tokens->getNextNonWhitespace($nextIndex);
$nextToken = $tokens[$nextIndex];
}
// new statement with () - nothing to do
if ($nextToken->equals('(')) {
continue;
}
$this->insertBracesAfter($tokens, $tokens->getPrevMeaningfulToken($nextIndex));
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition() {
return new FixerConfigurationResolver([
(new FixerOptionBuilder('remove_for_anonymous_classes', 'when enabled will remove braces around an anonymous class declaration in a case when constructor doesn\'t contain any arguments'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* @param Tokens $tokens
* @param int $index
*/
private function insertBracesAfter(Tokens $tokens, $index) {
$tokens->insertAt(++$index, [new Token('('), new Token(')')]);
}
/**
* @param Tokens $tokens
* @param int $index
*/
private function removeBracesAfter(Tokens $tokens, int $index) {
$tokens->clearRange(
$tokens->getNextTokenOfKind($index, ['(']),
$tokens->getNextTokenOfKind($index, [')'])
);
}
}

View File

@ -1,151 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Fixer\Whitespace;
use Ely\CS\Fixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* This is copy of the PR https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/3688
*
* @author ErickSkrauch <erickskrauch@ely.by>
*/
final class BlankLineAroundClassBodyFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface {
/**
* {@inheritdoc}
*/
public function getDefinition() {
return new FixerDefinition(
'Ensure that class body contains one blank line after class definition and before its end.',
[
new CodeSample(
'<?php
class Sample
{
protected function foo()
{
}
}
'
),
new CodeSample(
'<?php
new class extends Foo {
protected function foo()
{
}
};
',
['apply_to_anonymous_classes' => false]
),
new CodeSample(
'<?php
new class extends Foo {
protected function foo()
{
}
};
',
['apply_to_anonymous_classes' => true]
),
]
);
}
/**
* {@inheritdoc}
*/
public function getPriority() {
// should be run after the BracesFixer
return -26;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens) {
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens) {
$analyzer = new TokensAnalyzer($tokens);
foreach ($tokens as $index => $token) {
if (!$token->isClassy()) {
continue;
}
$countLines = $this->configuration['blank_lines_count'];
if (!$this->configuration['apply_to_anonymous_classes'] && $analyzer->isAnonymousClass($index)) {
$countLines = 0;
}
$startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']);
if ($tokens[$startBraceIndex + 1]->isWhitespace()) {
$nextStatementIndex = $tokens->getNextMeaningfulToken($startBraceIndex);
// Traits should be placed right after a class opening brace,
if ($tokens[$nextStatementIndex]->getContent() !== 'use') {
$this->fixBlankLines($tokens, $startBraceIndex + 1, $countLines);
}
}
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex);
if ($tokens[$endBraceIndex - 1]->isWhitespace()) {
$this->fixBlankLines($tokens, $endBraceIndex - 1, $countLines);
}
}
}
/**
* {@inheritdoc}
*/
protected function createConfigurationDefinition() {
return new FixerConfigurationResolver([
(new FixerOptionBuilder('blank_lines_count', 'adjusts an amount of the blank lines.'))
->setAllowedTypes(['int'])
->setDefault(1)
->getOption(),
(new FixerOptionBuilder('apply_to_anonymous_classes', 'whether this fixer should be applied to anonymous classes.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
/**
* Cleanup a whitespace token.
*
* @param Tokens $tokens
* @param int $index
* @param int $countLines
*/
private function fixBlankLines(Tokens $tokens, $index, $countLines) {
$content = $tokens[$index]->getContent();
// Apply fix only in the case when the count lines do not equals to expected
if (substr_count($content, "\n") === $countLines + 1) {
return;
}
// The final bit of the whitespace must be the next statement's indentation
Preg::matchAll('/[^\n\r]+[\r\n]*/', $content, $matches);
$lines = $matches[0];
$eol = $this->whitespacesConfig->getLineEnding();
$tokens[$index] = new Token([T_WHITESPACE, str_repeat($eol, $countLines + 1) . end($lines)]);
}
}

View File

@ -1,103 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Fixer\Whitespace;
use Ely\CS\Fixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use SplFileInfo;
/**
* This is extended version of the original `blank_line_before_statement` fixer.
* It applies only to `return` statements and only in cases, when on the current nesting level more than one statements.
*
* @url https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/5c5de791ab/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Andreas Möller <am@localheinz.com>
* @author SpacePossum
*/
final class BlankLineBeforeReturnFixer extends AbstractFixer implements WhitespacesAwareFixerInterface {
/**
* {@inheritdoc}
*/
public function getDefinition() {
return new FixerDefinition(
'An empty line feed should precede a return statement.',
[new CodeSample("<?php\nfunction A()\n{\n echo 1;\n return 1;\n}\n")]
);
}
/**
* @inheritdoc
*/
public function isCandidate(Tokens $tokens) {
return $tokens->isTokenKindFound(T_RETURN);
}
/**
* {@inheritdoc}
*/
public function getPriority() {
// should be run after NoUselessReturnFixer, ClassDefinitionFixer and BracesFixer
return -26;
}
/**
* @inheritdoc
*/
protected function applyFix(SplFileInfo $file, Tokens $tokens) {
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(T_RETURN)) {
continue;
}
$eol = $this->whitespacesConfig->getLineEnding();
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
if (!$prevNonWhitespaceToken->equalsAny([';', '}'])) {
continue;
}
$prevIndex = $index - 1;
$prevToken = $tokens[$prevIndex];
if ($prevToken->isWhitespace()) {
$countParts = substr_count($prevToken->getContent(), "\n");
if ($countParts === 0) {
$tokens[$prevIndex] = new Token([T_WHITESPACE, rtrim($prevToken->getContent(), " \t") . $eol . $eol]);
} elseif ($countParts === 1) {
$backwardIndex = $prevIndex;
do {
if (--$backwardIndex < 0) {
break;
}
$backwardToken = $tokens[$backwardIndex];
if ($backwardToken->getContent() === '{') {
break;
}
if ($backwardToken->isWhitespace()) {
$countParts += substr_count($backwardToken->getContent(), "\n");
}
} while ($countParts < 3);
if ($countParts !== 2) {
$tokens[$prevIndex] = new Token([T_WHITESPACE, $eol . $prevToken->getContent()]);
}
}
} else {
$tokens->insertAt($index, new Token([T_WHITESPACE, $eol . $eol]));
++$index;
++$limit;
}
}
}
}

View File

@ -1,178 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Fixer\Whitespace;
use Ely\CS\Fixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use SplFileInfo;
/**
* This is rewritten version of the original fixer created by @PedroTroller with improved cases validation and
* targeted to the PHP-CS-Fixer 2.11 version.
*
* @url https://github.com/PedroTroller/PhpCSFixer-Custom-Fixers/blob/affdf99f51/src/PedroTroller/CS/Fixer/CodingStyle/LineBreakBetweenStatementsFixer.php
*
* @author ErickSkrauch <erickskrauch@ely.by>
*/
final class LineBreakAfterStatementsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface {
/**
* There is no 'do', 'cause the processing of the 'while' also includes do {} while (); construction
*/
const STATEMENTS = [
T_IF,
T_SWITCH,
T_FOR,
T_FOREACH,
T_WHILE,
];
/**
* @inheritdoc
*/
public function getDefinition() {
return new FixerDefinition(
'Ensures that there is one blank line above the control statements',
[
new CodeSample(
'<?php
class Foo
{
/**
* @return null
*/
public function foo() {
do {
// ...
} while (true);
foreach (["foo", "bar"] as $str) {
// ...
}
if (true === false) {
// ...
}
foreach (["foo", "bar"] as $str) {
if ($str === "foo") {
// smth
}
}
while (true) {
// ...
}
switch("123") {
case "123":
break;
}
$a = "next statement";
}
}
'
),
]
);
}
/**
* @inheritdoc
*/
public function isCandidate(Tokens $tokens) {
return $tokens->isAnyTokenKindsFound(self::STATEMENTS);
}
/**
* {@inheritdoc}
*/
public function getPriority() {
// for the best result should be run after the BracesFixer
return -26;
}
protected function applyFix(SplFileInfo $file, Tokens $tokens) {
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(self::STATEMENTS)) {
continue;
}
$endStatementIndex = $this->findStatementEnd($tokens, $index);
$nextStatementIndex = $tokens->getNextNonWhitespace($endStatementIndex);
if ($nextStatementIndex === null) {
continue;
}
if ($tokens[$nextStatementIndex]->equals('}')) {
$this->fixBlankLines($tokens, $endStatementIndex + 1, 0);
continue;
}
$this->fixBlankLines($tokens, $endStatementIndex + 1, 1);
}
}
private function fixBlankLines(Tokens $tokens, $index, $countLines) {
$content = $tokens[$index]->getContent();
// Apply fix only in the case when the count lines do not equals to expected
if (substr_count($content, "\n") === $countLines + 1) {
return;
}
// The final bit of the whitespace must be the next statement's indentation
Preg::matchAll('/[^\n\r]+[\r\n]*/', $content, $matches);
$lines = $matches[0];
$eol = $this->whitespacesConfig->getLineEnding();
$tokens[$index] = new Token([T_WHITESPACE, str_repeat($eol, $countLines + 1) . end($lines)]);
}
private function findStatementEnd(Tokens $tokens, int $index): int {
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
if ($nextToken->equals('(')) {
$parenthesisEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
$possibleBeginBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
} else {
$possibleBeginBraceIndex = $nextIndex;
}
// `do {} while ();`
if ($tokens[$index]->isGivenKind(T_WHILE) && $tokens[$possibleBeginBraceIndex]->equals(';')) {
return $possibleBeginBraceIndex;
}
$possibleBeginBrace = $tokens[$possibleBeginBraceIndex];
if ($possibleBeginBrace->equals('{')) {
$blockEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $possibleBeginBraceIndex);
} else {
$blockEnd = $tokens->getNextTokenOfKind($possibleBeginBraceIndex, [';']);
}
$nextStatementIndex = $tokens->getNextMeaningfulToken($blockEnd);
if ($nextStatementIndex === null) {
return $blockEnd;
}
// `if () {} elseif {}`
if ($tokens[$nextStatementIndex]->isGivenKind(T_ELSEIF)) {
return $this->findStatementEnd($tokens, $nextStatementIndex);
}
// `if () {} else if {}` or simple `if () {} else {}`
if ($tokens[$nextStatementIndex]->isGivenKind(T_ELSE)) {
$nextNextStatementIndex = $tokens->getNextMeaningfulToken($nextStatementIndex);
if ($tokens[$nextNextStatementIndex]->isGivenKind(T_IF)) {
return $this->findStatementEnd($tokens, $nextNextStatementIndex);
}
return $this->findStatementEnd($tokens, $nextStatementIndex);
}
return $blockEnd;
}
}

View File

@ -1,39 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS;
use ArrayIterator;
use IteratorAggregate;
use PhpCsFixer\Finder;
use PhpCsFixer\Fixer\FixerInterface;
use ReflectionClass;
use Traversable;
class Fixers implements IteratorAggregate {
public function getIterator(): Traversable {
$finder = new Finder();
$finder->in(__DIR__ . '/Fixer')->name('*.php');
$classes = [];
foreach ($finder as $file) {
$class = '\\Ely\\CS' . str_replace('/', '\\', mb_substr($file->getPathname(), mb_strlen(__DIR__), -4));
if (!class_exists($class)) {
continue;
}
/** @noinspection PhpUnhandledExceptionInspection */
$rfl = new ReflectionClass($class);
if (!$rfl->implementsInterface(FixerInterface::class) || $rfl->isAbstract()) {
continue;
}
$classes[] = $class;
}
return new ArrayIterator(array_map(function($class) {
return new $class();
}, $classes));
}
}

View File

@ -3,76 +3,263 @@ declare(strict_types=1);
namespace Ely\CS;
class Rules {
private static $rules = [
'@PSR2' => true,
'array_syntax' => [
'syntax' => 'short',
],
'binary_operator_spaces' => true,
'braces' => [
'position_after_functions_and_oop_constructs' => 'same',
],
'cast_spaces' => [
'space' => 'none',
],
'class_attributes_separation' => [
'elements' => ['method', 'property'],
],
'compact_nullable_typehint' => true,
'concat_space' => [
'spacing' => 'one',
],
'declare_equal_normalize' => true,
'function_declaration' => [
'closure_function_spacing' => 'none',
],
'function_to_constant' => true,
'include' => true,
'linebreak_after_opening_tag' => true,
'method_chaining_indentation' => true,
'modernize_types_casting' => true,
'no_short_bool_cast' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_unneeded_final_method' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'non_printable_character' => [
'use_escape_sequences_in_strings' => true,
],
'object_operator_without_whitespace' => true,
'ordered_class_elements' => true,
'ordered_imports' => true,
'random_api_migration' => true,
'return_type_declaration' => [
'space_before' => 'none',
],
'single_quote' => true,
'strict_comparison' => true,
'ternary_operator_spaces' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline_array' => true,
'visibility_required' => [
'elements' => ['property', 'method', 'const'],
],
'whitespace_after_comma_in_array' => true,
// Our custom or extended fixers
'Ely/blank_line_around_class_body' => [
'apply_to_anonymous_classes' => false,
],
'Ely/blank_line_before_return' => true,
'Ely/line_break_after_statements' => true,
'Ely/new_with_braces' => [
'remove_for_anonymous_classes' => true,
],
'Ely/remove_class_name_method_usages' => true,
];
final class Rules {
public static function create(array $overwrittenRules = []): array {
return array_merge(self::$rules, $overwrittenRules);
return array_merge([
'@PSR2' => true,
// Alias
'ereg_to_preg' => true,
'modernize_strpos' => PHP_MAJOR_VERSION >= 8,
'no_mixed_echo_print' => true,
'pow_to_exponentiation' => true,
'random_api_migration' => [
'replacements' => [
'getrandmax' => 'mt_getrandmax',
'rand' => 'random_int',
'srand' => 'mt_srand',
],
],
'set_type_to_cast' => true,
// Array Notation
'array_syntax' => [
'syntax' => 'short',
],
'no_multiline_whitespace_around_double_arrow' => true,
'no_whitespace_before_comma_in_array' => true,
'normalize_index_brace' => true,
'trim_array_spaces' => true,
'whitespace_after_comma_in_array' => true,
// Basic
'curly_braces_position' => [
'functions_opening_brace' => 'same_line',
'classes_opening_brace' => 'same_line',
],
'no_trailing_comma_in_singleline' => true,
'non_printable_character' => [
'use_escape_sequences_in_strings' => true,
],
'octal_notation' => PHP_MAJOR_VERSION >= 8 && PHP_MINOR_VERSION >= 1,
'psr_autoloading' => true,
// Casing
'class_reference_name_casing' => true,
'integer_literal_case' => true,
'lowercase_static_reference' => true,
'magic_constant_casing' => true,
'magic_method_casing' => true,
'native_function_casing' => true,
'native_function_type_declaration_casing' => true,
// Cast Notation
'cast_spaces' => [
'space' => 'none',
],
'lowercase_cast' => true,
'modernize_types_casting' => true,
'no_short_bool_cast' => true,
'no_unset_cast' => true,
'short_scalar_cast' => true,
// Class Notation
'class_attributes_separation' => [
'elements' => [
'method' => 'one',
'property' => 'one',
],
],
'class_definition' => [
'single_item_single_line' => true,
'inline_constructor_arguments' => false,
],
'no_null_property_initialization' => true,
'no_php4_constructor' => true,
'no_unneeded_final_method' => true,
'ordered_class_elements' => true,
'single_trait_insert_per_statement' => true,
'visibility_required' => true,
// Comment
'comment_to_phpdoc' => [
'ignored_tags' => [
'todo',
// https://phpstan.org/user-guide/ignoring-errors
'phpstan-ignore',
'phpstan-ignore-line',
'phpstan-ignore-next-line',
],
],
'multiline_comment_opening_closing' => true,
'no_empty_comment' => true,
'single_line_comment_spacing' => true,
'single_line_comment_style' => true,
// Control Structure
'empty_loop_body' => true,
'empty_loop_condition' => true,
'include' => true,
'no_alternative_syntax' => true,
'no_superfluous_elseif' => true,
'no_unneeded_control_parentheses' => true,
'no_useless_else' => true,
'switch_continue_to_break' => true,
'trailing_comma_in_multiline' => [
'elements' => PHP_MAJOR_VERSION >= 8
? ['arrays', 'arguments', 'parameters', 'match']
: ['arrays', 'arguments'],
],
'yoda_style' => [
'equal' => false,
'identical' => false,
'less_and_greater' => false,
],
// Function Notation
'combine_nested_dirname' => true,
'function_declaration' => [
'closure_function_spacing' => 'none',
'closure_fn_spacing' => 'none',
],
'function_typehint_space' => true,
'implode_call' => true,
'lambda_not_used_import' => true,
'return_type_declaration' => true,
// Import
'no_leading_import_slash' => true,
'no_unneeded_import_alias' => true,
'no_unused_imports' => true,
'ordered_imports' => [
'imports_order' => ['class', 'function', 'const'],
],
// Language Construct
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'declare_equal_normalize' => true,
'declare_parentheses' => true,
'dir_constant' => true,
'function_to_constant' => true,
'is_null' => true,
'single_space_around_construct' => true,
// List Notation
'list_syntax' => true,
// Namespace Notation
'clean_namespace' => true,
'no_leading_namespace_whitespace' => true,
// Naming
'no_homoglyph_names' => true,
// Operator
'assign_null_coalescing_to_coalesce_equal' => true,
'binary_operator_spaces' => true,
'concat_space' => [
'spacing' => 'one',
],
'logical_operators' => true,
'new_with_braces' => [
'anonymous_class' => false,
],
'no_useless_concat_operator' => true,
'no_useless_nullsafe_operator' => true,
'object_operator_without_whitespace' => true,
'operator_linebreak' => true,
'standardize_increment' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'ternary_to_null_coalescing' => true,
'unary_operator_spaces' => true,
// PHP Tag
'linebreak_after_opening_tag' => true,
// PHPUnit
'php_unit_construct' => true,
'php_unit_dedicate_assert_internal_type' => true,
'php_unit_expectation' => true,
'php_unit_fqcn_annotation' => true,
'php_unit_method_casing' => true,
'php_unit_mock' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_namespaced' => true,
'php_unit_no_expectation_annotation' => true,
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_strict' => true,
'php_unit_test_case_static_method_calls' => [
'call_type' => 'this',
],
// Return Notation
'no_useless_return' => true,
'return_assignment' => true,
'simplified_null_return' => true,
// Semicolon
'multiline_whitespace_before_semicolons' => true,
'no_empty_statement' => true,
'no_singleline_whitespace_before_semicolons' => true,
'semicolon_after_instruction' => true,
'space_after_semicolon' => true,
// Strict
'strict_comparison' => true,
// String notation
'explicit_string_variable' => true,
'simple_to_complex_string_variable' => true,
'single_quote' => true,
// Whitespace
'array_indentation' => true,
'compact_nullable_typehint' => true,
'method_chaining_indentation' => true,
'no_extra_blank_lines' => [
'tokens' => [
'attribute',
'break',
'case',
'continue',
'curly_brace_block',
'default',
'extra',
'parenthesis_brace_block',
'return',
'square_brace_block',
'switch',
'throw',
'use',
],
],
'no_spaces_around_offset' => true,
'no_whitespace_in_blank_line' => true,
'types_spaces' => [
'space_multiple_catch' => 'none',
],
// kubawerlos fixers
'PhpCsFixerCustomFixers/multiline_promoted_properties' => [
'minimum_number_of_parameters' => 2,
],
// Our custom or extended fixers
'ErickSkrauch/align_multiline_parameters' => [
'variables' => false,
'defaults' => false,
],
'ErickSkrauch/blank_line_around_class_body' => [
'apply_to_anonymous_classes' => false,
],
'ErickSkrauch/blank_line_before_return' => true,
'ErickSkrauch/line_break_after_statements' => true,
'ErickSkrauch/multiline_if_statement_braces' => true,
'ErickSkrauch/remove_class_name_method_usages' => true,
], $overwrittenRules);
}
}

View File

@ -1,67 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Test\Fixer\Operator;
use Ely\CS\Fixer\LanguageConstruct\RemoveClassNameMethodUsagesFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
/**
* @covers \Ely\CS\Fixer\LanguageConstruct\RemoveClassNameMethodUsagesFixer
*/
class RemoveClassNameMethodUsagesFixerTest extends AbstractFixerTestCase {
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideFixCases
*/
public function testFix($expected, $input = null) {
$this->doTest($expected, $input);
}
public function provideFixCases() {
return [
[
'<?php echo className();',
],
[
'<?php
use Foo\Bar\Baz;
$exceptionString = Baz::classname();
',
],
[
'<?php
use Foo\Bar\Baz;
$className = Baz::class;
',
'<?php
use Foo\Bar\Baz;
$className = Baz::className();
',
],
[
'<?php
use Foo\Bar\Baz;
$exceptionString = "The class should be instance of " . Baz::class . " and nothing else";
',
'<?php
use Foo\Bar\Baz;
$exceptionString = "The class should be instance of " . Baz::className() . " and nothing else";
',
],
];
}
protected function createFixer() {
return new RemoveClassNameMethodUsagesFixer();
}
}

View File

@ -1,319 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Test\Fixer\Operator;
use Ely\CS\Fixer\Operator\NewWithBracesFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
/**
* Original file copied from:
* @url https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/5c5de791ab/tests/Fixer/Operator/NewWithBracesFixerTest.php
*
* @covers \Ely\CS\Fixer\Operator\NewWithBracesFixer
*/
class NewWithBracesFixerTest extends AbstractFixerTestCase {
private static $removeForAnonymousClasses = ['remove_for_anonymous_classes' => true];
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideFixCases
*/
public function testFix($expected, $input = null) {
$this->doTest($expected, $input);
}
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideFix70Cases
* @requires PHP 7.0
*/
public function testFix70($expected, $input = null, array $configuration = null) {
if ($configuration !== null) {
$this->fixer->configure($configuration);
}
$this->doTest($expected, $input);
}
public function provideFixCases() {
return [
[
'<?php class A { public function B(){ $static = new static(new \SplFileInfo(__FILE__)); }}',
],
[
'<?php $static = new self(new \SplFileInfo(__FILE__));',
],
[
'<?php $x = new X/**/ /**/ /**//**//**/ /**//**/ (/**/ /**/ /**//**//**/ /**//**/)/**/ /**/ /**//**//**/ /**//**/;/**/ /**/ /**//**//**/ /**//**/',
],
[
'<?php $x = new X();',
'<?php $x = new X;',
],
[
'<?php $y = new Y() ;',
'<?php $y = new Y ;',
],
[
'<?php $x = new Z() /**/;//',
'<?php $x = new Z /**/;//',
],
[
'<?php $foo = new $foo();',
'<?php $foo = new $foo;',
],
[
'<?php $xyz = new X(new Y(new Z()));',
'<?php $xyz = new X(new Y(new Z));',
],
[
'<?php $foo = (new $bar())->foo;',
'<?php $foo = (new $bar)->foo;',
],
[
'<?php $foo = (new $bar((new Foo())->bar))->foo;',
'<?php $foo = (new $bar((new Foo)->bar))->foo;',
],
[
'<?php $self = new self();',
'<?php $self = new self;',
],
[
'<?php $static = new static();',
'<?php $static = new static;',
],
[
'<?php $a = array( "key" => new DateTime(), );',
'<?php $a = array( "key" => new DateTime, );',
],
[
'<?php $a = array( "key" => new DateTime() );',
'<?php $a = array( "key" => new DateTime );',
],
[
'<?php $a = new $b[$c]();',
'<?php $a = new $b[$c];',
],
[
'<?php $a = new $b[$c[$d ? foo() : bar("bar[...]") - 1]]();',
'<?php $a = new $b[$c[$d ? foo() : bar("bar[...]") - 1]];',
],
[
'<?php $a = new $b[\'class\']();',
'<?php $a = new $b[\'class\'];',
],
[
'<?php $a = new $b[\'class\'] ($foo[\'bar\']);',
],
[
'<?php $a = new $b[\'class\'] () ;',
],
[
'<?php $a = new $b[$c] ($hello[$world]) ;',
],
[
"<?php \$a = new \$b['class']()\r\n\t ;",
"<?php \$a = new \$b['class']\r\n\t ;",
],
[
'<?php $a = $b ? new DateTime() : $b;',
'<?php $a = $b ? new DateTime : $b;',
],
[
'<?php new self::$adapters[$name]["adapter"]();',
'<?php new self::$adapters[$name]["adapter"];',
],
[
'<?php $a = new \Exception()?> <?php echo 1;',
'<?php $a = new \Exception?> <?php echo 1;',
],
[
'<?php $b = new \StdClass() /**/?>',
'<?php $b = new \StdClass /**/?>',
],
[
'<?php $a = new Foo() instanceof Foo;',
'<?php $a = new Foo instanceof Foo;',
],
[
'<?php
$a = new Foo() + 1;
$a = new Foo() - 1;
$a = new Foo() * 1;
$a = new Foo() / 1;
$a = new Foo() % 1;
',
'<?php
$a = new Foo + 1;
$a = new Foo - 1;
$a = new Foo * 1;
$a = new Foo / 1;
$a = new Foo % 1;
',
],
[
'<?php
$a = new Foo() & 1;
$a = new Foo() | 1;
$a = new Foo() ^ 1;
$a = new Foo() << 1;
$a = new Foo() >> 1;
',
'<?php
$a = new Foo & 1;
$a = new Foo | 1;
$a = new Foo ^ 1;
$a = new Foo << 1;
$a = new Foo >> 1;
',
],
[
'<?php
$a = new Foo() and 1;
$a = new Foo() or 1;
$a = new Foo() xor 1;
$a = new Foo() && 1;
$a = new Foo() || 1;
',
'<?php
$a = new Foo and 1;
$a = new Foo or 1;
$a = new Foo xor 1;
$a = new Foo && 1;
$a = new Foo || 1;
',
],
[
'<?php
if (new DateTime() > $this->startDate) {}
if (new DateTime() >= $this->startDate) {}
if (new DateTime() < $this->startDate) {}
if (new DateTime() <= $this->startDate) {}
if (new DateTime() == $this->startDate) {}
if (new DateTime() != $this->startDate) {}
if (new DateTime() <> $this->startDate) {}
if (new DateTime() === $this->startDate) {}
if (new DateTime() !== $this->startDate) {}
',
'<?php
if (new DateTime > $this->startDate) {}
if (new DateTime >= $this->startDate) {}
if (new DateTime < $this->startDate) {}
if (new DateTime <= $this->startDate) {}
if (new DateTime == $this->startDate) {}
if (new DateTime != $this->startDate) {}
if (new DateTime <> $this->startDate) {}
if (new DateTime === $this->startDate) {}
if (new DateTime !== $this->startDate) {}
',
],
[
'<?php $a = new \stdClass() ? $b : $c;',
'<?php $a = new \stdClass ? $b : $c;',
],
[
'<?php foreach (new Collection() as $x) {}',
'<?php foreach (new Collection as $x) {}',
],
[
'<?php $a = [(string) new Foo() => 1];',
'<?php $a = [(string) new Foo => 1];',
],
[
'<?php $a = [ "key" => new DateTime(), ];',
'<?php $a = [ "key" => new DateTime, ];',
],
[
'<?php $a = [ "key" => new DateTime() ];',
'<?php $a = [ "key" => new DateTime ];',
],
[
'<?php
$a = new Foo() ** 1;
',
'<?php
$a = new Foo ** 1;
',
],
];
}
public function provideFix70Cases() {
return [
[
'<?php
$a = new Foo() <=> 1;
',
'<?php
$a = new Foo <=> 1;
',
],
[
'<?php
$a = new class() {use SomeTrait;};
$a = new class() implements Foo{};
$a = new class() /**/ extends Bar1{};
$a = new class() extends Bar2 implements Foo{};
$a = new class() extends Bar3 implements Foo, Foo2{};
$a = new class() {}?>
',
'<?php
$a = new class {use SomeTrait;};
$a = new class implements Foo{};
$a = new class /**/ extends Bar1{};
$a = new class extends Bar2 implements Foo{};
$a = new class extends Bar3 implements Foo, Foo2{};
$a = new class {}?>
',
],
[
'<?php
class A {
public function B() {
$static = new static(new class(){});
}
}
',
'<?php
class A {
public function B() {
$static = new static(new class{});
}
}
',
],
[
'<?php
$a = new class {use SomeTrait;};
$a = new class implements Foo{};
$a = new class /**/ extends Bar1{};
$a = new class extends Bar2 implements Foo{};
$a = new class extends Bar3 implements Foo, Foo2{};
$a = new class {};
$a = new class {};
',
'<?php
$a = new class() {use SomeTrait;};
$a = new class() implements Foo{};
$a = new class() /**/ extends Bar1{};
$a = new class() extends Bar2 implements Foo{};
$a = new class() extends Bar3 implements Foo, Foo2{};
$a = new class() {};
$a = new class( ) {};
',
self::$removeForAnonymousClasses,
],
];
}
protected function createFixer() {
return new NewWithBracesFixer();
}
}

View File

@ -1,364 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Test\Fixer\Whitespace;
use Ely\CS\Fixer\Whitespace\BlankLineAroundClassBodyFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
use PhpCsFixer\WhitespacesFixerConfig;
/**
* @author ErickSkrauch <erickskrauch@ely.by>
*
* @covers \Ely\CS\Fixer\Whitespace\BlankLineAroundClassBodyFixer
*/
final class BlankLineAroundClassBodyFixerTest extends AbstractFixerTestCase {
private static $configurationDoNotApplyForAnonymousClasses = ['apply_to_anonymous_classes' => false];
private static $configurationTwoEmptyLines = ['blank_lines_count' => 2];
/**
* @param string $expected
* @param null|string $input
* @param null|array $configuration
*
* @dataProvider provideFixCases
*/
public function testFix($expected, $input = null, array $configuration = null) {
if (null !== $configuration) {
$this->fixer->configure($configuration);
}
$this->doTest($expected, $input);
}
/**
* @param string $expected
* @param null|string $input
* @param array $configuration
*
* @dataProvider provideAnonymousClassesCases
* @requires PHP 7.0
*/
public function testFixAnonymousClasses($expected, $input = null, array $configuration = null) {
if (null !== $configuration) {
$this->fixer->configure($configuration);
}
$this->doTest($expected, $input);
}
public function provideFixCases() {
$cases = [];
$cases[] = [
'<?php
class Good
{
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
class Good
{
/**
* Also blank line before DocBlock
*/
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
/**
* Also blank line before DocBlock
*/
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
class Good
{
/**
* Too many whitespaces
*/
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
/**
* Too many whitespaces
*/
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
interface Good
{
/**
* Also blank line before DocBlock
*/
public function firstMethod();
}',
'<?php
interface Good
{
/**
* Also blank line before DocBlock
*/
public function firstMethod();
}',
];
$cases[] = [
'<?php
trait Good
{
/**
* Also no blank line before DocBlock
*/
public function firstMethod() {}
}',
'<?php
trait Good
{
/**
* Also no blank line before DocBlock
*/
public function firstMethod() {}
}',
];
$cases[] = [
'<?php
class Good
{
use Foo\bar;
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
use Foo\bar;
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
class Good
{
use Foo\bar;
use Foo\baz;
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
use Foo\bar;
use Foo\baz;
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
class Good
{
use Foo, Bar {
Bar::smallTalk insteadof A;
Foo::bigTalk insteadof B;
}
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
use Foo, Bar {
Bar::smallTalk insteadof A;
Foo::bigTalk insteadof B;
}
public function firstMethod()
{
//code here
}
}',
];
$cases[] = [
'<?php
class Good
{
public function firstMethod()
{
//code here
}
}',
'<?php
class Good
{
public function firstMethod()
{
//code here
}
}',
self::$configurationTwoEmptyLines,
];
// check if some fancy whitespaces aren't modified
$cases[] = [
'<?php
class Good
{public
function firstMethod()
{
//code here
}
}',
];
return $cases;
}
public function provideAnonymousClassesCases() {
$cases = [];
$cases[] = [
'<?php
$class = new class extends \Foo {
public $field;
public function firstMethod() {}
};',
'<?php
$class = new class extends \Foo {
public $field;
public function firstMethod() {}
};',
];
$cases[] = [
'<?php
$class = new class extends \Foo {
public $field;
public function firstMethod() {}
};',
'<?php
$class = new class extends \Foo {
public $field;
public function firstMethod() {}
};',
self::$configurationDoNotApplyForAnonymousClasses,
];
return $cases;
}
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideMessyWhitespacesCases
*/
public function testMessyWhitespaces($expected, $input = null) {
/** @var \PhpCsFixer\Fixer\WhitespacesAwareFixerInterface $fixer */
$fixer = $this->fixer;
$fixer->setWhitespacesConfig(new WhitespacesFixerConfig("\t", "\r\n"));
$this->doTest($expected, $input);
}
public function provideMessyWhitespacesCases() {
return [
[
"<?php\nclass Foo\n{\r\n\r\n public function bar() {}\r\n\r\n}",
"<?php\nclass Foo\n{\n public function bar() {}\n}",
],
[
"<?php\nclass Foo\n{\r\n\r\n public function bar() {}\r\n\r\n}",
"<?php\nclass Foo\n{\r\n\r\n\n\n public function bar() {}\n\n\n\n}",
],
];
}
protected function createFixer() {
return new BlankLineAroundClassBodyFixer();
}
}

View File

@ -1,223 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Test\Fixer\Whitespace;
use Ely\CS\Fixer\Whitespace\BlankLineBeforeReturnFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
use PhpCsFixer\WhitespacesFixerConfig;
/**
* Original file copied from:
* @url https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/5c5de791ab/tests/Fixer/Whitespace/BlankLineBeforeStatementFixerTest.php
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Andreas Möller <am@localheinz.com>
* @author SpacePossum
*
* @internal
*
* @property BlankLineBeforeReturnFixer $fixer
*
* @covers \Ely\CS\Fixer\Whitespace\BlankLineBeforeReturnFixer
*/
final class BlankLineBeforeReturnFixerTest extends AbstractFixerTestCase {
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideFixCases
*/
public function testFix($expected, $input = null) {
$this->doTest($expected, $input);
}
public function provideFixCases() {
$cases = [];
$cases[] = [
'$a = $a;
return $a;
',
];
$cases[] = [
'<?php
$a = $a;
return $a;',
'<?php
$a = $a; return $a;',
];
$cases[] = [
'<?php
$b = $b;
return $b;',
'<?php
$b = $b;return $b;',
];
$cases[] = [
'<?php
$c = $c;
return $c;',
'<?php
$c = $c;
return $c;',
];
$cases[] = [
'<?php
$d = $d;
return $d;',
'<?php
$d = $d;
return $d;',
];
$cases[] = [
'<?php
if (true) {
return 1;
}',
];
$cases[] = [
'<?php
if (true)
return 1;
',
];
$cases[] = [
'<?php
if (true) {
return 1;
} else {
return 2;
}',
];
$cases[] = [
'<?php
if (true)
return 1;
else
return 2;
',
];
$cases[] = [
'<?php
if (true) {
return 1;
} elseif (false) {
return 2;
}',
];
$cases[] = [
'<?php
if (true)
return 1;
elseif (false)
return 2;
',
];
$cases[] = [
'<?php
throw new Exception("return true;");',
];
$cases[] = [
'<?php
function foo()
{
// comment
return "foo";
}',
];
$cases[] = [
'<?php
function foo()
{
// comment
return "bar";
}',
];
$cases[] = [
'<?php
function foo()
{
// comment
return "bar";
}',
];
$cases[] = [
'<?php
function foo() {
$a = "a";
$b = "b";
return $a . $b;
}',
'<?php
function foo() {
$a = "a";
$b = "b";
return $a . $b;
}',
];
$cases[] = [
'<?php
function foo() {
$b = "b";
return $a . $b;
}',
];
$cases[] = [
'<?php
function foo() {
$a = "a";
return $a . "hello";
}
function bar() {
$b = "b";
return $b . "hello";
}
',
];
return $cases;
}
/**
* @param string $expected
* @param null|string $input
*
* @dataProvider provideMessyWhitespacesCases
*/
public function testMessyWhitespaces($expected, $input = null) {
$this->fixer->setWhitespacesConfig(new WhitespacesFixerConfig("\t", "\r\n"));
$this->doTest($expected, $input);
}
public function provideMessyWhitespacesCases() {
return [
[
"<?php\r\n\$a = \$a;\r\n\r\nreturn \$a;",
"<?php\r\n\$a = \$a; return \$a;",
],
[
"<?php\r\n\$b = \$b;\r\n\r\nreturn \$b;",
"<?php\r\n\$b = \$b;return \$b;",
],
[
"<?php\r\n\$c = \$c;\r\n\r\nreturn \$c;",
"<?php\r\n\$c = \$c;\r\nreturn \$c;",
],
];
}
protected function createFixer() {
return new BlankLineBeforeReturnFixer();
}
}

View File

@ -1,571 +0,0 @@
<?php
declare(strict_types=1);
namespace Ely\CS\Test\Fixer\Whitespace;
use Ely\CS\Fixer\Whitespace\LineBreakAfterStatementsFixer;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
/**
* @covers \Ely\CS\Fixer\Whitespace\LineBreakAfterStatementsFixer
*
* @author ErickSkrauch <erickskrauch@ely.by>
*/
class LineBreakAfterStatementsFixerTest extends AbstractFixerTestCase {
/**
* @param string $expected
* @param string $input
*
* @dataProvider provideFixCases
*/
public function testFix(string $expected, $input = null) {
$this->doTest($expected, $input);
}
public function provideFixCases() {
$cases = [];
// Simple cases
$cases[] = [
'<?php
class Foo
{
public function foo()
{
if ("a" === "b") {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
if ("a" === "b") {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
if ("a" === "b") {
// code
} else {
// another code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
if ("a" === "b") {
// code
} else {
// another code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
for ($i = 0; $i < 3; $i++) {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
for ($i = 0; $i < 3; $i++) {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
foreach (["foo", "bar"] as $str) {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
foreach (["foo", "bar"] as $str) {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
while ($i < 10) {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
while ($i < 10) {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
do {
// code
} while ($i < 10);
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
do {
// code
} while ($i < 10);
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
switch ("str") {
case "a":
break;
case "b":
break;
default:
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
switch ("str") {
case "a":
break;
case "b":
break;
default:
// code
}
$a = "next statement";
}
}',
];
// Extended cases
$cases[] = [
'<?php
class Foo
{
public function bar()
{
if ("a" === "b") {
// code
} else if ("a" === "c") {
// code
} else if ("a" === "d") {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function bar()
{
if ("a" === "b") {
// code
} else if ("a" === "c") {
// code
} else if ("a" === "d") {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function bar()
{
if ("a" === "b") {
// code
} elseif ("a" === "c") {
// code
} elseif ("a" === "d") {
// code
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function bar()
{
if ("a" === "b") {
// code
} elseif ("a" === "c") {
// code
} elseif ("a" === "d") {
// code
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function bar()
{
foreach (["foo", "bar"] as $str) {
if ($str === "foo") {
// code
}
}
}
}',
'<?php
class Foo
{
public function bar()
{
foreach (["foo", "bar"] as $str) {
if ($str === "foo") {
// code
}
}
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
switch ("str") {
case "a": {
break;
}
case "b": {
break;
}
default: {
// code
}
}
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
switch ("str") {
case "a": {
break;
}
case "b": {
break;
}
default: {
// code
}
}
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
$a = "prev statement";
foreach ($coordinates as $coordinate) {
$points = explode(",", $coordinate);
}
',
];
// Issue 5
$cases[] = [
'<?php
class Foo
{
public function foo()
{
if ("a" === "b")
$this->bar();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
if ("a" === "b")
$this->bar();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
if ("a" === "b")
$this->bar();
else
$this->baz();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
if ("a" === "b")
$this->bar();
else
$this->baz();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
for ($i = 0; $i < 3; $i++)
$this->bar();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
for ($i = 0; $i < 3; $i++)
$this->bar();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
foreach (["foo", "bar"] as $str)
$this->bar();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
foreach (["foo", "bar"] as $str)
$this->bar();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
while ($i < 10)
$this->bar();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
while ($i < 10)
$this->bar();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function foo()
{
do
$this->bar();
while ($i < 10);
$a = "next statement";
}
}',
'<?php
class Foo
{
public function foo()
{
do
$this->bar();
while ($i < 10);
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function bar()
{
if ("a" === "b")
$this->foo();
else if ("a" === "c")
$this->bar();
else if ("a" === "d")
$this->baz();
$a = "next statement";
}
}',
'<?php
class Foo
{
public function bar()
{
if ("a" === "b")
$this->foo();
else if ("a" === "c")
$this->bar();
else if ("a" === "d")
$this->baz();
$a = "next statement";
}
}',
];
$cases[] = [
'<?php
class Foo
{
public function bar()
{
foreach (["foo", "bar"] as $str)
if ($str === "foo")
$this->bar();
return 3;
}
}',
'<?php
class Foo
{
public function bar()
{
foreach (["foo", "bar"] as $str)
if ($str === "foo")
$this->bar();
return 3;
}
}',
];
return $cases;
}
protected function createFixer() {
return new LineBreakAfterStatementsFixer();
}
}