From 2885a1f74dc5806e01795c43ac2ff883549e0f12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Lange?= Date: Tue, 7 Apr 2026 16:36:49 +0200 Subject: [PATCH] Bump up all versions and remove deprecated stuff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Björn Lange --- README.md | 35 ++- composer.json | 30 +-- infection.json.dist | 13 - infection.json5.dist | 19 ++ phpcs.xml.dist | 3 - phpunit.xml.dist | 6 +- .../BestIt/CodeSniffer/CodeWarning.php | 4 +- .../BestIt/CodeSniffer/Helper/DocHelper.php | 4 +- .../CodeSniffer/Helper/DocTagHelper.php | 60 ++--- .../BestIt/CodeSniffer/Helper/LineHelper.php | 2 +- .../CodeSniffer/Helper/PropertyHelper.php | 1 + .../BestIt/CodeSniffer/Helper/TokenHelper.php | 4 + .../BestIt/Sniffs/ClassRegistrationTrait.php | 2 +- .../Sniffs/Commenting/AbstractDocSniff.php | 2 + .../Commenting/RedundantWhitespaceSniff.php | 1 + .../EmptyArrayForComparisonSniff.php | 2 + .../Sniffs/Comparisons/EqualOperatorSniff.php | 1 + .../ParasOfNegativeInstanceOfSniff.php | 4 +- .../BestIt/Sniffs/DocPosProviderTrait.php | 2 +- .../DocTags/AbstractDisallowedTagsSniff.php | 1 + .../DocTags/AbstractRequiredTagsSniff.php | 3 +- .../Sniffs/DocTags/AbstractTagSniff.php | 2 + .../DocTags/DisallowLeadingAttributeSniff.php | 2 + .../BestIt/Sniffs/DocTags/PackageTagSniff.php | 1 + .../BestIt/Sniffs/DocTags/ParamTagSniff.php | 53 +++- .../DocTags/RequiredMethodTagsSniff.php | 2 + .../BestIt/Sniffs/DocTags/TagSortingSniff.php | 2 + .../BestIt/Sniffs/DocTags/VarTagSniff.php | 2 + .../AlphabeticClassContentSniff.php | 2 + .../AlphabeticallySortedUsesSniff.php | 2 + .../NoWhitespaceAfterClassOpeningSniff.php | 6 +- .../BestIt/Sniffs/Formatting/OpenTagSniff.php | 160 ++++++------ .../Formatting/TrailingArrayCommaSniff.php | 5 + .../Formatting/TraitUseDeclarationSniff.php | 1 + .../Sniffs/Formatting/UCVFSortingSniff.php | 2 + .../Sniffs/Functions/MultipleReturnSniff.php | 2 + .../Functions/NoSimplePropertyMethodSniff.php | 4 +- .../CamelCaseVariableSniff.php | 2 + .../Sniffs/Spacing/ConstantSpacingSniff.php | 3 +- .../Sniffs/Spacing/PropertySpacingSniff.php | 3 +- .../Sniffs/Spacing/SpaceAfterDeclareSniff.php | 188 +++++++------- .../Sniffs/Spacing/SpaceAroundConcatSniff.php | 1 + .../Sniffs/Spacing/TraitUseSpacingSniff.php | 14 +- .../BestIt/Sniffs/Spacing/UseSpacingSniff.php | 6 +- .../Sniffs/Strings/ConcatCalculationSniff.php | 1 + .../TypeHints/ExplicitAssertionsSniff.php | 22 +- .../TypeHints/PropertyTypeHintSniff.php | 13 +- .../TypeHints/ReturnTypeDeclarationSniff.php | 94 ++++--- .../SuggestExplicitReturnTypeSniff.php | 2 +- src/Standards/BestIt/ruleset.xml | 4 +- tests/CodeSniffer/CodeErrorTest.php | 55 ++++ tests/CodeSniffer/CodeWarningTest.php | 101 ++++++++ tests/CodeSniffer/Helper/ClassHelperTest.php | 8 +- tests/CodeSniffer/Helper/DocTagHelperTest.php | 207 ++++++++++----- tests/CodeSniffer/Helper/FileHelper.php | 1 + tests/CodeSniffer/Helper/TokenHelperTest.php | 22 +- .../Helper/UseStatementHelperTest.php | 26 +- tests/SniffTestCase.php | 104 +++++++- .../ModernClassNameReferenceSniffTest.php | 19 +- ...fTest.php => AbstractDocSniffTestCase.php} | 19 +- tests/Sniffs/Commenting/ClassDocSniffTest.php | 7 +- .../Commenting/ConstantDocSniffTest.php | 8 +- .../Commenting/EmptyLinesDocSniffTest.php | 8 +- ...fTest.php => AbstractDocSniffTestCase.php} | 6 +- .../Commenting/FunctionDocSniffTest.php | 8 +- .../Commenting/PropertyDocSniffTest.php | 8 +- .../RedundantWhitespaceSniffTest.php | 23 +- .../EmptyArrayForComparisonSniffTest.php | 9 +- .../Comparisons/EqualOperatorSniffTest.php | 9 +- .../ParasOfNegativeInstanceOfSniffTest.php | 9 +- .../DefaultSniffIntegrationTestTrait.php | 243 ------------------ tests/Sniffs/DocTags/AuthorTagSniffTest.php | 9 +- .../Sniffs/DocTags/DeprecatedTagSniffTest.php | 29 ++- .../DisallowLeadingAttributeSniffTest.php | 15 +- .../DocTags/DisallowedClassTagsSniffTest.php | 26 +- tests/Sniffs/DocTags/ParamTagSniffTest.php | 39 +-- .../DocTags/RequiredClassTagsSniffTest.php | 8 +- tests/Sniffs/DocTags/TagSortingSniffTest.php | 29 ++- tests/Sniffs/DocTags/ThrowsTagSniffTest.php | 2 +- .../AlphabeticClassContentSniffTest.php | 30 ++- .../AlphabeticallySortedUsesSniffTest.php | 23 +- .../correct/Correct.php | 13 + ...ectEmptyLinesAfterOpeningBrace.8.fixed.php | 13 + ...IncorrectEmptyLinesAfterOpeningBrace.8.php | 14 + ...tEmptyLinesBeforeClosingBrace.14.fixed.php | 13 + ...correctEmptyLinesBeforeClosingBrace.14.php | 14 + .../ForbidDoubledWhitespaceSniffTest.php | 8 +- ...NoWhitespaceAfterClassOpeningSniffTest.php | 9 +- tests/Sniffs/Formatting/OpenTagSniffTest.php | 42 +-- .../ReturnTypeHintSpacingSniffTest.php | 6 +- .../TrailingArrayCommaSniffTest.php | 9 +- .../TrailingCommaInDeclarationSniffTest.php | 9 +- .../TraitUseDeclarationSniffTest.php | 9 +- .../Formatting/UCVFSortingSniffTest.php | 8 +- .../Functions/ForbiddenFunctionsSniffTest.php | 6 +- .../Functions/MultipleReturnSniffTest.php | 9 +- .../Functions/NoNamedArgumentsSniffTest.php | 9 +- .../NoSimplePropertyMethodSniffTest.php | 9 +- .../TrailingCommaInCallSniffTest.php | 33 +-- .../CamelCaseVariableSniffTest.php | 27 +- tests/Sniffs/SniffCorrectFilesTrait.php | 48 ++++ tests/Sniffs/SniffErrorFilesTrait.php | 76 ++++++ tests/Sniffs/SniffWarningFilesTrait.php | 76 ++++++ .../Spacing/ClassMemberSpacingSniffTest.php | 9 +- .../Spacing/ConstantSpacingSniffTest.php | 9 +- .../UseSpacingSniff/correct/Correct.php | 10 +- ...tBetweenDifferentTypeOfUse(1).10.fixed.php | 21 -- ...esCountBetweenDifferentTypeOfUse(1).10.php | 22 -- ...tBetweenDifferentTypeOfUse(3).12.fixed.php | 1 + .../Spacing/NamespaceSpacingSniffTest.php | 9 +- .../Spacing/PropertySpacingSniffTest.php | 19 +- .../Spacing/SpaceAfterDeclareSniffTest.php | 72 +++--- .../Spacing/SpaceAroundConcatSniffTest.php | 9 +- .../Spacing/TraitUseSpacingSniffTest.php | 9 +- tests/Sniffs/Spacing/UseSpacingSniffTest.php | 9 +- .../Strings/ConcatCalculationSniffTest.php | 9 +- .../TypeHints/ExplicitAssertionsSniffTest.php | 9 +- ...t.18,26,34,42,50,58,66,74,82,94.fixed.php} | 14 +- ...ypeHint.18,26,34,42,50,58,66,74,82,94.php} | 14 +- .../TypeHints/PropertyTypeHintSniffTest.php | 11 +- .../ReturnTypeDeclarationSniffTest.php | 8 +- .../SuggestExplicitReturnTypeSniffTest.php | 9 +- tests/TestRequiredConstantsTrait.php | 7 +- 123 files changed, 1654 insertions(+), 996 deletions(-) delete mode 100644 infection.json.dist create mode 100644 infection.json5.dist create mode 100644 tests/CodeSniffer/CodeErrorTest.php create mode 100644 tests/CodeSniffer/CodeWarningTest.php rename tests/Sniffs/Commenting/{AbstractDocSniffTest.php => AbstractDocSniffTestCase.php} (73%) rename tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/{AbstractDocSniffTest.php => AbstractDocSniffTestCase.php} (91%) delete mode 100644 tests/Sniffs/DefaultSniffIntegrationTestTrait.php create mode 100644 tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/correct/Correct.php create mode 100644 tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/with_errors/IncorrectEmptyLinesAfterOpeningBrace.8.fixed.php create mode 100644 tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/with_errors/IncorrectEmptyLinesAfterOpeningBrace.8.php create mode 100644 tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/with_errors/IncorrectEmptyLinesBeforeClosingBrace.14.fixed.php create mode 100644 tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/with_errors/IncorrectEmptyLinesBeforeClosingBrace.14.php create mode 100644 tests/Sniffs/SniffCorrectFilesTrait.php create mode 100644 tests/Sniffs/SniffErrorFilesTrait.php create mode 100644 tests/Sniffs/SniffWarningFilesTrait.php delete mode 100644 tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.fixed.php delete mode 100644 tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.php rename tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/{MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.fixed.php => MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.fixed.php} (82%) rename tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/{MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.php => MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.php} (86%) diff --git a/README.md b/README.md index f836c018..71190479 100644 --- a/README.md +++ b/README.md @@ -277,12 +277,37 @@ enforce that the constant values stay api-stable! #### Default Integration Tests -The trait _BestIt\Sniffs\DefaultSniffIntegrationTestTrait_ provides you with three tests to test the usually use cases of -a sniff based on sniff-individual test files: +Three focused traits provide the standard fixture-based sniff test scenarios. Use only the traits your sniff's fixture +directory actually needs: + +- **`BestIt\Sniffs\SniffCorrectFilesTrait`** — provides `testCorrect()`. Use whenever you have a `correct/` fixture folder. Always required. +- **`BestIt\Sniffs\SniffErrorFilesTrait`** — provides `testErrors()`. Use when you have a `with_errors/` fixture folder. +- **`BestIt\Sniffs\SniffWarningFilesTrait`** — provides `testWarnings()`. Use when you have a `with_warnings/` fixture folder. + +Example for a sniff that has both errors and warnings: + +```php +class MySniffTest extends SniffTestCase +{ + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; + // ... +} +``` + +Example for a sniff that only has errors: + +```php +class MySniffTest extends SniffTestCase +{ + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; + // ... +} +``` -1. testCorrect -2. testErrors -3. testWarnings +The tests `testCorrect`, `testErrors`, and `testWarnings` are provided respectively by the above traits. ##### Requirements diff --git a/composer.json b/composer.json index 4ab106f5..6b5d845b 100644 --- a/composer.json +++ b/composer.json @@ -8,15 +8,15 @@ "phpcbf" ], "low-level-checks": [ - "license-check", + "phpcpd --fuzzy --verbose src tests", + "phpcs -p src --standard=PHPCompatibility --runtime-set testVersion 8.2", "phpmd build,src,tests text phpmd.xml.dist", - "phpcpd src tests", "phpcs --ignore=\"**.js\" --runtime-set ignore_warnings_on_exit 1", "phpunit --coverage-xml=build/coverage/coverage-xml --log-junit=build/coverage/junit.xml" ], "high-level-checks": [ "@low-level-checks", - "infection --only-covered -s --no-progress --no-ansi --no-interaction --min-msi=75 --min-covered-msi=75 --skip-initial-tests --coverage=build/coverage --threads=4" + "infection -s --no-progress --no-ansi --no-interaction --min-msi=77 --min-covered-msi=77 --skip-initial-tests --coverage=build/coverage --threads=4" ] }, "type": "library", @@ -45,23 +45,21 @@ }, "prefer-stable": true, "require": { - "php": ">=8.0", - "slevomat/coding-standard": "^8.0" + "php": ">=8.2", + "slevomat/coding-standard": "^8.0", + "squizlabs/php_codesniffer": "^4.0" }, "require-dev": { - "phpmd/phpmd": "^2.6", - "sebastian/phpcpd": "^6.0.3", - "phploc/phploc": "^7.0.2", - "phpunit/phpunit": "^9.3", - "phpcompatibility/php-compatibility": "^9.3", + "phpmd/phpmd": "^2.15", + "phpunit/phpunit": "^12.0", "captainhook/plugin-composer": "^5.3", - "best-it/license-check": "^0.1.0", - "infection/infection": "^0.21.5", - "pdepend/pdepend": "2.8.*" - }, - "suggest": { - "phpcompatibility/php-compatibility": "If you want to check for php version compatibility. Please use at least ^9.0." + "infection/infection": "^0.32", + "systemsdk/phpcpd": "^8.3", + "phpcompatibility/php-compatibility": "^10.0.0@dev" }, + "suggest": { + "phpcompatibility/php-compatibility": "If you want to check for php version compatibility. Please use at least ^9.0." + }, "config": { "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true, diff --git a/infection.json.dist b/infection.json.dist deleted file mode 100644 index 7bd968f7..00000000 --- a/infection.json.dist +++ /dev/null @@ -1,13 +0,0 @@ -{ - "source": { - "directories": [ - "src" - ] - }, - "mutators": { - "@default": true, - "global-ignoreSourceCodeByRegex": [ - ".*->recordMetric.*" - ] - } -} \ No newline at end of file diff --git a/infection.json5.dist b/infection.json5.dist new file mode 100644 index 00000000..15dc75fc --- /dev/null +++ b/infection.json5.dist @@ -0,0 +1,19 @@ +{ + "source": { + "directories": [ + "src" + ] + }, + "mutators": { + "@default": true, + "global-ignore": [ + "BestIt\\Sniffs\\AbstractSniff::areRequirementsMet", + "BestIt\\Sniffs\\AbstractSniff::fixDefaultProblem", + "BestIt\\Sniffs\\AbstractSniff::setUp", + "BestIt\\Sniffs\\AbstractSniff::tearDown" + ], + "global-ignoreSourceCodeByRegex": [ + ".*->recordMetric.*" + ] + } +} \ No newline at end of file diff --git a/phpcs.xml.dist b/phpcs.xml.dist index f466db86..aa6d972d 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -4,9 +4,6 @@ - - - ./build/ ./src/ ./tests/ diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 6994c9c9..29e073be 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,13 +1,13 @@ - - + + ./src ./tests - + ./tests diff --git a/src/Standards/BestIt/CodeSniffer/CodeWarning.php b/src/Standards/BestIt/CodeSniffer/CodeWarning.php index 88da904e..a6a7bf0f 100644 --- a/src/Standards/BestIt/CodeSniffer/CodeWarning.php +++ b/src/Standards/BestIt/CodeSniffer/CodeWarning.php @@ -84,9 +84,9 @@ public function getStackPosition(): int /** * Returns the erroneous token. * - * @return array The "broken" token. + * @return null|array The "broken" token. */ - public function getToken(): array + public function getToken(): ?array { return $this->token; } diff --git a/src/Standards/BestIt/CodeSniffer/Helper/DocHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/DocHelper.php index f357a786..fa0e221c 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/DocHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/DocHelper.php @@ -7,7 +7,9 @@ use DomainException; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Util\Tokens; + use function sprintf; + use const T_DOC_COMMENT_CLOSE_TAG; /** @@ -149,7 +151,7 @@ private function loadBlockEndPosition(): ?int // Search till the next method, property, etc ... TokenHelper::findPreviousExcluding( $this->file, - TokenHelper::$ineffectiveTokenCodes + Tokens::$methodPrefixes, + TokenHelper::INEFFECTIVE_TOKEN_CODES + Tokens::METHOD_MODIFIERS, $this->stackPos - 1, ), ); diff --git a/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php index 83cb057d..be914f4a 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/DocTagHelper.php @@ -5,9 +5,11 @@ namespace BestIt\CodeSniffer\Helper; use PHP_CodeSniffer\Files\File; + use function array_key_exists; use function in_array; use function is_int; + use const T_DOC_COMMENT_CLOSE_TAG; use const T_DOC_COMMENT_STRING; use const T_DOC_COMMENT_TAG; @@ -66,34 +68,27 @@ private function getCommentStartToken(): array } /** - * Loads the tag content for the given tag position. + * Returns the individual count of every tag. * - * @param int $tagPosition The position of the tag. - * @param int $iteratedPosition + * @param array $tagTokens Array of tag tokens. * - * @return array The content tokens of the tag. + * @return array List of comment tags with there count of the current comment */ - private function loadTagContentTokens(int $tagPosition, int &$iteratedPosition): array + public function getTagCounts(array $tagTokens): array { - $contents = []; - $myColumn = $this->tokens[$tagPosition]['column']; - $closingPos = $this->file->findNext([T_DOC_COMMENT_CLOSE_TAG], $position = $tagPosition + 1); - - while ($position < $closingPos) { - $contentToken = $this->tokens[$position++]; + $tagCounts = []; - if (($contentToken['code'] === T_DOC_COMMENT_TAG) && ($contentToken['column'] <= $myColumn)) { - break; - } + foreach ($tagTokens as $tagToken) { + $tagName = $tagToken['content']; - if (in_array($contentToken['code'], [T_DOC_COMMENT_STRING, T_DOC_COMMENT_TAG])) { - $contents[$position] = $contentToken; + if (!array_key_exists($tagName, $tagCounts)) { + $tagCounts[$tagName] = 0; } - $iteratedPosition = $position; + ++$tagCounts[$tagName]; } - return $contents; + return $tagCounts; } /** @@ -120,26 +115,33 @@ public function getTagTokens(): array } /** - * Returns the individual count of every tag. + * Loads the tag content for the given tag position. * - * @param array $tagTokens Array of tag tokens. + * @param int $tagPosition The position of the tag. + * @param int $iteratedPosition * - * @return array List of comment tags with there count of the current comment + * @return array The content tokens of the tag. */ - public function getTagCounts(array $tagTokens): array + private function loadTagContentTokens(int $tagPosition, int &$iteratedPosition): array { - $tagCounts = []; + $contents = []; + $myColumn = $this->tokens[$tagPosition]['column']; + $closingPos = $this->file->findNext([T_DOC_COMMENT_CLOSE_TAG], $position = $tagPosition + 1); - foreach ($tagTokens as $tagToken) { - $tagName = $tagToken['content']; + while ($position < $closingPos) { + $contentToken = $this->tokens[$position++]; - if (!array_key_exists($tagName, $tagCounts)) { - $tagCounts[$tagName] = 0; + if (($contentToken['code'] === T_DOC_COMMENT_TAG) && ($contentToken['column'] <= $myColumn)) { + break; } - ++$tagCounts[$tagName]; + if (in_array($contentToken['code'], [T_DOC_COMMENT_STRING, T_DOC_COMMENT_TAG])) { + $contents[$position] = $contentToken; + } + + $iteratedPosition = $position; } - return $tagCounts; + return $contents; } } diff --git a/src/Standards/BestIt/CodeSniffer/Helper/LineHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/LineHelper.php index b1d366af..4a783e9e 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/LineHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/LineHelper.php @@ -53,7 +53,7 @@ public function __construct(File $file, ?Fixer $fixer = null) * * @return void */ - public function removeLine(int $line): void + private function removeLine(int $line): void { foreach ($this->file->getTokens() as $tagPtr => $tagToken) { if ($tagToken['line'] !== $line) { diff --git a/src/Standards/BestIt/CodeSniffer/Helper/PropertyHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/PropertyHelper.php index f7de4669..670ef743 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/PropertyHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/PropertyHelper.php @@ -5,6 +5,7 @@ namespace BestIt\CodeSniffer\Helper; use PHP_CodeSniffer\Files\File; + use function substr; /** diff --git a/src/Standards/BestIt/CodeSniffer/Helper/TokenHelper.php b/src/Standards/BestIt/CodeSniffer/Helper/TokenHelper.php index 7b7ab7d8..d0552e39 100644 --- a/src/Standards/BestIt/CodeSniffer/Helper/TokenHelper.php +++ b/src/Standards/BestIt/CodeSniffer/Helper/TokenHelper.php @@ -14,4 +14,8 @@ */ class TokenHelper extends BaseHelper { + public const ARRAY_TOKEN_CODES = [ + T_ARRAY, + T_OPEN_SHORT_ARRAY, + ]; } diff --git a/src/Standards/BestIt/Sniffs/ClassRegistrationTrait.php b/src/Standards/BestIt/Sniffs/ClassRegistrationTrait.php index 9fe1096f..bd088830 100644 --- a/src/Standards/BestIt/Sniffs/ClassRegistrationTrait.php +++ b/src/Standards/BestIt/Sniffs/ClassRegistrationTrait.php @@ -32,6 +32,6 @@ trait ClassRegistrationTrait */ public function register(): array { - return Tokens::$ooScopeTokens; + return Tokens::OO_SCOPE_TOKENS; } } diff --git a/src/Standards/BestIt/Sniffs/Commenting/AbstractDocSniff.php b/src/Standards/BestIt/Sniffs/Commenting/AbstractDocSniff.php index 22013acc..63e84dd4 100644 --- a/src/Standards/BestIt/Sniffs/Commenting/AbstractDocSniff.php +++ b/src/Standards/BestIt/Sniffs/Commenting/AbstractDocSniff.php @@ -9,7 +9,9 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\DocPosProviderTrait; + use function ucfirst; + use const T_DOC_COMMENT_OPEN_TAG; use const T_DOC_COMMENT_STRING; use const T_DOC_COMMENT_TAG; diff --git a/src/Standards/BestIt/Sniffs/Commenting/RedundantWhitespaceSniff.php b/src/Standards/BestIt/Sniffs/Commenting/RedundantWhitespaceSniff.php index dd3901df..b095c46d 100644 --- a/src/Standards/BestIt/Sniffs/Commenting/RedundantWhitespaceSniff.php +++ b/src/Standards/BestIt/Sniffs/Commenting/RedundantWhitespaceSniff.php @@ -5,6 +5,7 @@ namespace BestIt\Sniffs\Commenting; use BestIt\Sniffs\AbstractSniff; + use const T_DOC_COMMENT_STAR; use const T_DOC_COMMENT_TAG; use const T_DOC_COMMENT_WHITESPACE; diff --git a/src/Standards/BestIt/Sniffs/Comparisons/EmptyArrayForComparisonSniff.php b/src/Standards/BestIt/Sniffs/Comparisons/EmptyArrayForComparisonSniff.php index 4d2843fc..a855c5fb 100644 --- a/src/Standards/BestIt/Sniffs/Comparisons/EmptyArrayForComparisonSniff.php +++ b/src/Standards/BestIt/Sniffs/Comparisons/EmptyArrayForComparisonSniff.php @@ -7,7 +7,9 @@ use BestIt\CodeSniffer\CodeError; use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; + use function array_key_exists; + use const T_ARRAY; use const T_CLOSE_PARENTHESIS; use const T_CLOSE_SHORT_ARRAY; diff --git a/src/Standards/BestIt/Sniffs/Comparisons/EqualOperatorSniff.php b/src/Standards/BestIt/Sniffs/Comparisons/EqualOperatorSniff.php index 00d78570..996e7ae4 100644 --- a/src/Standards/BestIt/Sniffs/Comparisons/EqualOperatorSniff.php +++ b/src/Standards/BestIt/Sniffs/Comparisons/EqualOperatorSniff.php @@ -6,6 +6,7 @@ use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\SuppressingTrait; + use const T_IS_EQUAL; use const T_IS_NOT_EQUAL; diff --git a/src/Standards/BestIt/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniff.php b/src/Standards/BestIt/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniff.php index bf794f5e..20637ac1 100644 --- a/src/Standards/BestIt/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniff.php +++ b/src/Standards/BestIt/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniff.php @@ -8,7 +8,9 @@ use BestIt\CodeSniffer\CodeWarning; use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; + use function array_merge; + use const T_ASPERAND; use const T_BOOLEAN_NOT; use const T_INSTANCEOF; @@ -126,7 +128,7 @@ private function getPositionOfTokenBeforeCheck(): int return TokenHelper::findPreviousExcluding( $file, // And skip object property accesses - array_merge(TokenHelper::$ineffectiveTokenCodes, [T_ASPERAND, T_OBJECT_OPERATOR, T_STRING, T_VARIABLE]), + array_merge(TokenHelper::INEFFECTIVE_TOKEN_CODES, [T_ASPERAND, T_OBJECT_OPERATOR, T_STRING, T_VARIABLE]), $stackPosition - 1, ); } diff --git a/src/Standards/BestIt/Sniffs/DocPosProviderTrait.php b/src/Standards/BestIt/Sniffs/DocPosProviderTrait.php index a1e47372..fba290de 100644 --- a/src/Standards/BestIt/Sniffs/DocPosProviderTrait.php +++ b/src/Standards/BestIt/Sniffs/DocPosProviderTrait.php @@ -34,7 +34,7 @@ trait DocPosProviderTrait * * @return int|bool */ - protected function getDocCommentPos() + protected function getDocCommentPos(): int|false|null { if ($this->docCommentPos === false) { $this->docCommentPos = $this->loadDocCommentPos(); diff --git a/src/Standards/BestIt/Sniffs/DocTags/AbstractDisallowedTagsSniff.php b/src/Standards/BestIt/Sniffs/DocTags/AbstractDisallowedTagsSniff.php index 7a9b4e6f..41175a28 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/AbstractDisallowedTagsSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/AbstractDisallowedTagsSniff.php @@ -7,6 +7,7 @@ use BestIt\CodeSniffer\Helper\DocTagHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\DocPosProviderTrait; + use function in_array; use function substr; diff --git a/src/Standards/BestIt/Sniffs/DocTags/AbstractRequiredTagsSniff.php b/src/Standards/BestIt/Sniffs/DocTags/AbstractRequiredTagsSniff.php index 6c328be3..9a2b150e 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/AbstractRequiredTagsSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/AbstractRequiredTagsSniff.php @@ -8,6 +8,7 @@ use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\DocPosProviderTrait; use Closure; + use function array_filter; use function array_key_exists; use function array_map; @@ -234,7 +235,7 @@ abstract protected function getTagRules(): array; * * @return bool|string */ - private function hasFixCallback(string $rule, string $tag) + private function hasFixCallback(string $rule, string $tag): bool|string { return method_exists($this, $method = sprintf('fix%s%s', ucfirst($rule), ucfirst($tag))) ? $method diff --git a/src/Standards/BestIt/Sniffs/DocTags/AbstractTagSniff.php b/src/Standards/BestIt/Sniffs/DocTags/AbstractTagSniff.php index a4c10261..feeffa2b 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/AbstractTagSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/AbstractTagSniff.php @@ -7,10 +7,12 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use PHP_CodeSniffer\Util\Tokens; + use function class_exists; use function implode; use function spl_autoload_call; use function substr; + use const T_DOC_COMMENT_CLOSE_TAG; use const T_DOC_COMMENT_STRING; use const T_DOC_COMMENT_TAG; diff --git a/src/Standards/BestIt/Sniffs/DocTags/DisallowLeadingAttributeSniff.php b/src/Standards/BestIt/Sniffs/DocTags/DisallowLeadingAttributeSniff.php index 6f66d181..f9fd7419 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/DisallowLeadingAttributeSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/DisallowLeadingAttributeSniff.php @@ -8,10 +8,12 @@ use BestIt\CodeSniffer\CodeWarning; use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; + use function compact; use function in_array; use function sprintf; use function str_repeat; + use const T_ATTRIBUTE; use const T_ATTRIBUTE_END; use const T_CLOSE_SQUARE_BRACKET; diff --git a/src/Standards/BestIt/Sniffs/DocTags/PackageTagSniff.php b/src/Standards/BestIt/Sniffs/DocTags/PackageTagSniff.php index 7865ce84..e912d0e2 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/PackageTagSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/PackageTagSniff.php @@ -6,6 +6,7 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use SlevomatCodingStandard\Helpers\NamespaceHelper; + use const T_DOC_COMMENT_STRING; use const T_NAMESPACE; diff --git a/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php b/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php index aee32c41..123621be 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/ParamTagSniff.php @@ -7,14 +7,19 @@ use BestIt\CodeSniffer\CodeError; use BestIt\CodeSniffer\CodeWarning; use BestIt\CodeSniffer\Helper\TokenHelper; + use function array_filter; use function array_values; use function in_array; use function preg_quote; use function strtolower; + use const ARRAY_FILTER_USE_KEY; +use const T_ATTRIBUTE; +use const T_ATTRIBUTE_END; use const T_CLOSE_PARENTHESIS; use const T_DOC_COMMENT_OPEN_TAG; +use const T_FUNCTION; use const T_VARIABLE; /** @@ -188,27 +193,34 @@ private function checkType(): bool */ protected function findAllVariablePositions(): array { + $searchStart = $this->stackPos + 1; + + // Skip past any PHP 8 attributes (#[...]) before the function declaration. + $attrStart = $this->file->findNext([T_ATTRIBUTE], $searchStart); + while ($attrStart !== false) { + $attrEnd = $this->file->findNext([T_ATTRIBUTE_END], $attrStart + 1); + if ($attrEnd === false) { + break; + } + // Only skip if the attribute comes before the next function keyword. + $nextFunction = $this->file->findNext([T_FUNCTION], $searchStart); + if ($nextFunction !== false && $attrStart > $nextFunction) { + break; + } + $searchStart = $attrEnd + 1; + $attrStart = $this->file->findNext([T_ATTRIBUTE], $searchStart); + } + + $closeParen = $this->file->findNext([T_CLOSE_PARENTHESIS], $searchStart); + return TokenHelper::findNextAll( $this->file, [T_VARIABLE], $this->stackPos + 1, - $this->file->findNext([T_CLOSE_PARENTHESIS], $this->stackPos + 1), + $closeParen, ); } - /** - * Returns a pattern to check if the content is valid. - * - * @return string The pattern which matches successful. - */ - protected function getValidPattern(): string - { - $varOfThisTag = $this->getArgumentTokenOfTag(); - - return '/(?P[\w|\|\[\]]*) ?(?P' . preg_quote($varOfThisTag['content'], '/') . - ') ?(?P.*)/m'; - } - /** * Returns the name of the real function argument for this parameter tag. * @@ -223,6 +235,19 @@ private function getArgumentTokenOfTag(): array return $this->argumentToken; } + /** + * Returns a pattern to check if the content is valid. + * + * @return string The pattern which matches successful. + */ + protected function getValidPattern(): string + { + $varOfThisTag = $this->getArgumentTokenOfTag(); + + return '/(?P[\w|\|\[\]]*) ?(?P' . preg_quote($varOfThisTag['content'], '/') . + ') ?(?P.*)/m'; + } + /** * Loads and checks the variables of the following method. * diff --git a/src/Standards/BestIt/Sniffs/DocTags/RequiredMethodTagsSniff.php b/src/Standards/BestIt/Sniffs/DocTags/RequiredMethodTagsSniff.php index fe280dce..e88db92b 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/RequiredMethodTagsSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/RequiredMethodTagsSniff.php @@ -6,8 +6,10 @@ use BestIt\Sniffs\FunctionRegistrationTrait; use SlevomatCodingStandard\Helpers\FunctionHelper; + use function in_array; use function str_repeat; + use const T_FUNCTION; use const T_STRING; diff --git a/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php b/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php index 21cb33b8..11c90d37 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/TagSortingSniff.php @@ -8,6 +8,7 @@ use BestIt\CodeSniffer\Helper\DocTagHelper; use BestIt\CodeSniffer\Helper\LineHelper; use BestIt\Sniffs\AbstractSniff; + use function array_filter; use function array_key_exists; use function array_shift; @@ -17,6 +18,7 @@ use function strcasecmp; use function strlen; use function uasort; + use const T_DOC_COMMENT_OPEN_TAG; /** diff --git a/src/Standards/BestIt/Sniffs/DocTags/VarTagSniff.php b/src/Standards/BestIt/Sniffs/DocTags/VarTagSniff.php index c2b15152..8d8da709 100644 --- a/src/Standards/BestIt/Sniffs/DocTags/VarTagSniff.php +++ b/src/Standards/BestIt/Sniffs/DocTags/VarTagSniff.php @@ -5,9 +5,11 @@ namespace BestIt\Sniffs\DocTags; use BestIt\CodeSniffer\Helper\TokenHelper; + use function array_column; use function array_map; use function implode; + use const T_FUNCTION; /** diff --git a/src/Standards/BestIt/Sniffs/Formatting/AlphabeticClassContentSniff.php b/src/Standards/BestIt/Sniffs/Formatting/AlphabeticClassContentSniff.php index ff8cece5..41664508 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/AlphabeticClassContentSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/AlphabeticClassContentSniff.php @@ -8,8 +8,10 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\ClassRegistrationTrait; + use function array_values; use function natsort; + use const T_CONST; use const T_FUNCTION; use const T_STRING; diff --git a/src/Standards/BestIt/Sniffs/Formatting/AlphabeticallySortedUsesSniff.php b/src/Standards/BestIt/Sniffs/Formatting/AlphabeticallySortedUsesSniff.php index 0ecae798..faf8393b 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/AlphabeticallySortedUsesSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/AlphabeticallySortedUsesSniff.php @@ -11,10 +11,12 @@ use BestIt\Sniffs\AbstractSniff; use SlevomatCodingStandard\Helpers\NamespaceHelper; use SlevomatCodingStandard\Helpers\UseStatement; + use function end; use function reset; use function strcasecmp; use function uasort; + use const T_OPEN_TAG; use const T_SEMICOLON; diff --git a/src/Standards/BestIt/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniff.php b/src/Standards/BestIt/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniff.php index 52e2dc29..e09f2cdb 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniff.php @@ -19,14 +19,12 @@ class NoWhitespaceAfterClassOpeningSniff extends EmptyLinesAroundClassBracesSnif * * @var int */ - // phpcs:ignore BestIt.TypeHints.PropertyTypeHint.MissingNativeTypeHint - public $linesCountAfterOpeningBrace = 0; + public int $linesCountAfterOpeningBrace = 0; /** * There MUST be no lines before the closing brace. * * @var int */ - // phpcs:ignore BestIt.TypeHints.PropertyTypeHint.MissingNativeTypeHint - public $linesCountBeforeClosingBrace = 0; + public int $linesCountBeforeClosingBrace = 0; } diff --git a/src/Standards/BestIt/Sniffs/Formatting/OpenTagSniff.php b/src/Standards/BestIt/Sniffs/Formatting/OpenTagSniff.php index 8732db0e..935fdf7f 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/OpenTagSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/OpenTagSniff.php @@ -16,20 +16,15 @@ class OpenTagSniff implements Sniff { /** - * Error message when open tag is not first statement. + * The next line after the open tag MUST be empty. */ - public const ERROR_NOT_FIRST_STATEMENT = 'Open tag is not first statement'; + public const CODE_LINE_NOT_EMPTY = 'LineNotEmpty'; /** * After the open tag there MUST be an empty line. */ public const CODE_NOT_FIRST_STATEMENT = 'OpenTagNotFirstStatement'; - /** - * Error message when there is no space after open tag. - */ - public const ERROR_NO_SPACE_AFTER_OPEN_TAG = 'No space after open tag'; - /** * There MUST be whitespace after the open tag. */ @@ -41,78 +36,37 @@ class OpenTagSniff implements Sniff public const ERROR_LINE_NOT_EMPTY = 'Line after open tag is not empty.'; /** - * The next line after the open tag MUST be empty. - */ - public const CODE_LINE_NOT_EMPTY = 'LineNotEmpty'; - - /** - * Registers the tokens that this sniff wants to listen for. - * - * @return int[] List of tokens to listen for + * Error message when open tag is not first statement. */ - public function register(): array - { - return [ - T_OPEN_TAG, - ]; - } + public const ERROR_NOT_FIRST_STATEMENT = 'Open tag is not first statement'; /** - * Called when one of the token types that this sniff is listening for is found. - * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint - * - * @param File $phpcsFile The PHP_CodeSniffer file where the token was found. - * @param int $stackPtr The position in the PHP_CodeSniffer file's token stack where the token was found. - * - * @return void Optionally returns a stack pointer. + * Error message when there is no space after open tag. */ - public function process(File $phpcsFile, $stackPtr): void - { - $tokens = $phpcsFile->getTokens(); - - //Open tag is not first token in token stack - if ($stackPtr !== 0) { - $this->handleOpenTagNotFirstStatement($phpcsFile, $stackPtr); - } - - $whitespacePtr = $stackPtr + 1; - $whitespaceToken = $tokens[$whitespacePtr]; - - //Following token not whitespace token - if ($whitespaceToken['code'] !== T_WHITESPACE) { - $this->handleNoSpaceAfterOpenTag($phpcsFile, $stackPtr, $whitespacePtr); - - return; - } - - //Whitespace token not empty - if ($whitespaceToken['length'] !== 0) { - $this->handleLineNotEmpty($phpcsFile, $whitespacePtr); - } - } + public const ERROR_NO_SPACE_AFTER_OPEN_TAG = 'No space after open tag'; /** - * Handles open tag not first statement error. + * Handles line after open tag not empty. * * @param File $phpcsFile The php cs file - * @param int $stackPtr Pointer to the open tag token + * @param int $whitespacePtr Pointer to the line after the open tag * * @return void */ - private function handleOpenTagNotFirstStatement(File $phpcsFile, int $stackPtr): void + private function handleLineNotEmpty(File $phpcsFile, int $whitespacePtr): void { - $fixNotFirstStatement = $phpcsFile->addFixableError( - self::ERROR_NOT_FIRST_STATEMENT, - $stackPtr, - static::CODE_NOT_FIRST_STATEMENT, + $fixSpaceNotScndLine = $phpcsFile->addFixableError( + self::ERROR_LINE_NOT_EMPTY, + $whitespacePtr, + static::CODE_LINE_NOT_EMPTY, ); - if ($fixNotFirstStatement) { + if ($fixSpaceNotScndLine) { $phpcsFile->fixer->beginChangeset(); - for ($i = 0; $i < $stackPtr; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } + $phpcsFile->fixer->replaceToken( + $whitespacePtr, + '', + ); $phpcsFile->fixer->endChangeset(); } } @@ -142,28 +96,82 @@ private function handleNoSpaceAfterOpenTag(File $phpcsFile, int $stackPtr, int $ } /** - * Handles line after open tag not empty. + * Handles open tag not first statement error. * * @param File $phpcsFile The php cs file - * @param int $whitespacePtr Pointer to the line after the open tag + * @param int $stackPtr Pointer to the open tag token * * @return void */ - private function handleLineNotEmpty(File $phpcsFile, int $whitespacePtr): void + private function handleOpenTagNotFirstStatement(File $phpcsFile, int $stackPtr): void { - $fixSpaceNotScndLine = $phpcsFile->addFixableError( - self::ERROR_LINE_NOT_EMPTY, - $whitespacePtr, - static::CODE_LINE_NOT_EMPTY, + $fixNotFirstStatement = $phpcsFile->addFixableError( + self::ERROR_NOT_FIRST_STATEMENT, + $stackPtr, + static::CODE_NOT_FIRST_STATEMENT, ); - if ($fixSpaceNotScndLine) { + if ($fixNotFirstStatement) { $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( - $whitespacePtr, - '', - ); + for ($i = 0; $i < $stackPtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } $phpcsFile->fixer->endChangeset(); } } + + /** + * Called when one of the token types that this sniff is listening for is found. + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint + * + * @param File $phpcsFile The PHP_CodeSniffer file where the token was found. + * @param int $stackPtr The position in the PHP_CodeSniffer file's token stack where the token was found. + * + * @return void Optionally returns a stack pointer. + */ + public function process(File $phpcsFile, $stackPtr): void + { + $tokens = $phpcsFile->getTokens(); + + //Open tag is not first token in token stack + if ($stackPtr !== 0) { + $this->handleOpenTagNotFirstStatement($phpcsFile, $stackPtr); + } + + $whitespacePtr = $stackPtr + 1; + $whitespaceToken = $tokens[$whitespacePtr]; + + // In phpcs 4, T_OPEN_TAG no longer includes the trailing newline. + // The token immediately after T_OPEN_TAG is a zero-length T_WHITESPACE "\n". + // Skip it to reach the actual line-2 content. + if ($whitespaceToken['code'] === T_WHITESPACE && $whitespaceToken['length'] === 0) { + $whitespacePtr++; + $whitespaceToken = $tokens[$whitespacePtr]; + } + + //Following token not whitespace token + if ($whitespaceToken['code'] !== T_WHITESPACE) { + $this->handleNoSpaceAfterOpenTag($phpcsFile, $stackPtr, $whitespacePtr); + + return; + } + + //Whitespace token not empty + if ($whitespaceToken['length'] !== 0) { + $this->handleLineNotEmpty($phpcsFile, $whitespacePtr); + } + } + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] List of tokens to listen for + */ + public function register(): array + { + return [ + T_OPEN_TAG, + ]; + } } diff --git a/src/Standards/BestIt/Sniffs/Formatting/TrailingArrayCommaSniff.php b/src/Standards/BestIt/Sniffs/Formatting/TrailingArrayCommaSniff.php index a05ae242..02f616f3 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/TrailingArrayCommaSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/TrailingArrayCommaSniff.php @@ -4,6 +4,7 @@ namespace BestIt\Sniffs\Formatting; +use BestIt\CodeSniffer\Helper\TokenHelper; use SlevomatCodingStandard\Sniffs\Arrays\TrailingArrayCommaSniff as BaseSniff; /** @@ -14,4 +15,8 @@ */ class TrailingArrayCommaSniff extends BaseSniff { + public function register(): array + { + return TokenHelper::ARRAY_TOKEN_CODES; + } } diff --git a/src/Standards/BestIt/Sniffs/Formatting/TraitUseDeclarationSniff.php b/src/Standards/BestIt/Sniffs/Formatting/TraitUseDeclarationSniff.php index 0297b0ae..9cde1022 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/TraitUseDeclarationSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/TraitUseDeclarationSniff.php @@ -8,6 +8,7 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\ClassRegistrationTrait; + use const T_COMMA; use const T_OPEN_CURLY_BRACKET; use const T_SEMICOLON; diff --git a/src/Standards/BestIt/Sniffs/Formatting/UCVFSortingSniff.php b/src/Standards/BestIt/Sniffs/Formatting/UCVFSortingSniff.php index 3f568052..16a70f12 100644 --- a/src/Standards/BestIt/Sniffs/Formatting/UCVFSortingSniff.php +++ b/src/Standards/BestIt/Sniffs/Formatting/UCVFSortingSniff.php @@ -9,12 +9,14 @@ use BestIt\CodeSniffer\Helper\UseStatementHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\ClassRegistrationTrait; + use function array_combine; use function array_filter; use function array_keys; use function array_map; use function array_search; use function uasort; + use const ARRAY_FILTER_USE_BOTH; use const T_CONST; use const T_FUNCTION; diff --git a/src/Standards/BestIt/Sniffs/Functions/MultipleReturnSniff.php b/src/Standards/BestIt/Sniffs/Functions/MultipleReturnSniff.php index 17af2556..a75d8f5e 100644 --- a/src/Standards/BestIt/Sniffs/Functions/MultipleReturnSniff.php +++ b/src/Standards/BestIt/Sniffs/Functions/MultipleReturnSniff.php @@ -7,9 +7,11 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\FunctionRegistrationTrait; + use function array_filter; use function array_shift; use function array_walk; + use const T_CLOSURE; use const T_FUNCTION; use const T_RETURN; diff --git a/src/Standards/BestIt/Sniffs/Functions/NoSimplePropertyMethodSniff.php b/src/Standards/BestIt/Sniffs/Functions/NoSimplePropertyMethodSniff.php index 7c2ab201..08e3b480 100644 --- a/src/Standards/BestIt/Sniffs/Functions/NoSimplePropertyMethodSniff.php +++ b/src/Standards/BestIt/Sniffs/Functions/NoSimplePropertyMethodSniff.php @@ -9,12 +9,14 @@ use SlevomatCodingStandard\Helpers\FunctionHelper; use SlevomatCodingStandard\Helpers\PropertyHelper; use SlevomatCodingStandard\Helpers\TokenHelper; + use function current; use function is_int; use function preg_match; use function substr; use function trim; use function ucfirst; + use const T_AS; use const T_CONST; use const T_FUNCTION; @@ -252,7 +254,7 @@ protected function processToken(): void * * @return array|mixed[] */ - public function register() + public function register(): array { return [ T_VAR, diff --git a/src/Standards/BestIt/Sniffs/NamingConventions/CamelCaseVariableSniff.php b/src/Standards/BestIt/Sniffs/NamingConventions/CamelCaseVariableSniff.php index 20b288ef..8982fd4f 100644 --- a/src/Standards/BestIt/Sniffs/NamingConventions/CamelCaseVariableSniff.php +++ b/src/Standards/BestIt/Sniffs/NamingConventions/CamelCaseVariableSniff.php @@ -9,8 +9,10 @@ use BestIt\Sniffs\VariableRegistrationTrait; use PHP_CodeSniffer\Util\Common; use SlevomatCodingStandard\Helpers\PropertyHelper; + use function array_key_exists; use function substr; + use const T_EQUAL; use const T_SEMICOLON; diff --git a/src/Standards/BestIt/Sniffs/Spacing/ConstantSpacingSniff.php b/src/Standards/BestIt/Sniffs/Spacing/ConstantSpacingSniff.php index 94f0f4df..9e672de8 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/ConstantSpacingSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/ConstantSpacingSniff.php @@ -20,6 +20,5 @@ class ConstantSpacingSniff extends BaseSniff * * @var int */ - // phpcs:ignore BestIt.TypeHints.PropertyTypeHint.MissingNativeTypeHint - public $minLinesCountBeforeWithoutComment = 1; + public int $minLinesCountBeforeWithoutComment = 1; } diff --git a/src/Standards/BestIt/Sniffs/Spacing/PropertySpacingSniff.php b/src/Standards/BestIt/Sniffs/Spacing/PropertySpacingSniff.php index d0887059..4d613393 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/PropertySpacingSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/PropertySpacingSniff.php @@ -20,6 +20,5 @@ class PropertySpacingSniff extends BaseSniff * * @var int */ - // phpcs:ignore BestIt.TypeHints.PropertyTypeHint.MissingNativeTypeHint - public $minLinesCountBeforeWithoutComment = 1; + public int $minLinesCountBeforeWithoutComment = 1; } diff --git a/src/Standards/BestIt/Sniffs/Spacing/SpaceAfterDeclareSniff.php b/src/Standards/BestIt/Sniffs/Spacing/SpaceAfterDeclareSniff.php index bc8de9c4..ffbf6a22 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/SpaceAfterDeclareSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/SpaceAfterDeclareSniff.php @@ -16,45 +16,118 @@ class SpaceAfterDeclareSniff implements Sniff { /** - * Error message when no whitespace is found. + * Multiple declare-statements SHOULD be grouped without a blank line. */ - public const MESSAGE_NO_WHITESPACE_FOUND = 'There is no whitespace after declare-statement.'; + public const CODE_GROUP_BLANK_LINE_FOUND = 'GroupBlankLineFound'; + + /** + * THERE MUST be just one single line after the declare statement. + */ + public const CODE_MUCH_WHITESPACE_FOUND = 'MuchWhitespaceFound'; /** * There MUST be one empty line after declare-statement. */ public const CODE_NO_WHITESPACE_FOUND = 'NoWhitespaceFound'; + /** + * Error message when blank lines in a group are found. + */ + public const MESSAGE_GROUP_BLANK_LINE_FOUND = 'Multpile declare-statements should be grouped without a blank line.'; + /** * Error message when more than one whitespaces are found. */ public const MESSAGE_MUCH_WHITESPACE_FOUND = 'There are more than one whitespaces after declare-statement.'; /** - * THERE MUST be just one single line after the declare statement. + * Error message when no whitespace is found. */ - public const CODE_MUCH_WHITESPACE_FOUND = 'MuchWhitespaceFound'; + public const MESSAGE_NO_WHITESPACE_FOUND = 'There is no whitespace after declare-statement.'; /** - * Error message when blank lines in a group are found. + * Handles blank lines found in declare group. + * + * @param File $phpcsFile The php cs file + * @param int $semicolonPtr Pointer to the semicolon + * @param int $secondSpacePtr Pointer to the second space + * @param int $nextNonSpacePtr Pointer to the next non space token + * + * @return void */ - public const MESSAGE_GROUP_BLANK_LINE_FOUND = 'Multpile declare-statements should be grouped without a blank line.'; + private function handleBlankLineInGroup( + File $phpcsFile, + int $semicolonPtr, + int $secondSpacePtr, + int $nextNonSpacePtr, + ): void { + $fixGroupBlankLines = $phpcsFile->addFixableError( + self::MESSAGE_GROUP_BLANK_LINE_FOUND, + $semicolonPtr, + static::CODE_GROUP_BLANK_LINE_FOUND, + ); + + if ($fixGroupBlankLines) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $secondSpacePtr; $i < $nextNonSpacePtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } /** - * Multiple declare-statements SHOULD be grouped without a blank line. + * Handles when more than one whitespaces are found. + * + * @param File $phpcsFile The php cs file + * @param int $semicolonPtr Pointer to the semicolon + * @param int $secondSpacePtr Pointer to the second space + * @param int $nextNonSpacePtr Pointer to the next non space token + * + * @return void */ - public const CODE_GROUP_BLANK_LINE_FOUND = 'GroupBlankLineFound'; + private function handleMuchWhitespacesFound( + File $phpcsFile, + int $semicolonPtr, + int $secondSpacePtr, + int $nextNonSpacePtr, + ): void { + $fixMuchWhitespaces = $phpcsFile->addFixableError( + self::MESSAGE_MUCH_WHITESPACE_FOUND, + $semicolonPtr, + static::CODE_MUCH_WHITESPACE_FOUND, + ); + + if ($fixMuchWhitespaces) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $secondSpacePtr; $i < $nextNonSpacePtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } /** - * Registers the tokens that this sniff wants to listen for. + * Handles when no whitespace is found. * - * @return int[] List of tokens to listen for + * @param File $phpcsFile The php cs file + * @param int $semicolonPtr Pointer to the semicolon token + * + * @return void */ - public function register(): array + private function handleNoWhitespaceFound(File $phpcsFile, int $semicolonPtr): void { - return [ - T_DECLARE, - ]; + $fixNoWhitespace = $phpcsFile->addFixableError( + self::MESSAGE_NO_WHITESPACE_FOUND, + $semicolonPtr, + static::CODE_NO_WHITESPACE_FOUND, + ); + + if ($fixNoWhitespace) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($semicolonPtr); + $phpcsFile->fixer->endChangeset(); + } } /** @@ -78,7 +151,7 @@ public function process(File $phpcsFile, $stackPtr): void $nextDeclarePtr = $phpcsFile->findNext(T_DECLARE, $semicolonPtr, null, false); - $whiteSpaceInGroupPtr = $phpcsFile->findNext(T_WHITESPACE, $secondSpacePtr, $nextDeclarePtr, false); + $whiteSpaceInGroupPtr = $phpcsFile->findNext(T_WHITESPACE, $secondSpacePtr, $nextDeclarePtr ?: null, false); //Declare statement group detected @@ -116,87 +189,14 @@ public function process(File $phpcsFile, $stackPtr): void } /** - * Handles when no whitespace is found. - * - * @param File $phpcsFile The php cs file - * @param int $semicolonPtr Pointer to the semicolon token + * Registers the tokens that this sniff wants to listen for. * - * @return void + * @return int[] List of tokens to listen for */ - private function handleNoWhitespaceFound(File $phpcsFile, int $semicolonPtr): void + public function register(): array { - $fixNoWhitespace = $phpcsFile->addFixableError( - self::MESSAGE_NO_WHITESPACE_FOUND, - $semicolonPtr, - static::CODE_NO_WHITESPACE_FOUND, - ); - - if ($fixNoWhitespace) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addNewline($semicolonPtr); - $phpcsFile->fixer->endChangeset(); - } - } - - /** - * Handles when more than one whitespaces are found. - * - * @param File $phpcsFile The php cs file - * @param int $semicolonPtr Pointer to the semicolon - * @param int $secondSpacePtr Pointer to the second space - * @param int $nextNonSpacePtr Pointer to the next non space token - * - * @return void - */ - private function handleMuchWhitespacesFound( - File $phpcsFile, - int $semicolonPtr, - int $secondSpacePtr, - int $nextNonSpacePtr, - ): void { - $fixMuchWhitespaces = $phpcsFile->addFixableError( - self::MESSAGE_MUCH_WHITESPACE_FOUND, - $semicolonPtr, - static::CODE_MUCH_WHITESPACE_FOUND, - ); - - if ($fixMuchWhitespaces) { - $phpcsFile->fixer->beginChangeset(); - for ($i = $secondSpacePtr; $i < $nextNonSpacePtr; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } - $phpcsFile->fixer->endChangeset(); - } - } - - /** - * Handles blank lines found in declare group. - * - * @param File $phpcsFile The php cs file - * @param int $semicolonPtr Pointer to the semicolon - * @param int $secondSpacePtr Pointer to the second space - * @param int $nextNonSpacePtr Pointer to the next non space token - * - * @return void - */ - private function handleBlankLineInGroup( - File $phpcsFile, - int $semicolonPtr, - int $secondSpacePtr, - int $nextNonSpacePtr, - ): void { - $fixGroupBlankLines = $phpcsFile->addFixableError( - self::MESSAGE_GROUP_BLANK_LINE_FOUND, - $semicolonPtr, - static::CODE_GROUP_BLANK_LINE_FOUND, - ); - - if ($fixGroupBlankLines) { - $phpcsFile->fixer->beginChangeset(); - for ($i = $secondSpacePtr; $i < $nextNonSpacePtr; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } - $phpcsFile->fixer->endChangeset(); - } + return [ + T_DECLARE, + ]; } } diff --git a/src/Standards/BestIt/Sniffs/Spacing/SpaceAroundConcatSniff.php b/src/Standards/BestIt/Sniffs/Spacing/SpaceAroundConcatSniff.php index d2b27ab1..a29d0467 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/SpaceAroundConcatSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/SpaceAroundConcatSniff.php @@ -7,6 +7,7 @@ use BestIt\CodeSniffer\CodeError; use BestIt\CodeSniffer\CodeWarning; use BestIt\Sniffs\AbstractSniff; + use const T_STRING_CONCAT; use const T_WHITESPACE; diff --git a/src/Standards/BestIt/Sniffs/Spacing/TraitUseSpacingSniff.php b/src/Standards/BestIt/Sniffs/Spacing/TraitUseSpacingSniff.php index ac579c2a..641d95cb 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/TraitUseSpacingSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/TraitUseSpacingSniff.php @@ -8,8 +8,10 @@ use BestIt\CodeSniffer\Helper\TokenHelper; use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\ClassRegistrationTrait; + use function count; use function substr_count; + use const T_CLOSE_CURLY_BRACKET; use const T_OPEN_CURLY_BRACKET; use const T_SEMICOLON; @@ -62,18 +64,18 @@ class TraitUseSpacingSniff extends AbstractSniff */ private const LINES_BETWEEN_USES = 0; - /** - * The message to the user for the error before usages. - */ - private const MESSAGE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE = - 'Expected %d lines before first use statement, found %d.'; - /** * The message to the user for the error after the last usage. */ private const MESSAGE_INCORRECT_LINES_COUNT_AFTER_LAST_USE = 'Expected %d lines after last use statement, found %d.'; + /** + * The message to the user for the error before usages. + */ + private const MESSAGE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE = + 'Expected %d lines before first use statement, found %d.'; + /** * The message to the user for the error between uses. */ diff --git a/src/Standards/BestIt/Sniffs/Spacing/UseSpacingSniff.php b/src/Standards/BestIt/Sniffs/Spacing/UseSpacingSniff.php index 0573e6b3..86f43cc0 100644 --- a/src/Standards/BestIt/Sniffs/Spacing/UseSpacingSniff.php +++ b/src/Standards/BestIt/Sniffs/Spacing/UseSpacingSniff.php @@ -7,11 +7,15 @@ use SlevomatCodingStandard\Sniffs\Namespaces\UseSpacingSniff as BaseSniff; /** - * Forces just one line before and one line after the usages. + * Forces just one line before and one line after the usages, and one line between different use types. * * @author blange * @package BestIt\Sniffs\Spacing */ class UseSpacingSniff extends BaseSniff { + /** + * Require one blank line between different use types (class/function/const) to comply with PSR-12. + */ + public int $linesCountBetweenUseTypes = 1; } diff --git a/src/Standards/BestIt/Sniffs/Strings/ConcatCalculationSniff.php b/src/Standards/BestIt/Sniffs/Strings/ConcatCalculationSniff.php index fb08dda5..822f9071 100644 --- a/src/Standards/BestIt/Sniffs/Strings/ConcatCalculationSniff.php +++ b/src/Standards/BestIt/Sniffs/Strings/ConcatCalculationSniff.php @@ -6,6 +6,7 @@ use BestIt\CodeSniffer\CodeError; use BestIt\Sniffs\AbstractSniff; + use const T_CLOSE_CURLY_BRACKET; use const T_CLOSE_PARENTHESIS; use const T_CLOSE_SHORT_ARRAY; diff --git a/src/Standards/BestIt/Sniffs/TypeHints/ExplicitAssertionsSniff.php b/src/Standards/BestIt/Sniffs/TypeHints/ExplicitAssertionsSniff.php index 127eac3d..1cc6bdef 100644 --- a/src/Standards/BestIt/Sniffs/TypeHints/ExplicitAssertionsSniff.php +++ b/src/Standards/BestIt/Sniffs/TypeHints/ExplicitAssertionsSniff.php @@ -11,7 +11,7 @@ use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; -use SlevomatCodingStandard\Helpers\Annotation\VariableAnnotation; +use SlevomatCodingStandard\Helpers\Annotation; use SlevomatCodingStandard\Helpers\AnnotationHelper; use SlevomatCodingStandard\Helpers\IndentationHelper; use SlevomatCodingStandard\Helpers\TokenHelper; @@ -82,22 +82,22 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void $codePointer = $firstPointerOnPreviousLine; } - $variableAnnotations = AnnotationHelper::getAnnotationsByName($phpcsFile, $docCommentOpenPointer, '@var'); + $variableAnnotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer, '@var'); if (count($variableAnnotations) === 0) { return; } - /** @var VariableAnnotation $variableAnnotation */ + /** @var Annotation $variableAnnotation */ foreach (array_reverse($variableAnnotations) as $variableAnnotation) { if ($variableAnnotation->isInvalid()) { continue; } - if ($variableAnnotation->getVariableName() === null) { + if ($variableAnnotation->getValue()->variableName === '') { continue; } - $variableAnnotationType = $variableAnnotation->getType(); + $variableAnnotationType = $variableAnnotation->getValue()->type; if ($variableAnnotationType instanceof UnionTypeNode || $variableAnnotationType instanceof IntersectionTypeNode) { foreach ($variableAnnotationType->types as $typeNode) { @@ -115,7 +115,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void continue; } - if ($variableAnnotation->getVariableName() !== $tokens[$codePointer]['content']) { + if ($variableAnnotation->getValue()->variableName !== $tokens[$codePointer]['content']) { continue; } @@ -125,7 +125,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void } elseif ($tokens[$codePointer]['code'] === T_LIST) { $listParenthesisOpener = TokenHelper::findNextEffective($phpcsFile, $codePointer + 1); - $variablePointerInList = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getVariableName(), $listParenthesisOpener + 1, $tokens[$listParenthesisOpener]['parenthesis_closer']); + $variablePointerInList = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getValue()->variableName, $listParenthesisOpener + 1, $tokens[$listParenthesisOpener]['parenthesis_closer']); if ($variablePointerInList === null) { continue; } @@ -139,7 +139,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void continue; } - $variablePointerInList = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getVariableName(), $codePointer + 1, $tokens[$codePointer]['bracket_closer']); + $variablePointerInList = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getValue()->variableName, $codePointer + 1, $tokens[$codePointer]['bracket_closer']); if ($variablePointerInList === null) { continue; } @@ -149,7 +149,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void } else { if ($tokens[$codePointer]['code'] === T_WHILE) { - $variablePointerInWhile = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getVariableName(), $tokens[$codePointer]['parenthesis_opener'] + 1, $tokens[$codePointer]['parenthesis_closer']); + $variablePointerInWhile = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getValue()->variableName, $tokens[$codePointer]['parenthesis_opener'] + 1, $tokens[$codePointer]['parenthesis_closer']); if ($variablePointerInWhile === null) { continue; } @@ -160,7 +160,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void } } else { $asPointer = TokenHelper::findNext($phpcsFile, T_AS, $tokens[$codePointer]['parenthesis_opener'] + 1, $tokens[$codePointer]['parenthesis_closer']); - $variablePointerInForeach = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getVariableName(), $asPointer + 1, $tokens[$codePointer]['parenthesis_closer']); + $variablePointerInForeach = TokenHelper::findNextContent($phpcsFile, T_VARIABLE, $variableAnnotation->getValue()->variableName, $asPointer + 1, $tokens[$codePointer]['parenthesis_closer']); if ($variablePointerInForeach === null) { continue; } @@ -205,7 +205,7 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void /** @var IdentifierTypeNode|ThisTypeNode|UnionTypeNode $variableAnnotationType */ $variableAnnotationType = $variableAnnotationType; - $assertion = $this->createAssert($variableAnnotation->getVariableName(), $variableAnnotationType); + $assertion = $this->createAssert($variableAnnotation->getValue()->variableName, $variableAnnotationType); if ($pointerToAddAssertion < $docCommentClosePointer && array_key_exists($pointerAfterDocComment + 1, $tokens)) { $phpcsFile->fixer->addContentBefore( diff --git a/src/Standards/BestIt/Sniffs/TypeHints/PropertyTypeHintSniff.php b/src/Standards/BestIt/Sniffs/TypeHints/PropertyTypeHintSniff.php index b583e62a..0c826b88 100644 --- a/src/Standards/BestIt/Sniffs/TypeHints/PropertyTypeHintSniff.php +++ b/src/Standards/BestIt/Sniffs/TypeHints/PropertyTypeHintSniff.php @@ -17,24 +17,21 @@ class PropertyTypeHintSniff extends SlevomatPropertyTypeHintSniff /** * Enforces to transform @var int into native int typehint. * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint - * @var bool bool/null + * @var bool|null */ - public $enableNativeTypeHint = true; + public ?bool $enableNativeTypeHint = true; /** * Enforces to transform @var mixed into native mixed typehint. * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint * @var bool|null */ - public $enableMixedTypeHint = true; + public ?bool $enableMixedTypeHint = true; /** * Enforces to transform @var string|int into native string|int typehint. * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.PropertyTypeHint.MissingNativeTypeHint - * @var bool bool|null + * @var bool|null */ - public $enableUnionTypeHint = true; + public ?bool $enableUnionTypeHint = true; } diff --git a/src/Standards/BestIt/Sniffs/TypeHints/ReturnTypeDeclarationSniff.php b/src/Standards/BestIt/Sniffs/TypeHints/ReturnTypeDeclarationSniff.php index 9d1561ff..3e19b27f 100644 --- a/src/Standards/BestIt/Sniffs/TypeHints/ReturnTypeDeclarationSniff.php +++ b/src/Standards/BestIt/Sniffs/TypeHints/ReturnTypeDeclarationSniff.php @@ -9,19 +9,25 @@ use BestIt\Sniffs\AbstractSniff; use BestIt\Sniffs\DocPosProviderTrait; use BestIt\Sniffs\SuppressingTrait; -use SlevomatCodingStandard\Helpers\Annotation\ReturnAnnotation; +use SlevomatCodingStandard\Helpers\Annotation; use SlevomatCodingStandard\Helpers\FunctionHelper; use SlevomatCodingStandard\Helpers\TokenHelper; use SlevomatCodingStandard\Helpers\TypeHintHelper; + use function array_filter; use function array_intersect; +use function array_map; use function count; use function explode; +use function implode; use function in_array; use function phpversion; +use function strlen; +use function strpos; use function strtolower; use function substr; use function version_compare; + use const T_FUNCTION; /** @@ -50,6 +56,8 @@ class ReturnTypeDeclarationSniff extends AbstractSniff */ private const NULL_TYPES = ['null', 'void']; + private const RETURN_TYPE_SEPARATOR = ' | '; + /** * Null as a return has no real return type, so we use this as a fallback. * @@ -113,6 +121,7 @@ private function addReturnType(): void /** * Returns true if this sniff may run. + * * @return bool */ protected function areRequirementsMet(): bool @@ -131,27 +140,37 @@ private function createReturnType(): string $returnTypeHint = ''; $typeCount = count($this->typesForFix); - foreach ($this->typesForFix as $type) { - // We add the default value if only null is used (which has no real native return type). - if ($type === 'null' && ($typeCount === 1)) { - $returnTypeHint = $this->defaultNullReturn; - break; // We still need this break to prevent further execution of the default value. - } + if ($typeCount === 1) { + return $this->typesForFix[0] === 'null' ? $this->defaultNullReturn : $this->typesForFix[0]; + } - // We add the question mark if there is a nullable type. - if (in_array($type, self::NULL_TYPES, true) && ($typeCount > 1)) { - $returnTypeHint = '?' . $returnTypeHint; - continue; // We still need this continue to prevent further execution of the questionmark. + if ($typeCount === 2) { + foreach ($this->typesForFix as $type) { + // We add the question mark if there is a nullable type. + if (in_array($type, self::NULL_TYPES, true)) { + $returnTypeHint = '?' . $returnTypeHint; + continue; // We still need this continue to prevent further execution of the questionmark. + } + + // We add a fixable "native" type. We do not fix custom classes (because it would have side effects to + // the imported usage of classes. + $returnTypeHint .= (TypeHintHelper::isSimpleTypeHint($type)) + ? TypeHintHelper::convertLongSimpleTypeHintToShort($type) + : $type; } - // We add a fixable "native" type. We do not fix custom classes (because it would have side effects to the - // imported usage of classes. - $returnTypeHint .= (TypeHintHelper::isSimpleTypeHint($type)) - ? TypeHintHelper::convertLongSimpleTypeHintToShort($type) - : $type; + return $returnTypeHint; } - return $returnTypeHint; + return implode( + '|', + array_map( + fn(string $type): string => TypeHintHelper::isSimpleTypeHint($type) + ? TypeHintHelper::convertLongSimpleTypeHintToShort($type) + : $type, + $this->typesForFix, + ), + ); } /** @@ -166,7 +185,7 @@ protected function fixDefaultProblem(CodeWarning $exception): void // Satisfy PHPMD unset($exception); - // This method is called, if it the error is not marked as fixable. So check our internal marker again. + // This method is called, if the error is not marked as fixable. So check our internal marker again. if ($this->typesForFix) { $this->addReturnType(); } @@ -189,15 +208,26 @@ private function getFunctionName(): string /** * Returns the return types of the annotation. * - * @param null|ReturnAnnotation $annotation + * @param null|Annotation $annotation * * @return array */ - private function getReturnsFromAnnotation(?ReturnAnnotation $annotation): array + private function getReturnsFromAnnotation(?Annotation $annotation): array { - return $this->isFilledReturnAnnotation($annotation) - ? explode('|', preg_split('~\\s+~', $annotation->getContent())[0]) - : []; + $returns = []; + + if ($this->isFilledReturnAnnotation($annotation)) { + $annotationValue = (string) $annotation->getValue(); + + if (strpos($annotationValue, self::RETURN_TYPE_SEPARATOR) === false) { + $returns[] = $annotationValue; + } else { + // The annotated value can be something like (array | null | string) + $returns = explode(self::RETURN_TYPE_SEPARATOR, substr($annotationValue, 1, strlen($annotationValue) - 2)); + } + } + + return $returns; } /** @@ -206,11 +236,11 @@ private function getReturnsFromAnnotation(?ReturnAnnotation $annotation): array * Usable means, that there should be one type != mixed in the return-annotation or a nullable type, which means * 2 types like null|$ANYTYPE. * - * @param ReturnAnnotation $annotation + * @param Annotation $annotation * * @return array|null Null if there are no usable types or the usable types. */ - private function getUsableReturnTypes(ReturnAnnotation $annotation): ?array + private function getUsableReturnTypes(Annotation $annotation): ?array { $return = null; @@ -223,7 +253,7 @@ private function getUsableReturnTypes(ReturnAnnotation $annotation): ?array version_compare(phpversion(), '7.1.0', '>=') && (count(array_intersect($returnTypes, self::NULL_TYPES)) === 1); - $return = ($justOneReturn || $isNullableType) ? $returnTypes : null; + $return = ($justOneReturn || $isNullableType || $returnTypeCount > 2) ? $returnTypes : null; } return $return; @@ -258,13 +288,13 @@ private function isCustomArrayType(string $returnTypeHint): bool /** * Check if function has a return annotation * - * @param ReturnAnnotation|null $returnAnnotation Annotation of the function + * @param Annotation|null $returnAnnotation Annotation of the function * * @return bool Function has a annotation */ - private function isFilledReturnAnnotation(?ReturnAnnotation $returnAnnotation = null): bool + private function isFilledReturnAnnotation(?Annotation $returnAnnotation = null): bool { - return $returnAnnotation && $returnAnnotation->getContent(); + return $returnAnnotation && (string) $returnAnnotation->getValue(); } /** @@ -307,9 +337,9 @@ private function loadFunctionName(): string /** * Loads the return annotation for this method. * - * @return null|ReturnAnnotation + * @return null|Annotation */ - protected function loadReturnAnnotation(): ?ReturnAnnotation + protected function loadReturnAnnotation(): ?Annotation { return FunctionHelper::findReturnAnnotation($this->getFile(), $this->stackPos); } @@ -337,7 +367,7 @@ protected function processToken(): void public function register(): array { - return TokenHelper::$functionTokenCodes; + return TokenHelper::FUNCTION_TOKEN_CODES; } /** diff --git a/src/Standards/BestIt/Sniffs/TypeHints/SuggestExplicitReturnTypeSniff.php b/src/Standards/BestIt/Sniffs/TypeHints/SuggestExplicitReturnTypeSniff.php index ab2a2514..05080a23 100644 --- a/src/Standards/BestIt/Sniffs/TypeHints/SuggestExplicitReturnTypeSniff.php +++ b/src/Standards/BestIt/Sniffs/TypeHints/SuggestExplicitReturnTypeSniff.php @@ -37,6 +37,6 @@ protected function processToken(): void public function register(): array { - return TokenHelper::$functionTokenCodes; + return TokenHelper::FUNCTION_TOKEN_CODES; } } diff --git a/src/Standards/BestIt/ruleset.xml b/src/Standards/BestIt/ruleset.xml index cdf536af..3d64eb94 100644 --- a/src/Standards/BestIt/ruleset.xml +++ b/src/Standards/BestIt/ruleset.xml @@ -9,9 +9,7 @@ The best it coding standard. - - - + diff --git a/tests/CodeSniffer/CodeErrorTest.php b/tests/CodeSniffer/CodeErrorTest.php new file mode 100644 index 00000000..ea802f92 --- /dev/null +++ b/tests/CodeSniffer/CodeErrorTest.php @@ -0,0 +1,55 @@ +fixture = new CodeError(self::CODE, self::MESSAGE, self::STACK_POSITION); + } + + public function testConstructorSetsCode(): void + { + static::assertSame(self::CODE, $this->fixture->getCode()); + } + + public function testConstructorSetsMessage(): void + { + static::assertSame(self::MESSAGE, $this->fixture->getMessage()); + } + + public function testConstructorSetsStackPosition(): void + { + static::assertSame(self::STACK_POSITION, $this->fixture->getStackPosition()); + } + + public function testExtendsCodeWarning(): void + { + static::assertInstanceOf(CodeWarning::class, $this->fixture); + } + + public function testExtendsException(): void + { + static::assertInstanceOf(Exception::class, $this->fixture); + } + + public function testImplementsThrowable(): void + { + static::assertInstanceOf(Throwable::class, $this->fixture); + } +} diff --git a/tests/CodeSniffer/CodeWarningTest.php b/tests/CodeSniffer/CodeWarningTest.php new file mode 100644 index 00000000..0de82fd7 --- /dev/null +++ b/tests/CodeSniffer/CodeWarningTest.php @@ -0,0 +1,101 @@ +fixture = new CodeWarning(self::CODE, self::MESSAGE, self::STACK_POSITION); + } + + public function testConstructorSetsCodeAsString(): void + { + static::assertSame(self::CODE, $this->fixture->getCode()); + } + + public function testConstructorSetsMessage(): void + { + static::assertSame(self::MESSAGE, $this->fixture->getMessage()); + } + + public function testConstructorSetsStackPosition(): void + { + static::assertSame(self::STACK_POSITION, $this->fixture->getStackPosition()); + } + + public function testExtendsException(): void + { + static::assertInstanceOf(Exception::class, $this->fixture); + } + + public function testGetPayloadReturnsEmptyArrayByDefault(): void + { + static::assertSame([], $this->fixture->getPayload()); + } + + public function testGetTokenReturnsNullByDefault(): void + { + static::assertNull($this->fixture->getToken()); + } + + public function testImplementsThrowable(): void + { + static::assertInstanceOf(Throwable::class, $this->fixture); + } + + public function testIsFixableDoesNotChangeWhenNullPassed(): void + { + $this->fixture->isFixable(true); + + $oldStatus = $this->fixture->isFixable(null); + + static::assertTrue($oldStatus); + static::assertTrue($this->fixture->isFixable()); + } + + public function testIsFixableReturnsFalseByDefault(): void + { + static::assertFalse($this->fixture->isFixable()); + } + + public function testIsFixableReturnsOldStatusWhenSettingNew(): void + { + $oldStatus = $this->fixture->isFixable(true); + + static::assertFalse($oldStatus); + static::assertTrue($this->fixture->isFixable()); + } + + public function testSetPayloadStoresAndReturnsSelf(): void + { + $payload = ['foo' => 'bar']; + $result = $this->fixture->setPayload($payload); + + static::assertSame($this->fixture, $result); + static::assertSame($payload, $this->fixture->getPayload()); + } + + public function testSetTokenStoresAndReturnsSelf(): void + { + $token = ['content' => 'foo', 'type' => 'T_STRING']; + $result = $this->fixture->setToken($token); + + static::assertSame($this->fixture, $result); + static::assertSame($token, $this->fixture->getToken()); + } +} diff --git a/tests/CodeSniffer/Helper/ClassHelperTest.php b/tests/CodeSniffer/Helper/ClassHelperTest.php index a7226e09..5e006cf3 100644 --- a/tests/CodeSniffer/Helper/ClassHelperTest.php +++ b/tests/CodeSniffer/Helper/ClassHelperTest.php @@ -18,6 +18,10 @@ class ClassHelperTest extends TestCase { use FileHelperTrait; + private const SEARCH_START = 29; + + private const TRAIT_POINTERS = [36, 42]; + /** * This is the relevant search start for the tests. * @@ -36,7 +40,7 @@ protected function setUp(): void { $this->file = $this->getFile(__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures/ClassHelper/TestClass.php'); - $this->searchStart = 44; + $this->searchStart = self::SEARCH_START; } /** @@ -46,7 +50,7 @@ protected function setUp(): void */ public function testGetTraitUsePointers(): void { - static::assertSame([51, 57], ClassHelper::getTraitUsePointers($this->file, 44)); + static::assertSame(self::TRAIT_POINTERS, ClassHelper::getTraitUsePointers($this->file, $this->searchStart)); } /** diff --git a/tests/CodeSniffer/Helper/DocTagHelperTest.php b/tests/CodeSniffer/Helper/DocTagHelperTest.php index 177a7946..ca3936df 100644 --- a/tests/CodeSniffer/Helper/DocTagHelperTest.php +++ b/tests/CodeSniffer/Helper/DocTagHelperTest.php @@ -5,6 +5,7 @@ namespace BestIt\CodeSniffer\Helper; use PHPUnit\Framework\TestCase; + use const T_CLASS; /** @@ -33,7 +34,7 @@ protected function setUp(): void { $file = $this->getFile(__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures/DocTagHelper/ORMJoinsOnMethod.php'); - $this->testedObject = new DocTagHelper($file, 23); + $this->testedObject = new DocTagHelper($file, 16); } /** @@ -44,365 +45,433 @@ protected function setUp(): void public function testGetCommentTagTokens(): void { $expectedArray = [ - 36 => [ + 29 => [ 'content' => '@ORM\\JoinTable(name="bestit_genius_offering_related_article",', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 9, 'column' => 8, 'length' => 61, 'level' => 1, - 'conditions' => [16 => T_CLASS,], + 'conditions' => [9 => T_CLASS,], 'contents' => [ - 42 => [ + 35 => [ 'content' => 'joinColumns={', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 10, 'column' => 13, 'length' => 13, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 47 => [ + 40 => [ 'content' => '@ORM\\JoinColumn(', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 11, 'column' => 17, 'length' => 16, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 52 => [ + 45 => [ 'content' => 'name="offering",', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 12, 'column' => 21, 'length' => 16, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 57 => [ + 50 => [ 'content' => 'referencedColumnName="id"', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 13, 'column' => 21, 'length' => 25, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 62 => [ + 55 => [ 'content' => ')', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 14, 'column' => 17, 'length' => 1, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 67 => [ + 60 => [ 'content' => '},', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 15, 'column' => 13, 'length' => 2, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 72 => [ + 65 => [ 'content' => 'inverseJoinColumns={', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 16, 'column' => 13, 'length' => 20, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 77 => [ + 70 => [ 'content' => '@ORM\\JoinColumn(', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 17, 'column' => 17, 'length' => 16, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 82 => [ + 75 => [ 'content' => 'name="article",', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 18, 'column' => 21, 'length' => 15, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 87 => [ + 80 => [ 'content' => 'referencedColumnName="id"', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 19, 'column' => 21, 'length' => 25, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 92 => [ + 85 => [ 'content' => ')', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 20, 'column' => 17, 'length' => 1, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 97 => [ + 90 => [ 'content' => '}', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 21, 'column' => 13, 'length' => 1, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 102 => [ + 95 => [ 'content' => ')', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 22, 'column' => 8, 'length' => 1, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 106 => [ + 99 => [ 'content' => '@ORM\\ManyToMany(targetEntity="Shopware\\Models\\Article\\Detail")', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 23, 'column' => 8, 'length' => 62, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [], ], - 111 => [ + 104 => [ 'content' => '@throws', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 24, 'column' => 8, 'length' => 7, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 114 => [ + 107 => [ 'content' => 'RuntimeException', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 24, 'column' => 16, 'length' => 16, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 118 => [ + 111 => [ 'content' => '@var', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 25, 'column' => 8, 'length' => 4, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 121 => [ + 114 => [ 'content' => 'Collection Now that we know who you are, I know who I am. I\'m not a mistake! ' . 'It all makes sense! In a comic,', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 25, 'column' => 13, 'length' => 108, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 126 => [ + 119 => [ 'content' => 'you know how you can tell who the arch-villain\'s going to be? He\'s the exact ' . 'opposite of the hero. And most', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 26, 'column' => 13, 'length' => 107, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 131 => [ + 124 => [ 'content' => 'times they\'re friends, like you and me! I should\'ve known way back when... ' . 'You know why, David? Because of', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 27, 'column' => 13, 'length' => 106, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], - 136 => [ + 129 => [ 'content' => 'the kids. They called me Mr Glass.', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 28, 'column' => 13, 'length' => 34, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 143 => [ + 136 => [ 'content' => '@param', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 30, 'column' => 8, 'length' => 6, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 146 => [ + 139 => [ 'content' => 'string $param1', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 30, 'column' => 15, 'length' => 14, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 150 => [ + 143 => [ 'content' => '@param', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 31, 'column' => 8, 'length' => 6, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 153 => [ + 146 => [ 'content' => 'string $param2', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 31, 'column' => 15, 'length' => 14, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 160 => [ + 153 => [ 'content' => '@todo', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 33, 'column' => 8, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 163 => [ + 156 => [ 'content' => 'Test1', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 33, 'column' => 14, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 167 => [ + 160 => [ 'content' => '@todo', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 34, 'column' => 8, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 170 => [ + 163 => [ 'content' => 'Test2', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 34, 'column' => 14, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 174 => [ + 167 => [ 'content' => '@todo', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 35, 'column' => 8, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 177 => [ + 170 => [ 'content' => 'Test3', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 35, 'column' => 14, 'length' => 5, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], - 184 => [ + 177 => [ 'content' => '@return', 'code' => 'PHPCS_T_DOC_COMMENT_TAG', 'type' => 'T_DOC_COMMENT_TAG', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 37, 'column' => 8, 'length' => 7, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], 'contents' => [ - 187 => [ + 180 => [ 'content' => 'void', 'code' => 'PHPCS_T_DOC_COMMENT_STRING', 'type' => 'T_DOC_COMMENT_STRING', + 'comment_opener' => 16, + 'comment_closer' => 182, 'line' => 37, 'column' => 16, 'length' => 4, 'level' => 1, - 'conditions' => [16 => T_CLASS], + 'conditions' => [9 => T_CLASS], ], ], ], diff --git a/tests/CodeSniffer/Helper/FileHelper.php b/tests/CodeSniffer/Helper/FileHelper.php index 1c6c182e..f5ab5c4a 100644 --- a/tests/CodeSniffer/Helper/FileHelper.php +++ b/tests/CodeSniffer/Helper/FileHelper.php @@ -8,6 +8,7 @@ use PHP_CodeSniffer\Exceptions\RuntimeException; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Ruleset; + use function file_get_contents; /** diff --git a/tests/CodeSniffer/Helper/TokenHelperTest.php b/tests/CodeSniffer/Helper/TokenHelperTest.php index 1ca0c5b8..b8efa3fb 100644 --- a/tests/CodeSniffer/Helper/TokenHelperTest.php +++ b/tests/CodeSniffer/Helper/TokenHelperTest.php @@ -7,6 +7,7 @@ use PHP_CodeSniffer\Exceptions\RuntimeException; use PHPUnit\Framework\TestCase; use SlevomatCodingStandard\Helpers\TokenHelper as BaseHelper; + use const DIRECTORY_SEPARATOR; use const T_DOC_COMMENT_TAG; use const T_IF; @@ -44,6 +45,17 @@ protected function setUp(): void $this->searchStart = 16; } + public function testConstants(): void + { + static::assertSame( + TokenHelper::ARRAY_TOKEN_CODES, + [ + T_ARRAY, + T_OPEN_SHORT_ARRAY, + ], + ); + } + /** * The doc comment should not contain any ifs! * @@ -61,7 +73,7 @@ public function testFindNextAllNone(): void */ public function testFindNextAllPrematureEnd(): void { - static::assertSame([38], TokenHelper::findNextAll($this->file, [T_DOC_COMMENT_TAG], $this->searchStart, 39)); + static::assertSame([31], TokenHelper::findNextAll($this->file, [T_DOC_COMMENT_TAG], $this->searchStart, 32)); } /** @@ -71,7 +83,7 @@ public function testFindNextAllPrematureEnd(): void */ public function testFindNextAllSuccess(): void { - static::assertSame([38, 45], TokenHelper::findNextAll($this->file, [T_DOC_COMMENT_TAG], $this->searchStart)); + static::assertSame([31, 38], TokenHelper::findNextAll($this->file, [T_DOC_COMMENT_TAG], $this->searchStart)); } /** @@ -82,7 +94,7 @@ public function testFindNextAllSuccess(): void public function testFindPreviousContentNone(): void { static::assertNull( - TokenHelper::findPreviousContent($this->file, [T_DOC_COMMENT_TAG], '@foobar', 45), + TokenHelper::findPreviousContent($this->file, [T_DOC_COMMENT_TAG], '@foobar', 38), ); } @@ -94,8 +106,8 @@ public function testFindPreviousContentNone(): void public function testFindPreviousContentSuccess(): void { static::assertSame( - 38, - TokenHelper::findPreviousContent($this->file, [T_DOC_COMMENT_TAG], '@author', 45), + 31, + TokenHelper::findPreviousContent($this->file, [T_DOC_COMMENT_TAG], '@author', 38), ); } diff --git a/tests/CodeSniffer/Helper/UseStatementHelperTest.php b/tests/CodeSniffer/Helper/UseStatementHelperTest.php index a0d72929..c1a5f8a4 100644 --- a/tests/CodeSniffer/Helper/UseStatementHelperTest.php +++ b/tests/CodeSniffer/Helper/UseStatementHelperTest.php @@ -5,9 +5,11 @@ namespace BestIt\CodeSniffer\Helper; use PHP_CodeSniffer\Files\File; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use SlevomatCodingStandard\Helpers\UseStatement; use SlevomatCodingStandard\Helpers\UseStatementHelper as BaseHelper; + use function mt_rand; /** @@ -23,23 +25,32 @@ class UseStatementHelperTest extends TestCase * * @return array */ - public function getTypeAsserts(): array + public static function getTypeAsserts(): array { return [ UseStatement::TYPE_CONSTANT => [UseStatement::TYPE_CONSTANT, 'const'], - UseStatement::TYPE_CLASS => [UseStatement::TYPE_CLASS], + UseStatement::TYPE_CLASS => [UseStatement::TYPE_CLASS, ''], UseStatement::TYPE_FUNCTION => [UseStatement::TYPE_FUNCTION, 'function'], ]; } + public static function getTypeOnlyAsserts(): array + { + return [ + UseStatement::TYPE_CONSTANT => [UseStatement::TYPE_CONSTANT], + UseStatement::TYPE_CLASS => [UseStatement::TYPE_CLASS], + UseStatement::TYPE_FUNCTION => [UseStatement::TYPE_FUNCTION], + ]; + } + /** * Checks if the correct value is returned. * - * @dataProvider getTypeAsserts * @param string $type * * @return void */ + #[DataProvider('getTypeOnlyAsserts')] public function testGetType(string $type): void { $useStatement = new UseStatement( @@ -52,21 +63,20 @@ public function testGetType(string $type): void static::assertSame( $type, - UseStatementHelper::getType($this->createMock(File::class), $useStatement), + UseStatementHelper::getType($this->createStub(File::class), $useStatement), ); } /** * Checks if the correct value is returned. * - * @dataProvider getTypeAsserts - * * @param string $type * @param string $name The name which should be used in php codes for uses. * * @return void */ - public function testGetTypeName(string $type, string $name = ''): void + #[DataProvider('getTypeAsserts')] + public function testGetTypeName(string $type, string $name): void { $useStatement = new UseStatement( 'bar', @@ -78,7 +88,7 @@ public function testGetTypeName(string $type, string $name = ''): void static::assertSame( $name, - UseStatementHelper::getTypeName($this->createMock(File::class), $useStatement), + UseStatementHelper::getTypeName($this->createStub(File::class), $useStatement), ); } diff --git a/tests/SniffTestCase.php b/tests/SniffTestCase.php index ed8eb84c..f221578e 100644 --- a/tests/SniffTestCase.php +++ b/tests/SniffTestCase.php @@ -4,13 +4,23 @@ namespace BestIt; -use Exception; use PHP_CodeSniffer\Files\File; use ReflectionClass; use ReflectionException; use SlevomatCodingStandard\Sniffs\TestCase as SlevomatTestCase; +use function array_map; +use function array_merge; +use function array_reverse; +use function basename; use function dirname; +use function explode; +use function glob; use function implode; +use function preg_match; +use function range; +use function sprintf; +use function str_replace; +use function strpos; use const DIRECTORY_SEPARATOR; /** @@ -211,6 +221,83 @@ protected function assertWarningsInFile( return $report; } + /** + * Returns a list of files which start with correct*. + * + * @return array With the path to a file as the first parameter. + */ + public function getCorrectFileListAsDataProvider(): array + { + $providerFiles = []; + + foreach (glob($this->getFixturePath() . '/correct/*.php') as $file) { + $providerFiles[basename($file)] = [$file]; + } + + return $providerFiles; + } + + /** + * Returns the metadata from the given file name if there is one. + * + * @param string $file + * @param array $errorData This method changes a marker for other files, if there is a file with a fixed marker. + * + * @return array + */ + protected function getMetadataFromFilenameAsAssertArray(string $file, array &$errorData): array + { + $fileMetaData = []; + $fileName = basename($file); + $matches = []; + $pattern = '/(?P\w+)(\(\w*\))?\.(?P[\d\-\,]*)(?P\.fixed)?\.php/'; + + if (preg_match($pattern, $fileName, $matches)) { + if (@$matches['fixedSuffix']) { + @$errorData[str_replace('.fixed', '', $fileName)][] = true; + } else { + $errorLines = explode(',', $matches['errorLines']); + + // Check if there is a range. + foreach ($errorLines as $index => $errorLine) { + if (strpos($errorLine, '-') !== false) { + unset($errorLines[$index]); + + $errorLines = array_merge($errorLines, range(...explode('-', $errorLine))); + } + } + + $fileMetaData = [ + $file, + $matches['code'], + array_map('intval', $errorLines), + ]; + } + } + + return $fileMetaData; + } + + /** + * Loads the assertion data out of the file names. + * + * @param bool $forErrors Load data for errors? + * + * @return array The assert data as data providers. + */ + protected function loadAssertData(bool $forErrors = true): array + { + $errorData = []; + + foreach ($this->getFixtureFiles($forErrors) as $file) { + if ($fileMetaData = $this->getMetadataFromFilenameAsAssertArray($file, $errorData)) { + $errorData[basename($file)] = $fileMetaData; + } + } + + return $errorData; + } + /** * Returns a list of files which start with correct* * @@ -320,6 +407,21 @@ private static function hasWarning(array $warningsOnLine, string $sniffCode, ?st return false; } + /** + * Returns the test files for errors or warnings. + * + * @param bool $forErrors Load data for errors? + * + * @return array The testable files. + */ + private function getFixtureFiles(bool $forErrors = true): array + { + return array_reverse(glob(sprintf( + $this->getFixturePath() . '/with_%s/*.php', + $forErrors ? 'errors' : 'warnings', + ))) ?: []; + } + /** * Returns the path to the fixture folder for this sniff. * diff --git a/tests/Sniffs/Classes/ModernClassNameReferenceSniffTest.php b/tests/Sniffs/Classes/ModernClassNameReferenceSniffTest.php index b70d8e4b..660760e8 100644 --- a/tests/Sniffs/Classes/ModernClassNameReferenceSniffTest.php +++ b/tests/Sniffs/Classes/ModernClassNameReferenceSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Classes; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_CLASS_C; use const T_NAME_FULLY_QUALIFIED; use const T_NAME_QUALIFIED; @@ -16,11 +18,17 @@ class ModernClassNameReferenceSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; - public function getRequiredConstantAsserts(): iterable + protected function getExpectedTokens(): array + { + return [T_CLASS_C, T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAME_RELATIVE]; + } + + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_CLASS_NAME_REFERENCED_VIA_FUNCTION_CALL' => [ @@ -34,11 +42,6 @@ public function getRequiredConstantAsserts(): iterable ]; } - protected function getExpectedTokens(): array - { - return [T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAME_RELATIVE, T_CLASS_C]; - } - protected function setUp(): void { parent::setUp(); diff --git a/tests/Sniffs/Commenting/AbstractDocSniffTest.php b/tests/Sniffs/Commenting/AbstractDocSniffTestCase.php similarity index 73% rename from tests/Sniffs/Commenting/AbstractDocSniffTest.php rename to tests/Sniffs/Commenting/AbstractDocSniffTestCase.php index 730a36af..c90d47d3 100644 --- a/tests/Sniffs/Commenting/AbstractDocSniffTest.php +++ b/tests/Sniffs/Commenting/AbstractDocSniffTestCase.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Commenting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use PHP_CodeSniffer\Sniffs\Sniff; +use PHPUnit\Framework\Attributes\DataProvider; + use function defined; /** @@ -16,8 +18,9 @@ * @author blange * @package BestIt\Sniffs\Commenting */ -abstract class AbstractDocSniffTest extends SniffTestCase +abstract class AbstractDocSniffTestCase extends SniffTestCase { + use SniffCorrectFilesTrait; use TestTokenRegistrationTrait; /** @@ -34,24 +37,24 @@ abstract class AbstractDocSniffTest extends SniffTestCase * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ - 'CODE_NO_LINE_AFTER_DOC_COMMENT' => ['CODE_NO_LINE_AFTER_DOC_COMMENT', 'NoLineAfterDocComment'], - 'CODE_NO_SUMMARY' => ['CODE_NO_SUMMARY', 'NoSummary'], - 'CODE_SUMMARY_TOO_LONG' => ['CODE_SUMMARY_TOO_LONG', 'SummaryTooLong'], - 'CODE_DOC_COMMENT_UC_FIRST' => ['CODE_DOC_COMMENT_UC_FIRST', 'DocCommentUcFirst'], + 'CODE_NO_LINE_AFTER_DOC_COMMENT' => ['CODE_NO_LINE_AFTER_DOC_COMMENT'], + 'CODE_NO_SUMMARY' => ['CODE_NO_SUMMARY'], + 'CODE_SUMMARY_TOO_LONG' => ['CODE_SUMMARY_TOO_LONG'], + 'CODE_DOC_COMMENT_UC_FIRST' => ['CODE_DOC_COMMENT_UC_FIRST'], ]; } /** * Checks if the api is extended. * - * @dataProvider getRequiredConstantAsserts * @param string $constant The name of the constant. * * @return void */ + #[DataProvider('getRequiredConstantAsserts')] public function testRequiredConstants(string $constant): void { static::assertTrue( diff --git a/tests/Sniffs/Commenting/ClassDocSniffTest.php b/tests/Sniffs/Commenting/ClassDocSniffTest.php index c5ec5604..0ecd4435 100644 --- a/tests/Sniffs/Commenting/ClassDocSniffTest.php +++ b/tests/Sniffs/Commenting/ClassDocSniffTest.php @@ -4,6 +4,8 @@ namespace BestIt\Sniffs\Commenting; +use BestIt\Sniffs\SniffErrorFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use PHP_CodeSniffer\Util\Tokens; /** @@ -13,8 +15,11 @@ * @package BestIt\Sniffs\Commenting * @see ClassDocSniff */ -class ClassDocSniffTest extends AbstractDocSniffTest +class ClassDocSniffTest extends AbstractDocSniffTestCase { + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; + /** * Returns the tokens which should be checked. * diff --git a/tests/Sniffs/Commenting/ConstantDocSniffTest.php b/tests/Sniffs/Commenting/ConstantDocSniffTest.php index 073ce61e..0c9ed841 100644 --- a/tests/Sniffs/Commenting/ConstantDocSniffTest.php +++ b/tests/Sniffs/Commenting/ConstantDocSniffTest.php @@ -4,6 +4,9 @@ namespace BestIt\Sniffs\Commenting; +use BestIt\Sniffs\SniffErrorFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; + use const T_CONST; /** @@ -13,8 +16,11 @@ * @package BestIt\Sniffs\Commenting * @see ConstantDocSniff */ -class ConstantDocSniffTest extends AbstractDocSniffTest +class ConstantDocSniffTest extends AbstractDocSniffTestCase { + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; + /** * Returns the tokens which should be checked. * diff --git a/tests/Sniffs/Commenting/EmptyLinesDocSniffTest.php b/tests/Sniffs/Commenting/EmptyLinesDocSniffTest.php index 5a330f81..5dd6ccfb 100644 --- a/tests/Sniffs/Commenting/EmptyLinesDocSniffTest.php +++ b/tests/Sniffs/Commenting/EmptyLinesDocSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\Commenting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; @@ -25,7 +26,8 @@ class EmptyLinesDocSniffTest extends SniffTestCase { use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; /** * Get the expected tokens. @@ -44,7 +46,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_EMPTY_LINES_FOUND' => ['CODE_EMPTY_LINES_FOUND', 'EmptyLinesFound'], diff --git a/tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTest.php b/tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTestCase.php similarity index 91% rename from tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTest.php rename to tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTestCase.php index fc4b6bd1..591ee8b7 100644 --- a/tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTest.php +++ b/tests/Sniffs/Commenting/Fixtures/RedundantWhitespaceSniff/correct/AbstractDocSniffTestCase.php @@ -5,7 +5,7 @@ namespace BestIt\Sniffs\Commenting; use BestIt\SniffTestCase; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use PHP_CodeSniffer\Sniffs\Sniff; use function defined; @@ -16,9 +16,9 @@ * @author blange * @package BestIt\Sniffs\Commenting */ -abstract class AbstractDocSniffsTest extends SniffTestCase +abstract class AbstractDocSniffsTestCase extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; use TestTokenRegistrationTrait; /** diff --git a/tests/Sniffs/Commenting/FunctionDocSniffTest.php b/tests/Sniffs/Commenting/FunctionDocSniffTest.php index 15569adb..2f18702b 100644 --- a/tests/Sniffs/Commenting/FunctionDocSniffTest.php +++ b/tests/Sniffs/Commenting/FunctionDocSniffTest.php @@ -4,6 +4,9 @@ namespace BestIt\Sniffs\Commenting; +use BestIt\Sniffs\SniffErrorFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; + use const T_FUNCTION; /** @@ -13,8 +16,11 @@ * @package BestIt\Sniffs\Commenting * @see FunctionDocSniff */ -class FunctionDocSniffTest extends AbstractDocSniffTest +class FunctionDocSniffTest extends AbstractDocSniffTestCase { + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; + /** * Returns the tokens which should be checked. * diff --git a/tests/Sniffs/Commenting/PropertyDocSniffTest.php b/tests/Sniffs/Commenting/PropertyDocSniffTest.php index a5ddb4a6..833e8677 100644 --- a/tests/Sniffs/Commenting/PropertyDocSniffTest.php +++ b/tests/Sniffs/Commenting/PropertyDocSniffTest.php @@ -4,6 +4,9 @@ namespace BestIt\Sniffs\Commenting; +use BestIt\Sniffs\SniffErrorFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; + use const T_VARIABLE; /** @@ -12,8 +15,11 @@ * @author blange * @package BestIt\Sniffs\Commenting */ -class PropertyDocSniffTest extends AbstractDocSniffTest +class PropertyDocSniffTest extends AbstractDocSniffTestCase { + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; + /** * Returns the tokens which should be checked. * diff --git a/tests/Sniffs/Commenting/RedundantWhitespaceSniffTest.php b/tests/Sniffs/Commenting/RedundantWhitespaceSniffTest.php index 7c567438..de8ed88f 100644 --- a/tests/Sniffs/Commenting/RedundantWhitespaceSniffTest.php +++ b/tests/Sniffs/Commenting/RedundantWhitespaceSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Commenting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_STAR; /** @@ -18,31 +20,32 @@ */ class RedundantWhitespaceSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { return [ - 'CODE_ERROR_REDUNDANT_WHITESPACE' => ['CODE_ERROR_REDUNDANT_WHITESPACE', 'RedundantWhitespace'], + T_DOC_COMMENT_STAR, ]; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { return [ - T_DOC_COMMENT_STAR, + 'CODE_ERROR_REDUNDANT_WHITESPACE' => ['CODE_ERROR_REDUNDANT_WHITESPACE', 'RedundantWhitespace'], ]; } diff --git a/tests/Sniffs/Comparisons/EmptyArrayForComparisonSniffTest.php b/tests/Sniffs/Comparisons/EmptyArrayForComparisonSniffTest.php index 8cb1307f..cd683f43 100644 --- a/tests/Sniffs/Comparisons/EmptyArrayForComparisonSniffTest.php +++ b/tests/Sniffs/Comparisons/EmptyArrayForComparisonSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Comparisons; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_IS_EQUAL; use const T_IS_IDENTICAL; use const T_IS_NOT_EQUAL; @@ -21,7 +23,8 @@ */ class EmptyArrayForComparisonSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -40,7 +43,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'EmptyArray' => ['CODE_EMPTY_ARRAY', 'EmptyArray'], diff --git a/tests/Sniffs/Comparisons/EqualOperatorSniffTest.php b/tests/Sniffs/Comparisons/EqualOperatorSniffTest.php index e19dd7d5..7cb00072 100644 --- a/tests/Sniffs/Comparisons/EqualOperatorSniffTest.php +++ b/tests/Sniffs/Comparisons/EqualOperatorSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Comparisons; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_IS_NOT_EQUAL; /** @@ -18,7 +20,8 @@ */ class EqualOperatorSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_EQUAL_OPERATOR_FOUND' => ['CODE_EQUAL_OPERATOR_FOUND', 'EqualOperatorFound'], diff --git a/tests/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniffTest.php b/tests/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniffTest.php index 295a7815..8535b706 100644 --- a/tests/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniffTest.php +++ b/tests/Sniffs/Comparisons/ParasOfNegativeInstanceOfSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Comparisons; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_INSTANCEOF; /** @@ -18,7 +20,8 @@ */ class ParasOfNegativeInstanceOfSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return iterable */ - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_MISSING_PARAS_AROUND_NEG_INSTANCE_OF' => [ diff --git a/tests/Sniffs/DefaultSniffIntegrationTestTrait.php b/tests/Sniffs/DefaultSniffIntegrationTestTrait.php deleted file mode 100644 index abc7fe28..00000000 --- a/tests/Sniffs/DefaultSniffIntegrationTestTrait.php +++ /dev/null @@ -1,243 +0,0 @@ - - * @package BestIt\Sniffs - */ -trait DefaultSniffIntegrationTestTrait -{ - /** - * Returns a list of files which start with correct* - * - * @return array With the path to a file as the first parameter. - */ - public function getCorrectFileListAsDataProvider(): array - { - $providerFiles = []; - - foreach (glob($this->getFixturePath() . '/correct/*.php') as $file) { - $providerFiles[basename($file)] = [$file]; - } - - return $providerFiles; - } - - /** - * Returns the metadata from the given file name if there is one. - * - * @param string $file - * @param array $errorData This method changes a marker for other files, if there is a file with a fixed marker. - * - * @return array - */ - protected function getMetadataFromFilenameAsAssertArray(string $file, array &$errorData): array - { - $fileMetaData = []; - $fileName = basename($file); - $matches = []; - $pattern = '/(?P\w+)(\(\w*\))?\.(?P[\d\-\,]*)(?P\.fixed)?\.php/'; - - if (preg_match($pattern, $fileName, $matches)) { - if (@$matches['fixedSuffix']) { - @$errorData[str_replace('.fixed', '', $fileName)][] = true; - } else { - $errorLines = explode(',', $matches['errorLines']); - - // Check if there is a range. - foreach ($errorLines as $index => $errorLine) { - if (strpos($errorLine, '-') !== false) { - unset($errorLines[$index]); - - $errorLines = array_merge($errorLines, range(...explode('-', $errorLine))); - } - } - - $fileMetaData = [ - $file, - $matches['code'], - array_map('intval', $errorLines), - ]; - } - } - - return $fileMetaData; - } - - /** - * Test that the given files contain no errors. - * - * @dataProvider getCorrectFileListAsDataProvider - * @param string $file Provided file to test - * - * @return void - */ - public function testCorrect(string $file): void - { - $this->assertFileCorrect($file); - } - - /** - * Tests files which have to be without errors. - * - * @param string $file File to test - * - * @return void - */ - abstract protected function assertFileCorrect(string $file): void; - - /** - * Tests errors. - * - * @dataProvider getErrorAsserts - * - * @param string $file Fixture file - * @param string $error Error code - * @param int[] $lines Lines where the error code occurs - * @param bool $withFixable Should we checked the fixed version? - * - * @return void - */ - public function testErrors(string $file, string $error, array $lines, bool $withFixable = false): void - { - $report = $this->assertErrorsInFile($file, $error, $lines); - - if ($withFixable) { - $this->assertAllFixedInFile($report); - } - } - - /** - * Asserts all errors in a given file. - * - * @param string $file Filename of the fixture - * @param string $error Error code - * @param int[] $lines Array of lines where the error code occurs - * @param array $sniffProperties Array of sniff properties - * - * @return File The php cs file - */ - abstract protected function assertErrorsInFile( - string $file, - string $error, - array $lines, - array $sniffProperties = [], - ): File; - - /** - * Tests warnings. - * - * @dataProvider getWarningAsserts - * - * @param string $file Fixture file - * @param string $warning Code of the warning. - * @param int[] $lines Lines where the error code occurs - * @param bool $withFixable Should we test a fixable? - * - * @return void - */ - public function testWarnings(string $file, string $warning, array $lines, bool $withFixable = false): void - { - $report = $this->assertWarningsInFile($file, $warning, $lines); - - if ($withFixable) { - $this->assertAllFixedInFile($report); - } - } - - /** - * Returns data for errors. - * - * @return array List of error data (Filepath, error code, error lines, fixable) - */ - public function getErrorAsserts(): array - { - return $this->loadAssertData(); - } - - /** - * Loads the assertion data out of the file names. - * - * The file name gives information about which errors in which line should occur. - * Example files would be ErrorCode.1.php, ErrorCode.1,2,3.php, ErrorCode.1,2,3.fixed.php. The error code must be - * the original code value from your sniff, the numbers after the first dot are the erroneous lines. - * - * If you provide an additional file which is suffixed with "fixed" then this is the correct formatted file for its - * erroneous sibling. - * - * @param bool $forErrors Load data for errors? - * - * @return array The assert data as data providers. - */ - private function loadAssertData(bool $forErrors = true): array - { - $errorData = []; - - foreach ($this->getFixtureFiles($forErrors) as $file) { - if ($fileMetaData = $this->getMetadataFromFilenameAsAssertArray($file, $errorData)) { - $errorData[basename($file)] = $fileMetaData; - } - } - - return $errorData; - } - - /*** - * Returns the test files for errors or warnings. - * - * @param bool $forErrors Load data for errors? - * - * @return array The testable files. - */ - private function getFixtureFiles(bool $forErrors = true): array - { - return array_reverse(glob(sprintf( - $this->getFixturePath() . '/with_%s/*.php', - $forErrors ? 'errors' : 'warnings', - ))) ?: []; - } - - /** - * Returns data for warnings. - * - * @return array List of warnig data (Filepath, error code, error lines, fixable) - */ - public function getWarningAsserts(): array - { - return $this->loadAssertData(false); - } - - /** - * Asserts all warnings in a given file. - * - * @throws Exception - * - * @param string $file Filename of the fixture - * @param string $error Error code - * @param int[] $lines Array of lines where the error code occurs - * @param array $sniffProperties Array of sniff properties - * - * @return File The php cs file - */ - abstract protected function assertWarningsInFile( - string $file, - string $error, - array $lines, - array $sniffProperties = [], - ): File; -} diff --git a/tests/Sniffs/DocTags/AuthorTagSniffTest.php b/tests/Sniffs/DocTags/AuthorTagSniffTest.php index 1e1bc635..90d22cc6 100644 --- a/tests/Sniffs/DocTags/AuthorTagSniffTest.php +++ b/tests/Sniffs/DocTags/AuthorTagSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_TAG; /** @@ -18,7 +20,8 @@ */ class AuthorTagSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_TAG_CONTENT_FORMAT_INVALID' => ['CODE_TAG_CONTENT_FORMAT_INVALID', 'TagContentFormatInvalid'], diff --git a/tests/Sniffs/DocTags/DeprecatedTagSniffTest.php b/tests/Sniffs/DocTags/DeprecatedTagSniffTest.php index fabfc631..76c6593d 100644 --- a/tests/Sniffs/DocTags/DeprecatedTagSniffTest.php +++ b/tests/Sniffs/DocTags/DeprecatedTagSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_TAG; /** @@ -18,31 +20,32 @@ */ class DeprecatedTagSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { - return [ - 'CODE_TAG_CONTENT_FORMAT_INVALID' => ['CODE_TAG_CONTENT_FORMAT_INVALID', 'TagContentFormatInvalid'], - 'CODE_TAG_MISSING_DATES' => ['CODE_TAG_MISSING_DATES', 'MissingDates'], - ]; + return [T_DOC_COMMENT_TAG]; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { - return [T_DOC_COMMENT_TAG]; + return [ + 'CODE_TAG_CONTENT_FORMAT_INVALID' => ['CODE_TAG_CONTENT_FORMAT_INVALID', 'TagContentFormatInvalid'], + 'CODE_TAG_MISSING_DATES' => ['CODE_TAG_MISSING_DATES', 'MissingDates'], + ]; } /** diff --git a/tests/Sniffs/DocTags/DisallowLeadingAttributeSniffTest.php b/tests/Sniffs/DocTags/DisallowLeadingAttributeSniffTest.php index 57de984d..1cf3bfba 100644 --- a/tests/Sniffs/DocTags/DisallowLeadingAttributeSniffTest.php +++ b/tests/Sniffs/DocTags/DisallowLeadingAttributeSniffTest.php @@ -4,26 +4,29 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_OPEN_TAG; class DisallowLeadingAttributeSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; - public function getRequiredConstantAsserts(): iterable + protected function getExpectedTokens(): array { - return ['CODE_WRONG_ATTRIBUTE_POSITION' => ['CODE_WRONG_ATTRIBUTE_POSITION', 'WrongAttrPos']]; + return [T_DOC_COMMENT_OPEN_TAG]; } - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): iterable { - return [T_DOC_COMMENT_OPEN_TAG]; + return ['CODE_WRONG_ATTRIBUTE_POSITION' => ['CODE_WRONG_ATTRIBUTE_POSITION', 'WrongAttrPos']]; } protected function setUp(): void diff --git a/tests/Sniffs/DocTags/DisallowedClassTagsSniffTest.php b/tests/Sniffs/DocTags/DisallowedClassTagsSniffTest.php index 19bc846d..9a10f5e6 100644 --- a/tests/Sniffs/DocTags/DisallowedClassTagsSniffTest.php +++ b/tests/Sniffs/DocTags/DisallowedClassTagsSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; @@ -18,30 +19,31 @@ */ class DisallowedClassTagsSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { - return [ - 'CODE_TAG_NOT_ALLOWED' => ['CODE_TAG_NOT_ALLOWED', 'TagNotAllowed'], - ]; + return Tokens::$ooScopeTokens; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { - return Tokens::$ooScopeTokens; + return [ + 'CODE_TAG_NOT_ALLOWED' => ['CODE_TAG_NOT_ALLOWED', 'TagNotAllowed'], + ]; } /** diff --git a/tests/Sniffs/DocTags/ParamTagSniffTest.php b/tests/Sniffs/DocTags/ParamTagSniffTest.php index 796134d8..99ceba64 100644 --- a/tests/Sniffs/DocTags/ParamTagSniffTest.php +++ b/tests/Sniffs/DocTags/ParamTagSniffTest.php @@ -4,12 +4,15 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use function array_merge; -use function sprintf; + use const T_DOC_COMMENT_TAG; /** @@ -20,7 +23,9 @@ */ class ParamTagSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -39,7 +44,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_TAG_MISSING_DESC' => ['CODE_TAG_MISSING_DESC', 'MissingDesc'], @@ -67,24 +72,28 @@ protected function setUp(): void /** * Tests description warnings after config. * - * @dataProvider getCorrectFileListAsDataProvider - * - * @param string $file Fixture file - * * @return void */ - public function testDescriptionWarningsWithConfig(string $file): void + public function testDescriptionWarningsWithConfig(): void { - $unusedData = []; - $fileMetadata = $this->getMetadataFromFilenameAsAssertArray($file, $unusedData); + $files = $this->getCorrectFileListAsDataProvider(); - if (!$fileMetadata) { - static::markTestSkipped(sprintf('The file %s does not contain any metadata.', basename($file))); + if (!$files) { + static::markTestSkipped('No correct fixtures found.'); } - $callData = array_merge($fileMetadata, [['descAsWarning' => true]]); + foreach ($files as [$file]) { + $unusedData = []; + $fileMetadata = $this->getMetadataFromFilenameAsAssertArray($file, $unusedData); - $this->assertWarningsInFile(...$callData); + if (!$fileMetadata) { + continue; + } + + $callData = array_merge($fileMetadata, [['descAsWarning' => true]]); + + $this->assertWarningsInFile(...$callData); + } } /** diff --git a/tests/Sniffs/DocTags/RequiredClassTagsSniffTest.php b/tests/Sniffs/DocTags/RequiredClassTagsSniffTest.php index 32527880..3d6f8c65 100644 --- a/tests/Sniffs/DocTags/RequiredClassTagsSniffTest.php +++ b/tests/Sniffs/DocTags/RequiredClassTagsSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; @@ -18,7 +19,8 @@ */ class RequiredClassTagsSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +39,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_TAG_OCCURRENCE_MIN_PREFIX' => ['CODE_TAG_OCCURRENCE_MIN_PREFIX', 'TagOccurrenceMin'], diff --git a/tests/Sniffs/DocTags/TagSortingSniffTest.php b/tests/Sniffs/DocTags/TagSortingSniffTest.php index 583a2bda..6a962a9a 100644 --- a/tests/Sniffs/DocTags/TagSortingSniffTest.php +++ b/tests/Sniffs/DocTags/TagSortingSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\DocTags; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_OPEN_TAG; /** @@ -18,31 +20,32 @@ */ class TagSortingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { - return [ - 'CODE_MISSING_NEWLINE_BETWEEN_TAGS' => ['CODE_MISSING_NEWLINE_BETWEEN_TAGS', 'MissingNewlineBetweenTags'], - 'CODE_WRONG_TAG_SORTING' => ['CODE_WRONG_TAG_SORTING', 'WrongTagSorting'], - ]; + return [T_DOC_COMMENT_OPEN_TAG]; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { - return [T_DOC_COMMENT_OPEN_TAG]; + return [ + 'CODE_MISSING_NEWLINE_BETWEEN_TAGS' => ['CODE_MISSING_NEWLINE_BETWEEN_TAGS', 'MissingNewlineBetweenTags'], + 'CODE_WRONG_TAG_SORTING' => ['CODE_WRONG_TAG_SORTING', 'WrongTagSorting'], + ]; } /** diff --git a/tests/Sniffs/DocTags/ThrowsTagSniffTest.php b/tests/Sniffs/DocTags/ThrowsTagSniffTest.php index 5d602e3e..8d5bdc6f 100644 --- a/tests/Sniffs/DocTags/ThrowsTagSniffTest.php +++ b/tests/Sniffs/DocTags/ThrowsTagSniffTest.php @@ -17,7 +17,7 @@ class ThrowsTagSniffTest extends AuthorTagSniffTest * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return parent::getRequiredConstantAsserts() + [ 'CODE_TAG_MISSING_DESC_DESC' => ['CODE_TAG_MISSING_DESC_DESC', 'MissingThrowDescription'], diff --git a/tests/Sniffs/Formatting/AlphabeticClassContentSniffTest.php b/tests/Sniffs/Formatting/AlphabeticClassContentSniffTest.php index 67bf35df..23920cdc 100644 --- a/tests/Sniffs/Formatting/AlphabeticClassContentSniffTest.php +++ b/tests/Sniffs/Formatting/AlphabeticClassContentSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; @@ -18,7 +19,8 @@ */ class AlphabeticClassContentSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -33,26 +35,26 @@ protected function getExpectedTokens(): array } /** - * Sets up the test. + * Returns the names of the required constants. * - * @return void + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function setUp(): void + public static function getRequiredConstantAsserts(): array { - parent::setUp(); - - $this->testedObject = new AlphabeticClassContentSniff(); + return [ + 'CODE_SORT_ALPHABETICALLY' => ['CODE_SORT_ALPHABETICALLY', 'SortAlphabetically'], + ]; } /** - * Returns the names of the required constants. + * Sets up the test. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return void */ - public function getRequiredConstantAsserts(): array + protected function setUp(): void { - return [ - 'CODE_SORT_ALPHABETICALLY' => ['CODE_SORT_ALPHABETICALLY', 'SortAlphabetically'], - ]; + parent::setUp(); + + $this->testedObject = new AlphabeticClassContentSniff(); } } diff --git a/tests/Sniffs/Formatting/AlphabeticallySortedUsesSniffTest.php b/tests/Sniffs/Formatting/AlphabeticallySortedUsesSniffTest.php index fd9789cc..beea4433 100644 --- a/tests/Sniffs/Formatting/AlphabeticallySortedUsesSniffTest.php +++ b/tests/Sniffs/Formatting/AlphabeticallySortedUsesSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_OPEN_TAG; /** @@ -18,31 +20,32 @@ */ class AlphabeticallySortedUsesSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { return [ - 'CODE_INCORRECT_ORDER' => ['CODE_INCORRECT_ORDER', 'IncorrectlyOrderedUses'], + T_OPEN_TAG, ]; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { return [ - T_OPEN_TAG, + 'CODE_INCORRECT_ORDER' => ['CODE_INCORRECT_ORDER', 'IncorrectlyOrderedUses'], ]; } diff --git a/tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/correct/Correct.php b/tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/correct/Correct.php new file mode 100644 index 00000000..0d637c5d --- /dev/null +++ b/tests/Sniffs/Formatting/Fixtures/NoWhitespaceAfterClassOpeningSniff/correct/Correct.php @@ -0,0 +1,13 @@ + [ diff --git a/tests/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniffTest.php b/tests/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniffTest.php index 9dbe5f00..18f543cd 100644 --- a/tests/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniffTest.php +++ b/tests/Sniffs/Formatting/NoWhitespaceAfterClassOpeningSniffTest.php @@ -4,15 +4,18 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_ENUM; class NoWhitespaceAfterClassOpeningSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -27,7 +30,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_EMPTY_LINES_AFTER_OPENING_BRACE' => diff --git a/tests/Sniffs/Formatting/OpenTagSniffTest.php b/tests/Sniffs/Formatting/OpenTagSniffTest.php index d452e158..e7fa6c2e 100644 --- a/tests/Sniffs/Formatting/OpenTagSniffTest.php +++ b/tests/Sniffs/Formatting/OpenTagSniffTest.php @@ -15,6 +15,27 @@ */ class OpenTagSniffTest extends SniffTestCase { + /** + * Checks the given file with defined error codes. + * + * @param string $file Filename of the fixture + * @param array $sniffProperties Array of sniff properties + * + * @return File The php cs file + */ + protected function checkFileAgainstSniff(string $file, array $sniffProperties = []): File + { + return $this->checkFile( + $file, + $sniffProperties, + [ + OpenTagSniff::CODE_LINE_NOT_EMPTY, + OpenTagSniff::CODE_NO_SPACE_AFTER_OPEN_TAG, + OpenTagSniff::CODE_NOT_FIRST_STATEMENT, + ], + ); + } + /** * Test empty line after open tag with no errors. * @@ -86,25 +107,4 @@ public function testNotFirstStatement(): void $this->assertAllFixedInFile($report); } - - /** - * Checks the given file with defined error codes. - * - * @param string $file Filename of the fixture - * @param array $sniffProperties Array of sniff properties - * - * @return File The php cs file - */ - protected function checkFileAgainstSniff(string $file, array $sniffProperties = []): File - { - return $this->checkFile( - $file, - $sniffProperties, - [ - OpenTagSniff::CODE_LINE_NOT_EMPTY, - OpenTagSniff::CODE_NO_SPACE_AFTER_OPEN_TAG, - OpenTagSniff::CODE_NOT_FIRST_STATEMENT, - ], - ); - } } diff --git a/tests/Sniffs/Formatting/ReturnTypeHintSpacingSniffTest.php b/tests/Sniffs/Formatting/ReturnTypeHintSpacingSniffTest.php index e4bebbf9..caf8c318 100644 --- a/tests/Sniffs/Formatting/ReturnTypeHintSpacingSniffTest.php +++ b/tests/Sniffs/Formatting/ReturnTypeHintSpacingSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\SniffTestCase; use SlevomatCodingStandard\Sniffs\TypeHints\ReturnTypeHintSpacingSniff as BaseReturnTypeHintSpacingSniff; @@ -16,7 +17,8 @@ */ class ReturnTypeHintSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; /** * The tested class. diff --git a/tests/Sniffs/Formatting/TrailingArrayCommaSniffTest.php b/tests/Sniffs/Formatting/TrailingArrayCommaSniffTest.php index d79f9d77..1ea3a81c 100644 --- a/tests/Sniffs/Formatting/TrailingArrayCommaSniffTest.php +++ b/tests/Sniffs/Formatting/TrailingArrayCommaSniffTest.php @@ -4,16 +4,19 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_ARRAY; use const T_OPEN_SHORT_ARRAY; class TrailingArrayCommaSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -25,7 +28,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_TRAILING_COMMA' => ['CODE_MISSING_TRAILING_COMMA', 'MissingTrailingComma'], diff --git a/tests/Sniffs/Formatting/TrailingCommaInDeclarationSniffTest.php b/tests/Sniffs/Formatting/TrailingCommaInDeclarationSniffTest.php index 60aca51b..b0bafb48 100644 --- a/tests/Sniffs/Formatting/TrailingCommaInDeclarationSniffTest.php +++ b/tests/Sniffs/Formatting/TrailingCommaInDeclarationSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_CLOSURE; use const T_FN; use const T_FUNCTION; @@ -20,7 +22,8 @@ */ class TrailingCommaInDeclarationSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -43,7 +46,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_TRAILING_COMMA' => ['CODE_MISSING_TRAILING_COMMA', 'MissingTrailingComma'], diff --git a/tests/Sniffs/Formatting/TraitUseDeclarationSniffTest.php b/tests/Sniffs/Formatting/TraitUseDeclarationSniffTest.php index 3b27e165..ccd47091 100644 --- a/tests/Sniffs/Formatting/TraitUseDeclarationSniffTest.php +++ b/tests/Sniffs/Formatting/TraitUseDeclarationSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_ANON_CLASS; use const T_CLASS; use const T_ENUM; @@ -16,7 +18,8 @@ class TraitUseDeclarationSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -31,7 +34,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MULTIPLE_TRAITS_PER_DECLARATION' => diff --git a/tests/Sniffs/Formatting/UCVFSortingSniffTest.php b/tests/Sniffs/Formatting/UCVFSortingSniffTest.php index 04aec9f1..f1081e78 100644 --- a/tests/Sniffs/Formatting/UCVFSortingSniffTest.php +++ b/tests/Sniffs/Formatting/UCVFSortingSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\Formatting; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; @@ -18,7 +19,8 @@ */ class UCVFSortingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -37,7 +39,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_WRONG_POSITION' => ['CODE_WRONG_POSITION', 'WrongPosition'], diff --git a/tests/Sniffs/Functions/ForbiddenFunctionsSniffTest.php b/tests/Sniffs/Functions/ForbiddenFunctionsSniffTest.php index 3883a15c..5b621433 100644 --- a/tests/Sniffs/Functions/ForbiddenFunctionsSniffTest.php +++ b/tests/Sniffs/Functions/ForbiddenFunctionsSniffTest.php @@ -4,7 +4,8 @@ namespace BestIt\Sniffs\Functions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\SniffTestCase; /** @@ -15,7 +16,8 @@ */ class ForbiddenFunctionsSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; private ForbiddenFunctionsSniff $testedClass; diff --git a/tests/Sniffs/Functions/MultipleReturnSniffTest.php b/tests/Sniffs/Functions/MultipleReturnSniffTest.php index 95bc5587..a5a5714c 100644 --- a/tests/Sniffs/Functions/MultipleReturnSniffTest.php +++ b/tests/Sniffs/Functions/MultipleReturnSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Functions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_FUNCTION; /** @@ -18,7 +20,8 @@ */ class MultipleReturnSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MULTIPLE_RETURNS_FOUND' => ['CODE_MULTIPLE_RETURNS_FOUND', 'MultipleReturnsFound'], diff --git a/tests/Sniffs/Functions/NoNamedArgumentsSniffTest.php b/tests/Sniffs/Functions/NoNamedArgumentsSniffTest.php index d2a7d750..42dc8ed6 100644 --- a/tests/Sniffs/Functions/NoNamedArgumentsSniffTest.php +++ b/tests/Sniffs/Functions/NoNamedArgumentsSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Functions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_PARAM_NAME; /** @@ -18,7 +20,8 @@ */ class NoNamedArgumentsSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_DISALLOWED_NAMED_ARGUMENT' => ['CODE_DISALLOWED_NAMED_ARGUMENT', 'DisallowedNamedArgument'], diff --git a/tests/Sniffs/Functions/NoSimplePropertyMethodSniffTest.php b/tests/Sniffs/Functions/NoSimplePropertyMethodSniffTest.php index f057b36f..e68a8ebc 100644 --- a/tests/Sniffs/Functions/NoSimplePropertyMethodSniffTest.php +++ b/tests/Sniffs/Functions/NoSimplePropertyMethodSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Functions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_PRIVATE; use const T_PROTECTED; use const T_PUBLIC; @@ -21,7 +23,8 @@ */ class NoSimplePropertyMethodSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -45,7 +48,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_SHOULD_USE_PROPERTY' => [ diff --git a/tests/Sniffs/Functions/TrailingCommaInCallSniffTest.php b/tests/Sniffs/Functions/TrailingCommaInCallSniffTest.php index a6ef5005..c17240f5 100644 --- a/tests/Sniffs/Functions/TrailingCommaInCallSniffTest.php +++ b/tests/Sniffs/Functions/TrailingCommaInCallSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Functions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_FUNCTION; use const T_OPEN_PARENTHESIS; @@ -19,20 +21,21 @@ */ class TrailingCommaInCallSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Sets up the test. + * Checks the registered tokens. * - * @return void + * @return array */ - protected function setUp(): void + protected function getExpectedTokens(): array { - parent::setUp(); - - $this->testedObject = new TrailingCommaInCallSniff(); + return [ + T_OPEN_PARENTHESIS, + ]; } /** @@ -40,7 +43,7 @@ protected function setUp(): void * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_TRAILING_COMMA' => ['CODE_MISSING_TRAILING_COMMA', 'MissingTrailingComma'], @@ -48,14 +51,14 @@ public function getRequiredConstantAsserts(): array } /** - * Checks the registered tokens. + * Sets up the test. * - * @return array + * @return void */ - protected function getExpectedTokens(): array + protected function setUp(): void { - return [ - T_OPEN_PARENTHESIS, - ]; + parent::setUp(); + + $this->testedObject = new TrailingCommaInCallSniff(); } } diff --git a/tests/Sniffs/NamingConventions/CamelCaseVariableSniffTest.php b/tests/Sniffs/NamingConventions/CamelCaseVariableSniffTest.php index 52b0a86e..58f6b6ec 100644 --- a/tests/Sniffs/NamingConventions/CamelCaseVariableSniffTest.php +++ b/tests/Sniffs/NamingConventions/CamelCaseVariableSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\NamingConventions; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_VARIABLE; /** @@ -18,30 +20,31 @@ */ class CamelCaseVariableSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; /** - * Returns the names of the required constants. + * Returns the tokens which should be checked. * - * @return array The required constants of a class. The second value is a possible value which should be checked. + * @return array Returns the expected token ids. */ - public function getRequiredConstantAsserts(): array + protected function getExpectedTokens(): array { - return [ - 'CODE_NOT_CAMEL_CASE' => ['CODE_NOT_CAMEL_CASE', 'NotCamelCase'], - ]; + return [T_VARIABLE]; } /** - * Returns the tokens which should be checked. + * Returns the names of the required constants. * - * @return array Returns the expected token ids. + * @return array The required constants of a class. The second value is a possible value which should be checked. */ - protected function getExpectedTokens(): array + public static function getRequiredConstantAsserts(): array { - return [T_VARIABLE]; + return [ + 'CODE_NOT_CAMEL_CASE' => ['CODE_NOT_CAMEL_CASE', 'NotCamelCase'], + ]; } /** diff --git a/tests/Sniffs/SniffCorrectFilesTrait.php b/tests/Sniffs/SniffCorrectFilesTrait.php new file mode 100644 index 00000000..65744da4 --- /dev/null +++ b/tests/Sniffs/SniffCorrectFilesTrait.php @@ -0,0 +1,48 @@ + + * @package BestIt\Sniffs + */ +trait SniffCorrectFilesTrait +{ + /** + * Tests files which have to be without errors. + * + * @param string $file File to test + * + * @return void + */ + abstract protected function assertFileCorrect(string $file): void; + + /** + * Returns a list of correct fixture files as a data provider. + * + * @return array With the path to a file as the first parameter. + */ + abstract public function getCorrectFileListAsDataProvider(): array; + + /** + * Tests that correct files produce no errors or warnings. + * + * @return void + */ + public function testCorrect(): void + { + $files = $this->getCorrectFileListAsDataProvider(); + + if (!$files) { + $this->markTestSkipped('No correct fixtures found.'); + } + + foreach ($files as [$file]) { + $this->assertFileCorrect($file); + } + } +} diff --git a/tests/Sniffs/SniffErrorFilesTrait.php b/tests/Sniffs/SniffErrorFilesTrait.php new file mode 100644 index 00000000..ac20799d --- /dev/null +++ b/tests/Sniffs/SniffErrorFilesTrait.php @@ -0,0 +1,76 @@ + + * @package BestIt\Sniffs + */ +trait SniffErrorFilesTrait +{ + /** + * Asserts all errors in a given file. + * + * @param string $file Filename of the fixture + * @param string $error Error code + * @param int[] $lines Array of lines where the error code occurs + * @param array $sniffProperties Array of sniff properties + * + * @return File The php cs file + */ + abstract protected function assertErrorsInFile( + string $file, + string $error, + array $lines, + array $sniffProperties = [], + ): File; + + /** + * Returns data for errors. + * + * @return array List of error data (Filepath, error code, error lines, fixable) + */ + public function getErrorAsserts(): array + { + return $this->loadAssertData(); + } + + /** + * Loads the assertion data out of the file names. + * + * @param bool $forErrors Load data for errors? + * + * @return array The assert data as data providers. + */ + abstract protected function loadAssertData(bool $forErrors = true): array; + + /** + * Tests errors. + * + * @return void + */ + public function testErrors(): void + { + $asserts = $this->getErrorAsserts(); + + if (!$asserts) { + $this->markTestSkipped('No error fixtures found.'); + } + + foreach ($asserts as $assert) { + [$file, $error, $lines] = $assert; + $withFixable = $assert[3] ?? false; + $report = $this->assertErrorsInFile($file, $error, $lines); + + if ($withFixable) { + $this->assertAllFixedInFile($report); + } + } + } +} diff --git a/tests/Sniffs/SniffWarningFilesTrait.php b/tests/Sniffs/SniffWarningFilesTrait.php new file mode 100644 index 00000000..201cc1a6 --- /dev/null +++ b/tests/Sniffs/SniffWarningFilesTrait.php @@ -0,0 +1,76 @@ + + * @package BestIt\Sniffs + */ +trait SniffWarningFilesTrait +{ + /** + * Asserts all warnings in a given file. + * + * @param string $file Filename of the fixture + * @param string $error Error code + * @param int[] $lines Array of lines where the error code occurs + * @param array $sniffProperties Array of sniff properties + * + * @return File The php cs file + */ + abstract protected function assertWarningsInFile( + string $file, + string $error, + array $lines, + array $sniffProperties = [], + ): File; + + /** + * Returns data for warnings. + * + * @return array List of warning data (Filepath, warning code, warning lines, fixable) + */ + public function getWarningAsserts(): array + { + return $this->loadAssertData(false); + } + + /** + * Loads the assertion data out of the file names. + * + * @param bool $forErrors Load data for errors? + * + * @return array The assert data as data providers. + */ + abstract protected function loadAssertData(bool $forErrors = true): array; + + /** + * Tests warnings. + * + * @return void + */ + public function testWarnings(): void + { + $asserts = $this->getWarningAsserts(); + + if (!$asserts) { + $this->markTestSkipped('No warning fixtures found.'); + } + + foreach ($asserts as $assert) { + [$file, $warning, $lines] = $assert; + $withFixable = $assert[3] ?? false; + $report = $this->assertWarningsInFile($file, $warning, $lines); + + if ($withFixable) { + $this->assertAllFixedInFile($report); + } + } + } +} diff --git a/tests/Sniffs/Spacing/ClassMemberSpacingSniffTest.php b/tests/Sniffs/Spacing/ClassMemberSpacingSniffTest.php index df1d0c80..87d3c444 100644 --- a/tests/Sniffs/Spacing/ClassMemberSpacingSniffTest.php +++ b/tests/Sniffs/Spacing/ClassMemberSpacingSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_ANON_CLASS; use const T_CLASS; use const T_ENUM; @@ -16,7 +18,8 @@ class ClassMemberSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -31,7 +34,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_COUNT_OF_BLANK_LINES_BETWEEN_MEMBERS' => [ diff --git a/tests/Sniffs/Spacing/ConstantSpacingSniffTest.php b/tests/Sniffs/Spacing/ConstantSpacingSniffTest.php index 9677f75a..7f6413a9 100644 --- a/tests/Sniffs/Spacing/ConstantSpacingSniffTest.php +++ b/tests/Sniffs/Spacing/ConstantSpacingSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_CONST; /** @@ -18,7 +20,8 @@ */ class ConstantSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -39,7 +42,7 @@ protected function getExpectedTokens(): array * * @return iterable */ - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_COUNT_OF_BLANK_LINES_AFTER_CONSTANT' => [ diff --git a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/correct/Correct.php b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/correct/Correct.php index 4bbecf3c..73d9465b 100644 --- a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/correct/Correct.php +++ b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/correct/Correct.php @@ -2,7 +2,10 @@ declare(strict_types=1); -namespace BestIt\Sniffs\Formatting\Fixtures\UseSpacingSniff\correct; +namespace BestIt\Sniffs\Formatting\Fixtures\UseSpacingSniff\with_errors; + +use SplObjectStorage; +use stdClass; use function uniqid; use function var_dump; @@ -11,6 +14,9 @@ class Correct { public function __construct() { - var_dump(uniqid()); + $storage = new SplObjectStorage(); + $storage->attach(new stdClass(), uniqid()); + + var_dump($storage); } } \ No newline at end of file diff --git a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.fixed.php b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.fixed.php deleted file mode 100644 index 2ba1ad18..00000000 --- a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.fixed.php +++ /dev/null @@ -1,21 +0,0 @@ -attach(new stdClass(), uniqid()); - - var_dump($storage); - } -} \ No newline at end of file diff --git a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.php b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.php deleted file mode 100644 index da67f8a5..00000000 --- a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(1).10.php +++ /dev/null @@ -1,22 +0,0 @@ -attach(new stdClass(), uniqid()); - - var_dump($storage); - } -} \ No newline at end of file diff --git a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(3).12.fixed.php b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(3).12.fixed.php index 2ba1ad18..da67f8a5 100644 --- a/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(3).12.fixed.php +++ b/tests/Sniffs/Spacing/Fixtures/UseSpacingSniff/with_errors/IncorrectLinesCountBetweenDifferentTypeOfUse(3).12.fixed.php @@ -6,6 +6,7 @@ use SplObjectStorage; use stdClass; + use function uniqid; use function var_dump; diff --git a/tests/Sniffs/Spacing/NamespaceSpacingSniffTest.php b/tests/Sniffs/Spacing/NamespaceSpacingSniffTest.php index 7657a8c8..2294db45 100644 --- a/tests/Sniffs/Spacing/NamespaceSpacingSniffTest.php +++ b/tests/Sniffs/Spacing/NamespaceSpacingSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_NAMESPACE; /** @@ -18,7 +20,8 @@ */ class NamespaceSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -39,7 +42,7 @@ protected function getExpectedTokens(): array * * @return iterable */ - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_LINES_COUNT_BEFORE_NAMESPACE' => [ diff --git a/tests/Sniffs/Spacing/PropertySpacingSniffTest.php b/tests/Sniffs/Spacing/PropertySpacingSniffTest.php index 6e76b2dd..3af1b9b9 100644 --- a/tests/Sniffs/Spacing/PropertySpacingSniffTest.php +++ b/tests/Sniffs/Spacing/PropertySpacingSniffTest.php @@ -4,36 +4,49 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + +use const T_ABSTRACT; +use const T_FINAL; use const T_PRIVATE; +use const T_PRIVATE_SET; use const T_PROTECTED; +use const T_PROTECTED_SET; use const T_PUBLIC; +use const T_PUBLIC_SET; use const T_READONLY; use const T_STATIC; use const T_VAR; class PropertySpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; protected function getExpectedTokens(): array { return [ + T_FINAL, + T_ABSTRACT, T_VAR, T_PUBLIC, + T_PUBLIC_SET, T_PROTECTED, + T_PROTECTED_SET, T_PRIVATE, + T_PRIVATE_SET, T_READONLY, T_STATIC, ]; } - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_COUNT_OF_BLANK_LINES_AFTER_PROPERTY' => [ diff --git a/tests/Sniffs/Spacing/SpaceAfterDeclareSniffTest.php b/tests/Sniffs/Spacing/SpaceAfterDeclareSniffTest.php index 744815d8..5751baa6 100644 --- a/tests/Sniffs/Spacing/SpaceAfterDeclareSniffTest.php +++ b/tests/Sniffs/Spacing/SpaceAfterDeclareSniffTest.php @@ -16,14 +16,23 @@ class SpaceAfterDeclareSniffTest extends SniffTestCase { /** - * Test space after declare with no errors. + * Checks the given file with defined error codes. * - * @return void + * @param string $file Filename of the fixture + * @param array $sniffProperties Array of sniff properties + * + * @return File The php cs file */ - public function testSpaceAfterDeclareCorrect(): void + protected function checkFileAgainstSniff(string $file, array $sniffProperties = []): File { - $this->assertNoSniffErrorInFile( - $this->checkFile($this->getFixtureFilePath('Correct.php')), + return $this->checkFile( + $file, + $sniffProperties, + [ + SpaceAfterDeclareSniff::CODE_NO_WHITESPACE_FOUND, + SpaceAfterDeclareSniff::CODE_MUCH_WHITESPACE_FOUND, + SpaceAfterDeclareSniff::CODE_GROUP_BLANK_LINE_FOUND, + ], ); } @@ -39,24 +48,6 @@ public function testEarlyReturn(): void ); } - /** - * Test no whitespace found error and fix. - * - * @return void - */ - public function testNoWhitespaceFound(): void - { - $report = $this->checkFile($this->getFixtureFilePath('NoWhitespaceFound.php')); - - $this->assertSniffError( - $report, - 3, - SpaceAfterDeclareSniff::CODE_NO_WHITESPACE_FOUND, - ); - - $this->assertAllFixedInFile($report); - } - /** * Test much whitespaces found error and fix. * @@ -102,23 +93,32 @@ public function testMultipleDeclareStatements(): void } /** - * Checks the given file with defined error codes. + * Test no whitespace found error and fix. * - * @param string $file Filename of the fixture - * @param array $sniffProperties Array of sniff properties + * @return void + */ + public function testNoWhitespaceFound(): void + { + $report = $this->checkFile($this->getFixtureFilePath('NoWhitespaceFound.php')); + + $this->assertSniffError( + $report, + 3, + SpaceAfterDeclareSniff::CODE_NO_WHITESPACE_FOUND, + ); + + $this->assertAllFixedInFile($report); + } + + /** + * Test space after declare with no errors. * - * @return File The php cs file + * @return void */ - protected function checkFileAgainstSniff(string $file, array $sniffProperties = []): File + public function testSpaceAfterDeclareCorrect(): void { - return $this->checkFile( - $file, - $sniffProperties, - [ - SpaceAfterDeclareSniff::CODE_NO_WHITESPACE_FOUND, - SpaceAfterDeclareSniff::CODE_MUCH_WHITESPACE_FOUND, - SpaceAfterDeclareSniff::CODE_GROUP_BLANK_LINE_FOUND, - ], + $this->assertNoSniffErrorInFile( + $this->checkFile($this->getFixtureFilePath('Correct.php')), ); } } diff --git a/tests/Sniffs/Spacing/SpaceAroundConcatSniffTest.php b/tests/Sniffs/Spacing/SpaceAroundConcatSniffTest.php index ffbbb817..29a48214 100644 --- a/tests/Sniffs/Spacing/SpaceAroundConcatSniffTest.php +++ b/tests/Sniffs/Spacing/SpaceAroundConcatSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_STRING_CONCAT; /** @@ -18,7 +20,8 @@ */ class SpaceAroundConcatSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_SPACE_AROUND_CONCAT' => ['CODE_MISSING_SPACE_AROUND_CONCAT', 'MissingSpaceAroundConcat'], diff --git a/tests/Sniffs/Spacing/TraitUseSpacingSniffTest.php b/tests/Sniffs/Spacing/TraitUseSpacingSniffTest.php index 47e152f3..3773ee24 100644 --- a/tests/Sniffs/Spacing/TraitUseSpacingSniffTest.php +++ b/tests/Sniffs/Spacing/TraitUseSpacingSniffTest.php @@ -4,11 +4,13 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; use Test_Enum; + use const T_ANON_CLASS; use const T_CLASS; use const T_ENUM; @@ -17,7 +19,8 @@ class TraitUseSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -32,7 +35,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE' => [ diff --git a/tests/Sniffs/Spacing/UseSpacingSniffTest.php b/tests/Sniffs/Spacing/UseSpacingSniffTest.php index eaced1d0..fa9fd0ea 100644 --- a/tests/Sniffs/Spacing/UseSpacingSniffTest.php +++ b/tests/Sniffs/Spacing/UseSpacingSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Spacing; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_OPEN_TAG; /** @@ -18,7 +20,8 @@ */ class UseSpacingSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestTokenRegistrationTrait; use TestRequiredConstantsTrait; @@ -39,7 +42,7 @@ protected function getExpectedTokens(): array * * @return iterable */ - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE' => [ diff --git a/tests/Sniffs/Strings/ConcatCalculationSniffTest.php b/tests/Sniffs/Strings/ConcatCalculationSniffTest.php index ba6ec4ff..1ffb8db5 100644 --- a/tests/Sniffs/Strings/ConcatCalculationSniffTest.php +++ b/tests/Sniffs/Strings/ConcatCalculationSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\Strings; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_STRING_CONCAT; /** @@ -18,7 +20,8 @@ */ class ConcatCalculationSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -37,7 +40,7 @@ protected function getExpectedTokens(): array * * @return iterable */ - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return [ 'CODE_CALCULATION_WITHOUT_BRACKETS' => [ diff --git a/tests/Sniffs/TypeHints/ExplicitAssertionsSniffTest.php b/tests/Sniffs/TypeHints/ExplicitAssertionsSniffTest.php index 99b4d616..6a6edb35 100644 --- a/tests/Sniffs/TypeHints/ExplicitAssertionsSniffTest.php +++ b/tests/Sniffs/TypeHints/ExplicitAssertionsSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\TypeHints; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_DOC_COMMENT_OPEN_TAG; /** @@ -18,7 +20,8 @@ */ class ExplicitAssertionsSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -39,7 +42,7 @@ protected function getExpectedTokens(): array * * @return array */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_REQUIRED_EXPLICIT_ASSERTION' => ['CODE_REQUIRED_EXPLICIT_ASSERTION', 'RequiredExplicitAssertion'], diff --git a/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.fixed.php b/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.fixed.php similarity index 82% rename from tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.fixed.php rename to tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.fixed.php index 5122281d..de413a62 100644 --- a/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.fixed.php +++ b/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.fixed.php @@ -79,7 +79,7 @@ public function testNullMethod(): ?string /** * @return array|null */ - public function testMultipleTypesMethod(): ?array + public function testMultipleArrayTypesMethod(): ?array { if (true) { return []; @@ -87,4 +87,16 @@ public function testMultipleTypesMethod(): ?array return null; } + + /** + * @return array|string|null + */ + public function testMultipleTypesMethod(): array|string|null + { + if (true) { + return []; + } + + return 'string' || null; + } } diff --git a/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.php b/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.php similarity index 86% rename from tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.php rename to tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.php index 09814f60..4960aac7 100644 --- a/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82.php +++ b/tests/Sniffs/TypeHints/Fixtures/ReturnTypeDeclarationSniff/with_errors/MissingReturnTypeHint.18,26,34,42,50,58,66,74,82,94.php @@ -79,7 +79,7 @@ public function testNullMethod() /** * @return array|null */ - public function testMultipleTypesMethod() + public function testMultipleArrayTypesMethod() { if (true) { return []; @@ -87,4 +87,16 @@ public function testMultipleTypesMethod() return null; } + + /** + * @return array|string|null + */ + public function testMultipleTypesMethod() + { + if (true) { + return []; + } + + return 'string' || null; + } } diff --git a/tests/Sniffs/TypeHints/PropertyTypeHintSniffTest.php b/tests/Sniffs/TypeHints/PropertyTypeHintSniffTest.php index 1ba6f76a..154fa6b6 100644 --- a/tests/Sniffs/TypeHints/PropertyTypeHintSniffTest.php +++ b/tests/Sniffs/TypeHints/PropertyTypeHintSniffTest.php @@ -4,10 +4,13 @@ namespace BestIt\Sniffs\TypeHints; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + +use const T_FINAL; use const T_PRIVATE; use const T_PROTECTED; use const T_PUBLIC; @@ -17,7 +20,8 @@ class PropertyTypeHintSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -29,10 +33,11 @@ protected function getExpectedTokens(): array T_PROTECTED, T_PRIVATE, T_STATIC, + T_FINAL, ]; } - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_ANY_TYPE_HINT' => ['CODE_MISSING_ANY_TYPE_HINT', 'MissingAnyTypeHint'], diff --git a/tests/Sniffs/TypeHints/ReturnTypeDeclarationSniffTest.php b/tests/Sniffs/TypeHints/ReturnTypeDeclarationSniffTest.php index 58762fcf..147583d6 100644 --- a/tests/Sniffs/TypeHints/ReturnTypeDeclarationSniffTest.php +++ b/tests/Sniffs/TypeHints/ReturnTypeDeclarationSniffTest.php @@ -4,10 +4,12 @@ namespace BestIt\Sniffs\TypeHints; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffErrorFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_FUNCTION; /** @@ -18,7 +20,7 @@ */ class ReturnTypeDeclarationSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffErrorFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -41,7 +43,7 @@ protected function getExpectedTokens(): array * * @return array The required constants of a class. The second value is a possible value which should be checked. */ - public function getRequiredConstantAsserts(): array + public static function getRequiredConstantAsserts(): array { return [ 'CODE_MISSING_RETURN_TYPE' => ['CODE_MISSING_RETURN_TYPE', 'MissingReturnTypeHint'], diff --git a/tests/Sniffs/TypeHints/SuggestExplicitReturnTypeSniffTest.php b/tests/Sniffs/TypeHints/SuggestExplicitReturnTypeSniffTest.php index 4670b017..5378594b 100644 --- a/tests/Sniffs/TypeHints/SuggestExplicitReturnTypeSniffTest.php +++ b/tests/Sniffs/TypeHints/SuggestExplicitReturnTypeSniffTest.php @@ -4,17 +4,20 @@ namespace BestIt\Sniffs\TypeHints; -use BestIt\Sniffs\DefaultSniffIntegrationTestTrait; +use BestIt\Sniffs\SniffCorrectFilesTrait; +use BestIt\Sniffs\SniffWarningFilesTrait; use BestIt\Sniffs\TestTokenRegistrationTrait; use BestIt\SniffTestCase; use BestIt\TestRequiredConstantsTrait; + use const T_CLOSURE; use const T_FN; use const T_FUNCTION; class SuggestExplicitReturnTypeSniffTest extends SniffTestCase { - use DefaultSniffIntegrationTestTrait; + use SniffCorrectFilesTrait; + use SniffWarningFilesTrait; use TestRequiredConstantsTrait; use TestTokenRegistrationTrait; @@ -27,7 +30,7 @@ protected function getExpectedTokens(): array ]; } - public function getRequiredConstantAsserts(): iterable + public static function getRequiredConstantAsserts(): iterable { return ['CODE_MIXED_TYPE' => ['CODE_MIXED_TYPE', 'MixedType']]; } diff --git a/tests/TestRequiredConstantsTrait.php b/tests/TestRequiredConstantsTrait.php index ec631df5..e98a808d 100644 --- a/tests/TestRequiredConstantsTrait.php +++ b/tests/TestRequiredConstantsTrait.php @@ -5,6 +5,8 @@ namespace BestIt; use PHP_CodeSniffer\Sniffs\Sniff; +use PHPUnit\Framework\Attributes\DataProvider; + use function constant; /** @@ -45,18 +47,17 @@ abstract public static function assertSame($expected, $actual, string $message = * * @return iterable The required constants of a class. The second value is a possible value which should be checked. */ - abstract public function getRequiredConstantAsserts(): iterable; + abstract public static function getRequiredConstantAsserts(): iterable; /** * Checks if the api is extended. * - * @dataProvider getRequiredConstantAsserts - * * @param string $constant The name of the constant. * @param string $constantValue We check the value as well, because some constants are fixed in ruleset.xmls. * * @return void */ + #[DataProvider('getRequiredConstantAsserts')] public function testRequiredConstants(string $constant, ?string $constantValue = null): void { $fullConstantName = get_class($this->testedObject) . '::' . $constant;