diff --git a/Inpsyde/Sniffs/CodeQuality/EncodingCommentSniff.php b/Inpsyde/Sniffs/CodeQuality/EncodingCommentSniff.php new file mode 100644 index 0000000..e8f306a --- /dev/null +++ b/Inpsyde/Sniffs/CodeQuality/EncodingCommentSniff.php @@ -0,0 +1,87 @@ + + */ + public function register(): array + { + return [T_COMMENT]; + } + + /** + * @param File $phpcsFile + * @param int $stackPtr + * @return void + * + * phpcs:disable Inpsyde.CodeQuality.ArgumentTypeDeclaration + */ + public function process(File $phpcsFile, $stackPtr): void + { + // phpcs:enable Inpsyde.CodeQuality.ArgumentTypeDeclaration + + $tokens = $phpcsFile->getTokens(); + + $comment = isset($tokens[$stackPtr]['content']) && is_string($tokens[$stackPtr]['content']) + ? $tokens[$stackPtr]['content'] + : ''; + + if (strpos($comment, self::DISALLOWED_COMMENT) === false) { + return; + } + + $fix = $phpcsFile->addFixableWarning( + 'Found outdated encoding declaration in comment.', + $stackPtr, + 'EncodingComment' + ); + + if ($fix) { + $this->fix($phpcsFile, $stackPtr); + } + } + + private function fix(File $phpcsFile, int $position): void + { + $phpcsFile->fixer->beginChangeset(); + + $phpcsFile->fixer->replaceToken($position, ''); + + $phpcsFile->fixer->endChangeset(); + } +} diff --git a/inpsyde-custom-sniffs.md b/inpsyde-custom-sniffs.md index fa80934..918b8ee 100644 --- a/inpsyde-custom-sniffs.md +++ b/inpsyde-custom-sniffs.md @@ -6,6 +6,7 @@ - Inpsyde.CodeQuality.ConstantVisibility - Inpsyde.CodeQuality.DisallowShortOpenTag - Inpsyde.CodeQuality.ElementNameMinimalLength +- Inpsyde.CodeQuality.EncodingComment - Inpsyde.CodeQuality.ForbiddenPublicProperty - Inpsyde.CodeQuality.FunctionBodyStart - Inpsyde.CodeQuality.FunctionLength @@ -95,6 +96,15 @@ alternatively, whitelist can be extended via `additionalAllowedNames` config, e. ``` +----- +## Inpsyde.CodeQuality.EncodingComment + +Prevent usage of some outdated encoding definition in PHP comments. + +It raises a Warning if something like this is found `-*- coding: utf-8 -*-`. + +This sniff has no available configuration. + ----- ## Inpsyde.CodeQuality.ForbiddenPublicProperty diff --git a/tests/fixtures/encoding-comment.php b/tests/fixtures/encoding-comment.php new file mode 100644 index 0000000..98b9ce3 --- /dev/null +++ b/tests/fixtures/encoding-comment.php @@ -0,0 +1,18 @@ + + + + + \ No newline at end of file