clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,137 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function rtrim;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_WHITESPACE;
/**
* @internal
*/
abstract class AbstractRequireOneLineDocComment implements Sniff
{
abstract protected function addError(File $phpcsFile, int $docCommentStartPointer): bool;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [T_DOC_COMMENT_OPEN_TAG];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentStartPointer
*/
public function process(File $phpcsFile, $docCommentStartPointer): void
{
$tokens = $phpcsFile->getTokens();
// Only validate properties without description
if (DocCommentHelper::hasDocCommentDescription($phpcsFile, $docCommentStartPointer)) {
return;
}
$docCommentEndPointer = $tokens[$docCommentStartPointer]['comment_closer'];
$lineDifference = $tokens[$docCommentEndPointer]['line'] - $tokens[$docCommentStartPointer]['line'];
// Already one-line
if ($lineDifference === 0) {
return;
}
// Ignore empty lines
$currentLinePointer = $docCommentStartPointer;
do {
$currentLinePointer = TokenHelper::findFirstTokenOnNextLine($phpcsFile, $currentLinePointer);
if ($currentLinePointer === null || $currentLinePointer >= $docCommentEndPointer) {
break;
}
$types = [T_DOC_COMMENT_STAR, T_DOC_COMMENT_CLOSE_TAG];
$startingPointer = TokenHelper::findNext($phpcsFile, $types, $currentLinePointer, $docCommentEndPointer);
if ($startingPointer === null || $tokens[$startingPointer]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
break;
}
$nextEffectivePointer = TokenHelper::findNextExcluding(
$phpcsFile,
[T_DOC_COMMENT_WHITESPACE],
$startingPointer + 1,
$docCommentEndPointer + 1
);
if ($tokens[$currentLinePointer]['line'] === $tokens[$nextEffectivePointer]['line']) {
continue;
}
$lineDifference--;
} while (true);
// Looks like a compound doc-comment
if ($lineDifference > 2) {
return;
}
$fix = $this->addError($phpcsFile, $docCommentStartPointer);
if (!$fix) {
return;
}
$contentStartPointer = TokenHelper::findNextExcluding(
$phpcsFile,
[
T_DOC_COMMENT_WHITESPACE,
T_DOC_COMMENT_STAR,
],
$docCommentStartPointer + 1,
$docCommentEndPointer
);
$contentEndPointer = TokenHelper::findPreviousExcluding(
$phpcsFile,
[
T_DOC_COMMENT_WHITESPACE,
T_DOC_COMMENT_STAR,
],
$docCommentEndPointer - 1,
$docCommentStartPointer
);
if ($contentStartPointer === null) {
FixerHelper::removeBetween($phpcsFile, $docCommentStartPointer, $docCommentEndPointer);
return;
}
$phpcsFile->fixer->beginChangeset();
for ($i = $docCommentStartPointer + 1; $i < $docCommentEndPointer; $i++) {
if ($i >= $contentStartPointer && $i <= $contentEndPointer) {
if ($i === $contentEndPointer) {
$phpcsFile->fixer->replaceToken($i, rtrim($phpcsFile->fixer->getTokenContent($i), ' '));
}
continue;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->addContentBefore($contentStartPointer, ' ');
$phpcsFile->fixer->addContentBefore($docCommentEndPointer, ' ');
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,299 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_combine;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_unique;
use function implode;
use function ltrim;
use function preg_match_all;
use function sprintf;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
use const PREG_OFFSET_CAPTURE;
use const T_DOC_COMMENT_OPEN_TAG;
class AnnotationNameSniff implements Sniff
{
public const CODE_ANNOTATION_NAME_INCORRECT = 'AnnotationNameIncorrect';
private const STANDARD_ANNOTATIONS = [
'api',
'author',
'category',
'copyright',
'deprecated',
'example',
'filesource',
'global',
'ignore',
'inheritDoc',
'internal',
'license',
'link',
'method',
'package',
'param',
'property',
'property-read',
'property-write',
'return',
'see',
'since',
'source',
'subpackage',
'throws',
'todo',
'uses',
'used-by',
'var',
'version',
];
private const STATIC_ANALYSIS_ANNOTATIONS = [
'api',
'allow-private-mutation',
'assert',
'assert-if-true',
'assert-if-false',
'consistent-constructor',
'consistent-templates',
'extends',
'external-mutation-free',
'implements',
'mixin',
'ignore-falsable-return',
'ignore-nullable-return',
'ignore-var',
'ignore-variable-method',
'ignore-variable-property',
'immutable',
'import-type',
'internal',
'method',
'mutation-free',
'no-named-arguments',
'param',
'param-out',
'property',
'property-read',
'property-write',
'psalm-check-type',
'psalm-check-type-exact',
'psalm-suppress',
'psalm-trace',
'pure',
'readonly',
'readonly-allow-private-mutation',
'require-extends',
'require-implements',
'return',
'seal-properties',
'self-out',
'template',
'template-covariant',
'template-extends',
'template-implements',
'template-use',
'this-out',
'type',
'var',
'yield',
];
private const PHPUNIT_ANNOTATIONS = [
'author',
'after',
'afterClass',
'backupGlobals',
'backupStaticAttributes',
'before',
'beforeClass',
'codeCoverageIgnore',
'codeCoverageIgnoreStart',
'codeCoverageIgnoreEnd',
'covers',
'coversDefaultClass',
'coversNothing',
'dataProvider',
'depends',
'doesNotPerformAssertions',
'group',
'large',
'medium',
'preserveGlobalState',
'requires',
'runTestsInSeparateProcesses',
'runInSeparateProcess',
'small',
'test',
'testdox',
'testWith',
'ticket',
'uses',
];
/** @var list<string>|null */
public $annotations;
/** @var array<string, string>|null */
private $normalizedAnnotations;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentOpenPointer
*/
public function process(File $phpcsFile, $docCommentOpenPointer): void
{
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer);
$correctAnnotationNames = $this->getNormalizedAnnotationNames();
foreach ($annotations as $annotation) {
$lowerCasedAnnotationName = strtolower($annotation->getName());
if (!array_key_exists($lowerCasedAnnotationName, $correctAnnotationNames)) {
continue;
}
$correctAnnotationName = $correctAnnotationNames[$lowerCasedAnnotationName];
if ($correctAnnotationName === $annotation->getName()) {
continue;
}
$annotationNameWithoutAtSign = ltrim($annotation->getName(), '@');
$fullyQualifiedAnnotationName = NamespaceHelper::resolveClassName(
$phpcsFile,
$annotationNameWithoutAtSign,
$annotation->getStartPointer()
);
if (NamespaceHelper::normalizeToCanonicalName($fullyQualifiedAnnotationName) !== $annotationNameWithoutAtSign) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf('Annotation name is incorrect. Expected %s, found %s.', $correctAnnotationName, $annotation->getName()),
$annotation->getStartPointer(),
self::CODE_ANNOTATION_NAME_INCORRECT
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($annotation->getStartPointer(), $correctAnnotationName);
$phpcsFile->fixer->endChangeset();
}
$tokens = $phpcsFile->getTokens();
$docCommentContent = TokenHelper::getContent($phpcsFile, $docCommentOpenPointer, $tokens[$docCommentOpenPointer]['comment_closer']);
if (preg_match_all(
'~\{(' . implode('|', $correctAnnotationNames) . ')\}~i',
$docCommentContent,
$matches,
PREG_OFFSET_CAPTURE
) === 0) {
return;
}
foreach ($matches[1] as $match) {
$correctAnnotationName = $correctAnnotationNames[strtolower($match[0])];
if ($correctAnnotationName === $match[0]) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf('Annotation name is incorrect. Expected %s, found %s.', $correctAnnotationName, $match[0]),
$docCommentOpenPointer,
self::CODE_ANNOTATION_NAME_INCORRECT
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
$fixedDocCommentContent = substr($docCommentContent, 0, $match[1]) . $correctAnnotationName . substr(
$docCommentContent,
$match[1] + strlen($match[0])
);
FixerHelper::change(
$phpcsFile,
$docCommentOpenPointer,
$tokens[$docCommentOpenPointer]['comment_closer'],
$fixedDocCommentContent
);
$phpcsFile->fixer->endChangeset();
}
}
/**
* @return array<string, string>
*/
private function getNormalizedAnnotationNames(): array
{
if ($this->normalizedAnnotations !== null) {
return $this->normalizedAnnotations;
}
if ($this->annotations !== null) {
$annotationNames = array_map(static function (string $annotationName): string {
return ltrim($annotationName, '@');
}, SniffSettingsHelper::normalizeArray($this->annotations));
} else {
$annotationNames = array_merge(self::STANDARD_ANNOTATIONS, self::PHPUNIT_ANNOTATIONS, self::STATIC_ANALYSIS_ANNOTATIONS);
foreach (self::STATIC_ANALYSIS_ANNOTATIONS as $annotationName) {
if (strpos($annotationName, 'psalm') === 0) {
continue;
}
foreach (AnnotationHelper::STATIC_ANALYSIS_PREFIXES as $prefix) {
$annotationNames[] = sprintf('%s-%s', $prefix, $annotationName);
}
}
}
$annotationNames = array_map(static function (string $annotationName): string {
return '@' . $annotationName;
}, array_unique($annotationNames));
$this->normalizedAnnotations = array_combine(array_map(static function (string $annotationName): string {
return strtolower($annotationName);
}, $annotationNames), $annotationNames);
return $this->normalizedAnnotations;
}
}
@@ -0,0 +1,50 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\PhpDoc\DeprecatedTagValueNode;
use SlevomatCodingStandard\Helpers\Annotation;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use function count;
use const T_DOC_COMMENT_OPEN_TAG;
class DeprecatedAnnotationDeclarationSniff implements Sniff
{
public const MISSING_DESCRIPTION = 'MissingDescription';
/** @return array<int, (int|string)> */
public function register(): array
{
return [T_DOC_COMMENT_OPEN_TAG];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentStartPointer
*/
public function process(File $phpcsFile, $docCommentStartPointer): void
{
/** @var list<Annotation<DeprecatedTagValueNode>> $annotations */
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentStartPointer, '@deprecated');
if (count($annotations) === 0) {
return;
}
foreach ($annotations as $annotation) {
if ($annotation->getValue()->description !== '') {
continue;
}
$phpcsFile->addError(
'Deprecated annotation must have a description.',
$annotation->getStartPointer(),
self::MISSING_DESCRIPTION
);
}
}
}
@@ -0,0 +1,135 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
use SlevomatCodingStandard\Helpers\CommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\IndentationHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function array_merge;
use function in_array;
use function strlen;
use function substr;
use const T_CLOSE_CURLY_BRACKET;
use const T_CLOSURE;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_ELSE;
use const T_ELSEIF;
use const T_OPEN_CURLY_BRACKET;
use const T_WHITESPACE;
class DisallowCommentAfterCodeSniff implements Sniff
{
public const CODE_DISALLOWED_COMMENT_AFTER_CODE = 'DisallowedCommentAfterCode';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
/** @phpstan-var array<int, (int|string)> */
return array_merge(TokenHelper::$inlineCommentTokenCodes, [T_DOC_COMMENT_OPEN_TAG]);
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $commentPointer
*/
public function process(File $phpcsFile, $commentPointer): void
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$commentPointer]['column'] === 1) {
return;
}
$firstNonWhitespacePointerOnLine = TokenHelper::findFirstNonWhitespaceOnLine($phpcsFile, $commentPointer);
if ($firstNonWhitespacePointerOnLine === $commentPointer) {
return;
}
if (
$tokens[$firstNonWhitespacePointerOnLine]['code'] === T_DOC_COMMENT_OPEN_TAG
&& $tokens[$firstNonWhitespacePointerOnLine]['comment_closer'] > $commentPointer
) {
return;
}
$commentEndPointer = CommentHelper::getCommentEndPointer($phpcsFile, $commentPointer);
$nextNonWhitespacePointer = TokenHelper::findNextNonWhitespace($phpcsFile, $commentEndPointer + 1);
if (
$nextNonWhitespacePointer !== null
&& $commentEndPointer !== null
&& $tokens[$nextNonWhitespacePointer]['line'] === $tokens[$commentEndPointer]['line']
) {
return;
}
$fix = $phpcsFile->addFixableError('Comment after code is disallowed.', $commentPointer, self::CODE_DISALLOWED_COMMENT_AFTER_CODE);
if (!$fix) {
return;
}
$commentContent = TokenHelper::getContent($phpcsFile, $commentPointer, $commentEndPointer);
$commentHasNewLineAtTheEnd = substr($commentContent, -strlen($phpcsFile->eolChar)) === $phpcsFile->eolChar;
if (!$commentHasNewLineAtTheEnd) {
$commentContent .= $phpcsFile->eolChar;
}
$firstNonWhiteSpacePointerBeforeComment = TokenHelper::findPreviousNonWhitespace($phpcsFile, $commentPointer - 1);
$newLineAfterComment = $commentHasNewLineAtTheEnd
? $commentEndPointer
: TokenHelper::findLastTokenOnLine($phpcsFile, $commentEndPointer);
$indentation = IndentationHelper::getIndentation($phpcsFile, $firstNonWhitespacePointerOnLine);
$firstPointerOnLine = TokenHelper::findFirstTokenOnLine($phpcsFile, $firstNonWhitespacePointerOnLine);
$phpcsFile->fixer->beginChangeset();
if (
$tokens[$firstNonWhiteSpacePointerBeforeComment]['code'] === T_OPEN_CURLY_BRACKET
&& array_key_exists('scope_condition', $tokens[$firstNonWhiteSpacePointerBeforeComment])
&& in_array(
$tokens[$tokens[$firstNonWhiteSpacePointerBeforeComment]['scope_condition']]['code'],
[T_ELSEIF, T_ELSE, T_CLOSURE],
true
)
) {
$phpcsFile->fixer->addContent(
$firstNonWhiteSpacePointerBeforeComment,
$phpcsFile->eolChar . IndentationHelper::addIndentation($indentation) . $commentContent
);
} elseif ($tokens[$firstNonWhitespacePointerOnLine]['code'] === T_CLOSE_CURLY_BRACKET) {
$phpcsFile->fixer->addContent($firstNonWhiteSpacePointerBeforeComment, $phpcsFile->eolChar . $indentation . $commentContent);
} elseif (isset(Tokens::$stringTokens[$tokens[$firstPointerOnLine]['code']])) {
$prevNonStringToken = TokenHelper::findPreviousExcluding(
$phpcsFile,
[T_WHITESPACE] + Tokens::$stringTokens,
$firstPointerOnLine - 1
);
$firstTokenOnNonStringTokenLine = TokenHelper::findFirstTokenOnLine($phpcsFile, $prevNonStringToken);
$firstNonWhitespacePointerOnNonStringTokenLine = TokenHelper::findFirstNonWhitespaceOnLine($phpcsFile, $prevNonStringToken);
$prevLineIndentation = IndentationHelper::getIndentation($phpcsFile, $firstNonWhitespacePointerOnNonStringTokenLine);
$phpcsFile->fixer->addContentBefore($firstTokenOnNonStringTokenLine, $prevLineIndentation . $commentContent);
$phpcsFile->fixer->addNewline($firstNonWhiteSpacePointerBeforeComment);
} else {
$phpcsFile->fixer->addContentBefore($firstPointerOnLine, $indentation . $commentContent);
$phpcsFile->fixer->addNewline($firstNonWhiteSpacePointerBeforeComment);
}
FixerHelper::removeBetweenIncluding($phpcsFile, $firstNonWhiteSpacePointerBeforeComment + 1, $newLineAfterComment);
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,108 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\PropertyHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function rtrim;
use function sprintf;
use const T_VARIABLE;
use const T_WHITESPACE;
class DisallowOneLinePropertyDocCommentSniff implements Sniff
{
public const CODE_ONE_LINE_PROPERTY_COMMENT = 'OneLinePropertyComment';
/**
* @return list<int>
*/
public function register(): array
{
return [T_VARIABLE];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $propertyPointer
*/
public function process(File $phpcsFile, $propertyPointer): void
{
$tokens = $phpcsFile->getTokens();
// Not a property
if (!PropertyHelper::isProperty($phpcsFile, $propertyPointer)) {
return;
}
// Only validate properties with comment
if (!DocCommentHelper::hasDocComment($phpcsFile, $propertyPointer)) {
return;
}
/** @var int $docCommentStartPointer */
$docCommentStartPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $propertyPointer);
$docCommentEndPointer = $tokens[$docCommentStartPointer]['comment_closer'];
$lineDifference = $tokens[$docCommentEndPointer]['line'] - $tokens[$docCommentStartPointer]['line'];
// Already multi-line
if ($lineDifference !== 0) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Found one-line comment for property %s, use multi-line comment instead.',
PropertyHelper::getFullyQualifiedName($phpcsFile, $propertyPointer)
),
$docCommentStartPointer,
self::CODE_ONE_LINE_PROPERTY_COMMENT
);
if (!$fix) {
return;
}
$commentWhitespacePointer = TokenHelper::findPrevious($phpcsFile, [T_WHITESPACE], $docCommentStartPointer);
$indent = ($commentWhitespacePointer !== null ? $tokens[$commentWhitespacePointer]['content'] : '') . ' ';
/** empty comment is not split into start & end tokens properly */
if ($tokens[$docCommentStartPointer]['content'] === '/***/') {
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($docCommentStartPointer, '/**');
$phpcsFile->fixer->addNewline($docCommentStartPointer);
$phpcsFile->fixer->addContent($docCommentStartPointer, $indent);
$phpcsFile->fixer->addContent($docCommentStartPointer, '*');
$phpcsFile->fixer->addNewline($docCommentStartPointer);
$phpcsFile->fixer->addContent($docCommentStartPointer, $indent);
$phpcsFile->fixer->addContent($docCommentStartPointer, '*/');
$phpcsFile->fixer->endChangeset();
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addNewline($docCommentStartPointer);
$phpcsFile->fixer->addContent($docCommentStartPointer, $indent);
$phpcsFile->fixer->addContent($docCommentStartPointer, '*');
if ($docCommentEndPointer - 1 !== $docCommentStartPointer) {
$phpcsFile->fixer->replaceToken(
$docCommentEndPointer - 1,
rtrim($phpcsFile->fixer->getTokenContent($docCommentEndPointer - 1), ' ')
);
}
$phpcsFile->fixer->addContentBefore($docCommentEndPointer, $indent);
$phpcsFile->fixer->addNewlineBefore($docCommentEndPointer);
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,781 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\Annotation;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\IndentationHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_combine;
use function array_diff;
use function array_flip;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_values;
use function asort;
use function count;
use function explode;
use function in_array;
use function ksort;
use function max;
use function preg_match;
use function sprintf;
use function strlen;
use function strpos;
use function substr;
use function substr_count;
use function trim;
use function usort;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_WHITESPACE;
class DocCommentSpacingSniff implements Sniff
{
public const CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_CONTENT = 'IncorrectLinesCountBeforeFirstContent';
public const CODE_INCORRECT_LINES_COUNT_BETWEEN_DESCRIPTION_AND_ANNOTATIONS = 'IncorrectLinesCountBetweenDescriptionAndAnnotations';
public const CODE_INCORRECT_LINES_COUNT_BETWEEN_DIFFERENT_ANNOTATIONS_TYPES = 'IncorrectLinesCountBetweenDifferentAnnotationsTypes';
public const CODE_INCORRECT_LINES_COUNT_BETWEEN_ANNOTATIONS_GROUPS = 'IncorrectLinesCountBetweenAnnotationsGroups';
public const CODE_INCORRECT_LINES_COUNT_AFTER_LAST_CONTENT = 'IncorrectLinesCountAfterLastContent';
public const CODE_INCORRECT_ANNOTATIONS_GROUP = 'IncorrectAnnotationsGroup';
public const CODE_INCORRECT_ORDER_OF_ANNOTATIONS_GROUPS = 'IncorrectOrderOfAnnotationsGroup';
public const CODE_INCORRECT_ORDER_OF_ANNOTATIONS_IN_GROUP = 'IncorrectOrderOfAnnotationsInGroup';
/** @var int */
public $linesCountBeforeFirstContent = 0;
/** @var int */
public $linesCountBetweenDescriptionAndAnnotations = 1;
/** @var int */
public $linesCountBetweenDifferentAnnotationsTypes = 0;
/** @var int */
public $linesCountBetweenAnnotationsGroups = 1;
/** @var int */
public $linesCountAfterLastContent = 0;
/** @var list<string> */
public $annotationsGroups = [];
/** @var array<list<string>>|null */
private $normalizedAnnotationsGroups = null;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentOpenerPointer
*/
public function process(File $phpcsFile, $docCommentOpenerPointer): void
{
$this->linesCountBeforeFirstContent = SniffSettingsHelper::normalizeInteger($this->linesCountBeforeFirstContent);
$this->linesCountBetweenDescriptionAndAnnotations = SniffSettingsHelper::normalizeInteger(
$this->linesCountBetweenDescriptionAndAnnotations
);
$this->linesCountBetweenDifferentAnnotationsTypes = SniffSettingsHelper::normalizeInteger(
$this->linesCountBetweenDifferentAnnotationsTypes
);
$this->linesCountBetweenAnnotationsGroups = SniffSettingsHelper::normalizeInteger($this->linesCountBetweenAnnotationsGroups);
$this->linesCountAfterLastContent = SniffSettingsHelper::normalizeInteger($this->linesCountAfterLastContent);
if (DocCommentHelper::isInline($phpcsFile, $docCommentOpenerPointer)) {
return;
}
$tokens = $phpcsFile->getTokens();
if (TokenHelper::findNextExcluding(
$phpcsFile,
[T_DOC_COMMENT_WHITESPACE, T_DOC_COMMENT_STAR],
$docCommentOpenerPointer + 1,
$tokens[$docCommentOpenerPointer]['comment_closer']
) === null) {
return;
}
$parsedDocComment = DocCommentHelper::parseDocComment($phpcsFile, $docCommentOpenerPointer);
if ($parsedDocComment === null) {
return;
}
$firstContentStartPointer = $parsedDocComment->getNodeStartPointer($phpcsFile, $parsedDocComment->getNode()->children[0]);
$firstContentEndPointer = $parsedDocComment->getNodeEndPointer(
$phpcsFile,
$parsedDocComment->getNode()->children[0],
$firstContentStartPointer
);
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenerPointer);
usort($annotations, static function (Annotation $a, Annotation $b): int {
return $a->getStartPointer() <=> $b->getStartPointer();
});
$annotationsCount = count($annotations);
$firstAnnotationPointer = $annotationsCount > 0 ? $annotations[0]->getStartPointer() : null;
/** @var int $lastContentEndPointer */
$lastContentEndPointer = $annotationsCount > 0
? $annotations[$annotationsCount - 1]->getEndPointer()
: $firstContentEndPointer;
$this->checkLinesBeforeFirstContent($phpcsFile, $docCommentOpenerPointer, $firstContentStartPointer);
$this->checkLinesBetweenDescriptionAndFirstAnnotation(
$phpcsFile,
$docCommentOpenerPointer,
$firstContentStartPointer,
$firstContentEndPointer,
$firstAnnotationPointer
);
if (count($annotations) > 1) {
if (count($this->getAnnotationsGroups()) === 0) {
$this->checkLinesBetweenDifferentAnnotationsTypes($phpcsFile, $docCommentOpenerPointer, $annotations);
} else {
$this->checkAnnotationsGroups($phpcsFile, $docCommentOpenerPointer, $annotations);
}
}
$this->checkLinesAfterLastContent(
$phpcsFile,
$docCommentOpenerPointer,
$tokens[$docCommentOpenerPointer]['comment_closer'],
$lastContentEndPointer
);
}
private function checkLinesBeforeFirstContent(File $phpcsFile, int $docCommentOpenerPointer, int $firstContentStartPointer): void
{
$tokens = $phpcsFile->getTokens();
$whitespaceBeforeFirstContent = substr($tokens[$docCommentOpenerPointer]['content'], 0, strlen('/**'));
$whitespaceBeforeFirstContent .= TokenHelper::getContent($phpcsFile, $docCommentOpenerPointer + 1, $firstContentStartPointer - 1);
$linesCountBeforeFirstContent = max(substr_count($whitespaceBeforeFirstContent, $phpcsFile->eolChar) - 1, 0);
if ($linesCountBeforeFirstContent === $this->linesCountBeforeFirstContent) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s before first content, found %d.',
$this->linesCountBeforeFirstContent,
$this->linesCountBeforeFirstContent === 1 ? '' : 's',
$linesCountBeforeFirstContent
),
$firstContentStartPointer,
self::CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_CONTENT
);
if (!$fix) {
return;
}
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$phpcsFile->fixer->beginChangeset();
FixerHelper::change($phpcsFile, $docCommentOpenerPointer, $firstContentStartPointer - 1, '/**' . $phpcsFile->eolChar);
for ($i = 1; $i <= $this->linesCountBeforeFirstContent; $i++) {
$phpcsFile->fixer->addContent($docCommentOpenerPointer, sprintf('%s *%s', $indentation, $phpcsFile->eolChar));
}
$phpcsFile->fixer->addContentBefore($firstContentStartPointer, $indentation . ' * ');
$phpcsFile->fixer->endChangeset();
}
private function checkLinesBetweenDescriptionAndFirstAnnotation(
File $phpcsFile,
int $docCommentOpenerPointer,
int $firstContentStartPointer,
int $firstContentEndPointer,
?int $firstAnnotationPointer
): void
{
if ($firstAnnotationPointer === null) {
return;
}
if ($firstContentStartPointer === $firstAnnotationPointer) {
return;
}
$tokens = $phpcsFile->getTokens();
preg_match('~(\\s+)$~', $tokens[$firstContentEndPointer]['content'], $matches);
$whitespaceBetweenDescriptionAndFirstAnnotation = $matches[1] ?? '';
$whitespaceBetweenDescriptionAndFirstAnnotation .= TokenHelper::getContent(
$phpcsFile,
$firstContentEndPointer + 1,
$firstAnnotationPointer - 1
);
$linesCountBetweenDescriptionAndAnnotations = max(
substr_count($whitespaceBetweenDescriptionAndFirstAnnotation, $phpcsFile->eolChar) - 1,
0
);
if ($linesCountBetweenDescriptionAndAnnotations === $this->linesCountBetweenDescriptionAndAnnotations) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s between description and annotations, found %d.',
$this->linesCountBetweenDescriptionAndAnnotations,
$this->linesCountBetweenDescriptionAndAnnotations === 1 ? '' : 's',
$linesCountBetweenDescriptionAndAnnotations
),
$firstAnnotationPointer,
self::CODE_INCORRECT_LINES_COUNT_BETWEEN_DESCRIPTION_AND_ANNOTATIONS
);
if (!$fix) {
return;
}
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addNewline($firstContentEndPointer);
FixerHelper::removeBetween($phpcsFile, $firstContentEndPointer, $firstAnnotationPointer);
for ($i = 1; $i <= $this->linesCountBetweenDescriptionAndAnnotations; $i++) {
$phpcsFile->fixer->addContent($firstContentEndPointer, sprintf('%s *%s', $indentation, $phpcsFile->eolChar));
}
$phpcsFile->fixer->addContentBefore($firstAnnotationPointer, $indentation . ' * ');
$phpcsFile->fixer->endChangeset();
}
/**
* @param list<Annotation> $annotations
*/
private function checkLinesBetweenDifferentAnnotationsTypes(File $phpcsFile, int $docCommentOpenerPointer, array $annotations): void
{
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$previousAnnotation = null;
foreach ($annotations as $annotation) {
if ($previousAnnotation === null) {
$previousAnnotation = $annotation;
continue;
}
if ($annotation->getName() === $previousAnnotation->getName()) {
$previousAnnotation = $annotation;
continue;
}
$whitespaceAfterPreviousAnnotation = TokenHelper::getContent(
$phpcsFile,
$previousAnnotation->getEndPointer() + 1,
$annotation->getStartPointer() - 1
);
$linesCountAfterPreviousAnnotation = max(substr_count($whitespaceAfterPreviousAnnotation, $phpcsFile->eolChar) - 1, 0);
if ($linesCountAfterPreviousAnnotation === $this->linesCountBetweenDifferentAnnotationsTypes) {
$previousAnnotation = $annotation;
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s between different annotations types, found %d.',
$this->linesCountBetweenDifferentAnnotationsTypes,
$this->linesCountBetweenDifferentAnnotationsTypes === 1 ? '' : 's',
$linesCountAfterPreviousAnnotation
),
$annotation->getStartPointer(),
self::CODE_INCORRECT_LINES_COUNT_BETWEEN_DIFFERENT_ANNOTATIONS_TYPES
);
if (!$fix) {
$previousAnnotation = $annotation;
continue;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $previousAnnotation->getEndPointer(), $annotation->getStartPointer());
$phpcsFile->fixer->addNewline($previousAnnotation->getEndPointer());
for ($i = 1; $i <= $this->linesCountBetweenDifferentAnnotationsTypes; $i++) {
$phpcsFile->fixer->addContent($previousAnnotation->getEndPointer(), sprintf('%s *%s', $indentation, $phpcsFile->eolChar));
}
$phpcsFile->fixer->addContentBefore($annotation->getStartPointer(), $indentation . ' * ');
$phpcsFile->fixer->endChangeset();
$previousAnnotation = $annotation;
}
}
/**
* @param list<Annotation> $annotations
*/
private function checkAnnotationsGroups(File $phpcsFile, int $docCommentOpenerPointer, array $annotations): void
{
$tokens = $phpcsFile->getTokens();
$annotationsGroups = [];
$annotationsGroup = [];
$previousAnnotation = null;
foreach ($annotations as $annotation) {
if (
$previousAnnotation === null
|| $tokens[$previousAnnotation->getEndPointer()]['line'] + 1 === $tokens[$annotation->getStartPointer()]['line']
) {
$annotationsGroup[] = $annotation;
$previousAnnotation = $annotation;
continue;
}
$annotationsGroups[] = $annotationsGroup;
$annotationsGroup = [$annotation];
$previousAnnotation = $annotation;
}
if (count($annotationsGroup) > 0) {
$annotationsGroups[] = $annotationsGroup;
}
$this->checkAnnotationsGroupsOrder($phpcsFile, $docCommentOpenerPointer, $annotationsGroups, $annotations);
$this->checkLinesBetweenAnnotationsGroups($phpcsFile, $docCommentOpenerPointer, $annotationsGroups);
}
/**
* @param list<list<Annotation>> $annotationsGroups
*/
private function checkLinesBetweenAnnotationsGroups(File $phpcsFile, int $docCommentOpenerPointer, array $annotationsGroups): void
{
$tokens = $phpcsFile->getTokens();
$previousAnnotationsGroup = null;
foreach ($annotationsGroups as $annotationsGroup) {
if ($previousAnnotationsGroup === null) {
$previousAnnotationsGroup = $annotationsGroup;
continue;
}
$lastAnnotationInPreviousGroup = $previousAnnotationsGroup[count($previousAnnotationsGroup) - 1];
$firstAnnotationInActualGroup = $annotationsGroup[0];
$actualLinesCountBetweenAnnotationsGroups = $tokens[$firstAnnotationInActualGroup->getStartPointer()]['line'] - $tokens[$lastAnnotationInPreviousGroup->getEndPointer()]['line'] - 1;
if ($actualLinesCountBetweenAnnotationsGroups === $this->linesCountBetweenAnnotationsGroups) {
$previousAnnotationsGroup = $annotationsGroup;
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s between annotations groups, found %d.',
$this->linesCountBetweenAnnotationsGroups,
$this->linesCountBetweenAnnotationsGroups === 1 ? '' : 's',
$actualLinesCountBetweenAnnotationsGroups
),
$firstAnnotationInActualGroup->getStartPointer(),
self::CODE_INCORRECT_LINES_COUNT_BETWEEN_ANNOTATIONS_GROUPS
);
if (!$fix) {
$previousAnnotationsGroup = $annotationsGroup;
continue;
}
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addNewline($lastAnnotationInPreviousGroup->getEndPointer());
FixerHelper::removeBetween(
$phpcsFile,
$lastAnnotationInPreviousGroup->getEndPointer(),
$firstAnnotationInActualGroup->getStartPointer()
);
for ($i = 1; $i <= $this->linesCountBetweenAnnotationsGroups; $i++) {
$phpcsFile->fixer->addContent(
$lastAnnotationInPreviousGroup->getEndPointer(),
sprintf('%s *%s', $indentation, $phpcsFile->eolChar)
);
}
$phpcsFile->fixer->addContentBefore(
$firstAnnotationInActualGroup->getStartPointer(),
$indentation . ' * '
);
$phpcsFile->fixer->endChangeset();
}
}
/**
* @param list<list<Annotation>> $annotationsGroups
* @param list<Annotation> $annotations
*/
private function checkAnnotationsGroupsOrder(
File $phpcsFile,
int $docCommentOpenerPointer,
array $annotationsGroups,
array $annotations
): void
{
$getAnnotationsPointers = static function (Annotation $annotation): int {
return $annotation->getStartPointer();
};
$equals = static function (array $firstAnnotationsGroup, array $secondAnnotationsGroup) use ($getAnnotationsPointers): bool {
$firstAnnotationsPointers = array_map($getAnnotationsPointers, $firstAnnotationsGroup);
$secondAnnotationsPointers = array_map($getAnnotationsPointers, $secondAnnotationsGroup);
return count(array_diff($firstAnnotationsPointers, $secondAnnotationsPointers)) === 0
&& count(array_diff($secondAnnotationsPointers, $firstAnnotationsPointers)) === 0;
};
$sortedAnnotationsGroups = $this->sortAnnotationsToGroups($annotations);
$incorrectAnnotationsGroupsExist = false;
$annotationsGroupsPositions = [];
$fix = false;
$undefinedAnnotationsGroups = [];
foreach ($annotationsGroups as $annotationsGroupPosition => $annotationsGroup) {
foreach ($sortedAnnotationsGroups as $sortedAnnotationsGroupPosition => $sortedAnnotationsGroup) {
if ($equals($annotationsGroup, $sortedAnnotationsGroup)) {
$annotationsGroupsPositions[$annotationsGroupPosition] = $sortedAnnotationsGroupPosition;
continue 2;
}
$undefinedAnnotationsGroup = true;
foreach ($annotationsGroup as $annotation) {
foreach ($this->getAnnotationsGroups() as $annotationNames) {
foreach ($annotationNames as $annotationName) {
if ($this->isAnnotationMatched($annotation, $annotationName)) {
$undefinedAnnotationsGroup = false;
break 3;
}
}
}
}
if ($undefinedAnnotationsGroup) {
$undefinedAnnotationsGroups[] = $annotationsGroupPosition;
continue 2;
}
}
$incorrectAnnotationsGroupsExist = true;
$fix = $phpcsFile->addFixableError(
'Incorrect annotations group.',
$annotationsGroup[0]->getStartPointer(),
self::CODE_INCORRECT_ANNOTATIONS_GROUP
);
}
if (count($annotationsGroupsPositions) === 0 && count($undefinedAnnotationsGroups) > 1) {
$incorrectAnnotationsGroupsExist = true;
$fix = $phpcsFile->addFixableError(
'Incorrect annotations group.',
$annotationsGroups[0][0]->getStartPointer(),
self::CODE_INCORRECT_ANNOTATIONS_GROUP
);
}
if (!$incorrectAnnotationsGroupsExist) {
foreach ($undefinedAnnotationsGroups as $undefinedAnnotationsGroupPosition) {
$annotationsGroupsPositions[$undefinedAnnotationsGroupPosition] = (count($annotationsGroupsPositions) > 0
? max($annotationsGroupsPositions)
: 0) + 1;
}
ksort($annotationsGroupsPositions);
$positionsMappedToGroups = array_keys($annotationsGroupsPositions);
$tmp = array_values($annotationsGroupsPositions);
asort($tmp);
/** @var list<int> $normalizedAnnotationsGroupsPositions */
$normalizedAnnotationsGroupsPositions = array_combine(array_keys($positionsMappedToGroups), array_keys($tmp));
foreach ($normalizedAnnotationsGroupsPositions as $normalizedAnnotationsGroupPosition => $sortedAnnotationsGroupPosition) {
if ($normalizedAnnotationsGroupPosition === $sortedAnnotationsGroupPosition) {
continue;
}
$fix = $phpcsFile->addFixableError(
'Incorrect order of annotations groups.',
$annotationsGroups[$positionsMappedToGroups[$normalizedAnnotationsGroupPosition]][0]->getStartPointer(),
self::CODE_INCORRECT_ORDER_OF_ANNOTATIONS_GROUPS
);
break;
}
}
foreach ($annotationsGroups as $annotationsGroupPosition => $annotationsGroup) {
if (!array_key_exists($annotationsGroupPosition, $annotationsGroupsPositions)) {
continue;
}
if (!array_key_exists($annotationsGroupsPositions[$annotationsGroupPosition], $sortedAnnotationsGroups)) {
continue;
}
$sortedAnnotationsGroup = $sortedAnnotationsGroups[$annotationsGroupsPositions[$annotationsGroupPosition]];
foreach ($annotationsGroup as $annotationPosition => $annotation) {
if ($annotation === $sortedAnnotationsGroup[$annotationPosition]) {
continue;
}
$fix = $phpcsFile->addFixableError(
'Incorrect order of annotations in group.',
$annotation->getStartPointer(),
self::CODE_INCORRECT_ORDER_OF_ANNOTATIONS_IN_GROUP
);
break;
}
}
if (!$fix) {
return;
}
$firstAnnotation = $annotationsGroups[0][0];
$lastAnnotationsGroup = $annotationsGroups[count($annotationsGroups) - 1];
$lastAnnotation = $lastAnnotationsGroup[count($lastAnnotationsGroup) - 1];
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$fixedAnnotations = '';
$firstGroup = true;
foreach ($sortedAnnotationsGroups as $sortedAnnotationsGroup) {
if ($firstGroup) {
$firstGroup = false;
} else {
for ($i = 0; $i < $this->linesCountBetweenAnnotationsGroups; $i++) {
$fixedAnnotations .= sprintf('%s *%s', $indentation, $phpcsFile->eolChar);
}
}
foreach ($sortedAnnotationsGroup as $sortedAnnotation) {
$fixedAnnotations .= sprintf(
'%s * %s%s',
$indentation,
trim(TokenHelper::getContent($phpcsFile, $sortedAnnotation->getStartPointer(), $sortedAnnotation->getEndPointer())),
$phpcsFile->eolChar
);
}
}
$tokens = $phpcsFile->getTokens();
$docCommentCloserPointer = $tokens[$docCommentOpenerPointer]['comment_closer'];
$endOfLineBeforeFirstAnnotation = TokenHelper::findPreviousContent(
$phpcsFile,
T_DOC_COMMENT_WHITESPACE,
$phpcsFile->eolChar,
$firstAnnotation->getStartPointer() - 1,
$docCommentOpenerPointer
);
$docCommentContentEndPointer = TokenHelper::findNextContent(
$phpcsFile,
T_DOC_COMMENT_WHITESPACE,
$phpcsFile->eolChar,
$lastAnnotation->getEndPointer() + 1,
$docCommentCloserPointer
);
if ($docCommentContentEndPointer === null) {
$docCommentContentEndPointer = $lastAnnotation->getEndPointer();
}
$phpcsFile->fixer->beginChangeset();
if ($endOfLineBeforeFirstAnnotation === null) {
FixerHelper::change(
$phpcsFile,
$docCommentOpenerPointer,
$docCommentContentEndPointer,
'/**' . $phpcsFile->eolChar . $fixedAnnotations
);
} else {
FixerHelper::change($phpcsFile, $endOfLineBeforeFirstAnnotation + 1, $docCommentContentEndPointer, $fixedAnnotations);
}
$phpcsFile->fixer->endChangeset();
}
/**
* @param list<Annotation> $annotations
* @return list<list<Annotation>>
*/
private function sortAnnotationsToGroups(array $annotations): array
{
$expectedAnnotationsGroups = $this->getAnnotationsGroups();
$sortedAnnotationsGroups = [];
$annotationsNotInAnyGroup = [];
foreach ($annotations as $annotation) {
foreach ($expectedAnnotationsGroups as $annotationsGroupPosition => $annotationsGroup) {
foreach ($annotationsGroup as $annotationName) {
if ($this->isAnnotationMatched($annotation, $annotationName)) {
$sortedAnnotationsGroups[$annotationsGroupPosition][] = $annotation;
continue 3;
}
}
}
$annotationsNotInAnyGroup[] = $annotation;
}
ksort($sortedAnnotationsGroups);
foreach (array_keys($sortedAnnotationsGroups) as $annotationsGroupPosition) {
$expectedAnnotationsGroupOrder = array_flip($expectedAnnotationsGroups[$annotationsGroupPosition]);
usort(
$sortedAnnotationsGroups[$annotationsGroupPosition],
function (Annotation $firstAnnotation, Annotation $secondAnnotation) use ($expectedAnnotationsGroupOrder): int {
$getExpectedOrder = function (string $annotationName) use ($expectedAnnotationsGroupOrder): int {
if (array_key_exists($annotationName, $expectedAnnotationsGroupOrder)) {
return $expectedAnnotationsGroupOrder[$annotationName];
}
$order = 0;
foreach ($expectedAnnotationsGroupOrder as $expectedAnnotationName => $expectedAnnotationOrder) {
if ($this->isAnnotationNameInAnnotationNamespace($expectedAnnotationName, $annotationName)) {
$order = $expectedAnnotationOrder;
break;
}
}
return $order;
};
$expectedOrder = $getExpectedOrder($firstAnnotation->getName()) <=> $getExpectedOrder($secondAnnotation->getName());
return $expectedOrder !== 0
? $expectedOrder
: $firstAnnotation->getStartPointer() <=> $secondAnnotation->getStartPointer();
}
);
}
if (count($annotationsNotInAnyGroup) > 0) {
$sortedAnnotationsGroups[] = $annotationsNotInAnyGroup;
}
return $sortedAnnotationsGroups;
}
private function isAnnotationNameInAnnotationNamespace(string $annotationNamespace, string $annotationName): bool
{
return $this->isAnnotationStartedFrom($annotationNamespace, $annotationName)
|| (
in_array(substr($annotationNamespace, -1), ['\\', '-', ':'], true)
&& strpos($annotationName, $annotationNamespace) === 0
);
}
private function isAnnotationStartedFrom(string $annotationNamespace, string $annotationName): bool
{
return substr($annotationNamespace, -1) === '*'
&& strpos($annotationName, substr($annotationNamespace, 0, -1)) === 0;
}
private function isAnnotationMatched(Annotation $annotation, string $annotationName): bool
{
if ($annotation->getName() === $annotationName) {
return true;
}
return $this->isAnnotationNameInAnnotationNamespace($annotationName, $annotation->getName());
}
private function checkLinesAfterLastContent(
File $phpcsFile,
int $docCommentOpenerPointer,
int $docCommentCloserPointer,
int $lastContentEndPointer
): void
{
$whitespaceAfterLastContent = TokenHelper::getContent($phpcsFile, $lastContentEndPointer + 1, $docCommentCloserPointer);
$linesCountAfterLastContent = max(substr_count($whitespaceAfterLastContent, $phpcsFile->eolChar) - 1, 0);
if ($linesCountAfterLastContent === $this->linesCountAfterLastContent) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s after last content, found %d.',
$this->linesCountAfterLastContent,
$this->linesCountAfterLastContent === 1 ? '' : 's',
$linesCountAfterLastContent
),
$lastContentEndPointer,
self::CODE_INCORRECT_LINES_COUNT_AFTER_LAST_CONTENT
);
if (!$fix) {
return;
}
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenerPointer);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $lastContentEndPointer, $docCommentCloserPointer);
$phpcsFile->fixer->addNewline($lastContentEndPointer);
for ($i = 1; $i <= $this->linesCountAfterLastContent; $i++) {
$phpcsFile->fixer->addContent($lastContentEndPointer, sprintf('%s *%s', $indentation, $phpcsFile->eolChar));
}
$phpcsFile->fixer->addContentBefore($docCommentCloserPointer, $indentation . ' ');
$phpcsFile->fixer->endChangeset();
}
/**
* @return array<list<string>>
*/
private function getAnnotationsGroups(): array
{
if ($this->normalizedAnnotationsGroups === null) {
$this->normalizedAnnotationsGroups = [];
foreach ($this->annotationsGroups as $annotationsGroup) {
$this->normalizedAnnotationsGroups[] = SniffSettingsHelper::normalizeArray(explode(',', $annotationsGroup));
}
}
return $this->normalizedAnnotationsGroups;
}
}
@@ -0,0 +1,198 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\CommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\StringHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function preg_match;
use function preg_replace;
use function substr;
use const T_COMMENT;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_WHITESPACE;
class EmptyCommentSniff implements Sniff
{
public const CODE_EMPTY_COMMENT = 'EmptyComment';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
T_COMMENT,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $commentStartPointer
*/
public function process(File $phpcsFile, $commentStartPointer): void
{
$commentEndPointer = CommentHelper::getCommentEndPointer($phpcsFile, $commentStartPointer);
if ($commentEndPointer === null) {
// Part of block comment
return;
}
$commentContent = $this->getCommentContent($phpcsFile, $commentStartPointer, $commentEndPointer);
$isLineComment = CommentHelper::isLineComment($phpcsFile, $commentStartPointer);
$isEmpty = $this->isEmpty($commentContent, $isLineComment);
if (!$isEmpty) {
return;
}
if (
$isLineComment
&& $this->isPartOfMultiLineInlineComments($phpcsFile, $commentStartPointer, $commentEndPointer)
) {
return;
}
$fix = $phpcsFile->addFixableError('Empty comment', $commentStartPointer, self::CODE_EMPTY_COMMENT);
if (!$fix) {
return;
}
$tokens = $phpcsFile->getTokens();
/** @var int $pointerBeforeWhitespaceBeforeComment */
$pointerBeforeWhitespaceBeforeComment = TokenHelper::findPreviousNonWhitespace($phpcsFile, $commentStartPointer - 1);
$whitespaceBeforeComment = $pointerBeforeWhitespaceBeforeComment !== $commentStartPointer - 1
? TokenHelper::getContent($phpcsFile, $pointerBeforeWhitespaceBeforeComment + 1, $commentStartPointer - 1)
: '';
$fixedWhitespaceBeforeComment = preg_replace('~[ \\t]+$~', '', $whitespaceBeforeComment);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $pointerBeforeWhitespaceBeforeComment, $commentStartPointer);
$phpcsFile->fixer->addContent($pointerBeforeWhitespaceBeforeComment, $fixedWhitespaceBeforeComment);
FixerHelper::removeBetweenIncluding($phpcsFile, $commentStartPointer, $commentEndPointer);
$whitespacePointerAfterComment = $commentEndPointer + 1;
if ($tokens[$pointerBeforeWhitespaceBeforeComment]['line'] === $tokens[$commentStartPointer]['line']) {
if (StringHelper::endsWith($tokens[$commentEndPointer]['content'], $phpcsFile->eolChar)) {
$phpcsFile->fixer->addNewline($commentEndPointer);
}
} elseif (
array_key_exists($whitespacePointerAfterComment, $tokens)
&& $tokens[$whitespacePointerAfterComment]['code'] === T_WHITESPACE
) {
$fixedWhitespaceAfterComment = preg_replace(
'~^[ \\t]*' . $phpcsFile->eolChar . '~',
'',
$tokens[$whitespacePointerAfterComment]['content']
);
$phpcsFile->fixer->replaceToken($whitespacePointerAfterComment, $fixedWhitespaceAfterComment);
}
$phpcsFile->fixer->endChangeset();
}
private function isEmpty(string $comment, bool $isLineComment): bool
{
return $isLineComment
? (bool) preg_match('~^\\s*$~', $comment)
: (bool) preg_match('~^[\\s\*]*$~', $comment);
}
private function getCommentContent(File $phpcsFile, int $commentStartPointer, int $commentEndPointer): string
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$commentStartPointer]['code'] === T_DOC_COMMENT_OPEN_TAG) {
return TokenHelper::getContent($phpcsFile, $commentStartPointer + 1, $commentEndPointer - 1);
}
if (preg_match('~^(?://|#)(.*)~', $tokens[$commentStartPointer]['content'], $matches) !== 0) {
return $matches[1];
}
return substr(TokenHelper::getContent($phpcsFile, $commentStartPointer, $commentEndPointer), 2, -2);
}
private function isPartOfMultiLineInlineComments(File $phpcsFile, int $commentStartPointer, int $commentEndPointer): bool
{
if (!$this->isNonEmptyLineCommentBefore($phpcsFile, $commentStartPointer)) {
return false;
}
return $this->isNonEmptyLineCommentAfter($phpcsFile, $commentEndPointer);
}
private function isNonEmptyLineCommentBefore(File $phpcsFile, int $commentStartPointer): bool
{
$tokens = $phpcsFile->getTokens();
/** @var int $beforeCommentStartPointer */
$beforeCommentStartPointer = TokenHelper::findPreviousNonWhitespace($phpcsFile, $commentStartPointer - 1);
if ($tokens[$beforeCommentStartPointer]['code'] !== T_COMMENT) {
return false;
}
if (!CommentHelper::isLineComment($phpcsFile, $beforeCommentStartPointer)) {
return false;
}
if ($tokens[$beforeCommentStartPointer]['line'] + 1 !== $tokens[$commentStartPointer]['line']) {
return false;
}
/** @var int $beforeCommentEndPointer */
$beforeCommentEndPointer = CommentHelper::getCommentEndPointer($phpcsFile, $beforeCommentStartPointer);
if (!$this->isEmpty($this->getCommentContent($phpcsFile, $beforeCommentStartPointer, $beforeCommentEndPointer), true)) {
return true;
}
return $this->isNonEmptyLineCommentBefore($phpcsFile, $beforeCommentStartPointer);
}
private function isNonEmptyLineCommentAfter(File $phpcsFile, int $commentEndPointer): bool
{
$tokens = $phpcsFile->getTokens();
$afterCommentStartPointer = TokenHelper::findNextNonWhitespace($phpcsFile, $commentEndPointer + 1);
if ($afterCommentStartPointer === null) {
return false;
}
if ($tokens[$afterCommentStartPointer]['code'] !== T_COMMENT) {
return false;
}
if (!CommentHelper::isLineComment($phpcsFile, $afterCommentStartPointer)) {
return false;
}
if ($tokens[$commentEndPointer]['line'] + 1 !== $tokens[$afterCommentStartPointer]['line']) {
return false;
}
/** @var int $afterCommentEndPointer */
$afterCommentEndPointer = CommentHelper::getCommentEndPointer($phpcsFile, $afterCommentStartPointer);
if (!$this->isEmpty($this->getCommentContent($phpcsFile, $afterCommentStartPointer, $afterCommentEndPointer), true)) {
return true;
}
return $this->isNonEmptyLineCommentAfter($phpcsFile, $afterCommentEndPointer);
}
}
@@ -0,0 +1,132 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function in_array;
use function sprintf;
use function trim;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_TAG;
use const T_DOC_COMMENT_WHITESPACE;
class ForbiddenAnnotationsSniff implements Sniff
{
public const CODE_ANNOTATION_FORBIDDEN = 'AnnotationForbidden';
/** @var list<string> */
public $forbiddenAnnotations = [];
/** @var list<string>|null */
private $normalizedForbiddenAnnotations;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentOpenPointer
*/
public function process(File $phpcsFile, $docCommentOpenPointer): void
{
$tokens = $phpcsFile->getTokens();
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer);
foreach ($annotations as $annotation) {
if (!in_array($annotation->getName(), $this->getNormalizedForbiddenAnnotations(), true)) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf('Use of annotation %s is forbidden.', $annotation->getName()),
$annotation->getStartPointer(),
self::CODE_ANNOTATION_FORBIDDEN
);
if (!$fix) {
continue;
}
$starPointer = TokenHelper::findPrevious(
$phpcsFile,
T_DOC_COMMENT_STAR,
$annotation->getStartPointer() - 1,
$docCommentOpenPointer
);
$annotationStartPointer = $starPointer ?? $annotation->getStartPointer();
/** @var int $nextPointer */
$nextPointer = TokenHelper::findNext(
$phpcsFile,
[T_DOC_COMMENT_TAG, T_DOC_COMMENT_CLOSE_TAG],
$annotation->getEndPointer() + 1
);
if ($tokens[$nextPointer]['code'] === T_DOC_COMMENT_TAG) {
$nextPointer = TokenHelper::findPrevious($phpcsFile, T_DOC_COMMENT_STAR, $nextPointer - 1);
}
$annotationEndPointer = $nextPointer - 1;
if ($tokens[$nextPointer]['code'] === T_DOC_COMMENT_CLOSE_TAG && $starPointer !== null) {
$pointerBeforeWhitespace = TokenHelper::findPreviousExcluding(
$phpcsFile,
[T_DOC_COMMENT_WHITESPACE, T_DOC_COMMENT_STAR],
$annotationStartPointer - 1
);
/** @var int $annotationStartPointer */
$annotationStartPointer = TokenHelper::findNext($phpcsFile, T_DOC_COMMENT_STAR, $pointerBeforeWhitespace + 1);
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $annotationStartPointer, $annotationEndPointer);
$docCommentUseful = false;
$docCommentClosePointer = $tokens[$docCommentOpenPointer]['comment_closer'];
for ($i = $docCommentOpenPointer + 1; $i < $docCommentClosePointer; $i++) {
$tokenContent = trim($phpcsFile->fixer->getTokenContent($i));
if ($tokenContent === '' || $tokenContent === '*') {
continue;
}
$docCommentUseful = true;
break;
}
if (!$docCommentUseful) {
/** @var int $nextPointerAfterDocComment */
$nextPointerAfterDocComment = TokenHelper::findNextEffective($phpcsFile, $docCommentClosePointer + 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $docCommentOpenPointer, $nextPointerAfterDocComment - 1);
}
$phpcsFile->fixer->endChangeset();
}
}
/**
* @return list<string>
*/
private function getNormalizedForbiddenAnnotations(): array
{
if ($this->normalizedForbiddenAnnotations === null) {
$this->normalizedForbiddenAnnotations = SniffSettingsHelper::normalizeArray($this->forbiddenAnnotations);
}
return $this->normalizedForbiddenAnnotations;
}
}
@@ -0,0 +1,132 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use Exception;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use function array_key_exists;
use function is_array;
use function preg_match;
use function preg_replace;
use function sprintf;
use const T_DOC_COMMENT_OPEN_TAG;
class ForbiddenCommentsSniff implements Sniff
{
public const CODE_COMMENT_FORBIDDEN = 'CommentForbidden';
/** @var list<string> */
public $forbiddenCommentPatterns = [];
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentOpenPointer
*/
public function process(File $phpcsFile, $docCommentOpenPointer): void
{
$tokens = $phpcsFile->getTokens();
$comments = DocCommentHelper::getDocCommentDescription($phpcsFile, $docCommentOpenPointer);
if ($comments === null) {
return;
}
foreach (SniffSettingsHelper::normalizeArray($this->forbiddenCommentPatterns) as $forbiddenCommentPattern) {
if (!SniffSettingsHelper::isValidRegularExpression($forbiddenCommentPattern)) {
throw new Exception(sprintf('%s is not valid PCRE pattern.', $forbiddenCommentPattern));
}
foreach ($comments as $comment) {
if (preg_match($forbiddenCommentPattern, $comment->getContent()) === 0) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf('Documentation comment contains forbidden comment "%s".', $comment->getContent()),
$comment->getPointer(),
self::CODE_COMMENT_FORBIDDEN
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
$fixedDocComment = preg_replace($forbiddenCommentPattern, '', $comment->getContent());
$phpcsFile->fixer->replaceToken($comment->getPointer(), $fixedDocComment);
for ($i = $comment->getPointer() - 1; $i > $docCommentOpenPointer; $i--) {
$contentWithoutSpaces = preg_replace('~ +$~', '', $tokens[$i]['content'], -1, $replacedCount);
if ($replacedCount === 0) {
break;
}
$phpcsFile->fixer->replaceToken($i, $contentWithoutSpaces);
}
$docCommentContent = '';
for ($i = $docCommentOpenPointer + 1; $i < $tokens[$docCommentOpenPointer]['comment_closer']; $i++) {
/** @var string|array<(string|int)> $token */
$token = $phpcsFile->fixer->getTokenContent($i);
$docCommentContent .= is_array($token) ? $token['content'] : $token;
}
if (preg_match('~^[\\s\*]*$~', $docCommentContent) !== 0) {
$pointerBeforeDocComment = $docCommentOpenPointer - 1;
$contentBeforeWithoutSpaces = preg_replace(
'~[\t ]+$~',
'',
$tokens[$pointerBeforeDocComment]['content'],
-1,
$replacedCount
);
if ($replacedCount !== 0) {
$phpcsFile->fixer->replaceToken($pointerBeforeDocComment, $contentBeforeWithoutSpaces);
}
FixerHelper::removeBetweenIncluding(
$phpcsFile,
$docCommentOpenPointer,
$tokens[$docCommentOpenPointer]['comment_closer']
);
$pointerAfterDocComment = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
if (array_key_exists($pointerAfterDocComment, $tokens)) {
$contentAfterWithoutSpaces = preg_replace(
'~^[\r\n]+~',
'',
$tokens[$pointerAfterDocComment]['content'],
-1,
$replacedCount
);
if ($replacedCount !== 0) {
$phpcsFile->fixer->replaceToken($pointerAfterDocComment, $contentAfterWithoutSpaces);
}
}
}
$phpcsFile->fixer->endChangeset();
}
}
}
}
@@ -0,0 +1,495 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use SlevomatCodingStandard\Helpers\Annotation;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\PropertyHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function count;
use function in_array;
use function preg_match;
use function sprintf;
use function substr;
use const T_AS;
use const T_ATTRIBUTE;
use const T_CLOSURE;
use const T_COALESCE_EQUAL;
use const T_COMMENT;
use const T_CONST;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_EQUAL;
use const T_FINAL;
use const T_FN;
use const T_FOREACH;
use const T_LIST;
use const T_OPEN_SHORT_ARRAY;
use const T_PRIVATE;
use const T_PROTECTED;
use const T_PUBLIC;
use const T_READONLY;
use const T_RETURN;
use const T_SEMICOLON;
use const T_STATIC;
use const T_VARIABLE;
use const T_WHILE;
class InlineDocCommentDeclarationSniff implements Sniff
{
public const CODE_INVALID_FORMAT = 'InvalidFormat';
public const CODE_INVALID_COMMENT_TYPE = 'InvalidCommentType';
public const CODE_MISSING_VARIABLE = 'MissingVariable';
public const CODE_NO_ASSIGNMENT = 'NoAssignment';
/** @var bool */
public $allowDocCommentAboveReturn = false;
/** @var bool */
public $allowAboveNonAssignment = false;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
T_COMMENT,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $commentOpenPointer
*/
public function process(File $phpcsFile, $commentOpenPointer): void
{
$tokens = $phpcsFile->getTokens();
$commentClosePointer = $tokens[$commentOpenPointer]['code'] === T_COMMENT
? $commentOpenPointer
: $tokens[$commentOpenPointer]['comment_closer'];
$pointerAfterCommentClosePointer = TokenHelper::findNextEffective($phpcsFile, $commentClosePointer + 1);
if ($pointerAfterCommentClosePointer !== null) {
do {
if ($tokens[$pointerAfterCommentClosePointer]['code'] !== T_ATTRIBUTE) {
break;
}
$pointerAfterCommentClosePointer = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$pointerAfterCommentClosePointer]['attribute_closer'] + 1
);
} while (true);
if (in_array(
$tokens[$pointerAfterCommentClosePointer]['code'],
[T_PRIVATE, T_PROTECTED, T_PUBLIC, T_READONLY, T_FINAL, T_CONST],
true
)) {
return;
}
if ($tokens[$pointerAfterCommentClosePointer]['code'] === T_STATIC) {
$pointerAfterStatic = TokenHelper::findNextEffective($phpcsFile, $pointerAfterCommentClosePointer + 1);
if (in_array($tokens[$pointerAfterStatic]['code'], [T_PRIVATE, T_PROTECTED, T_PUBLIC, T_READONLY], true)) {
return;
}
if ($tokens[$pointerAfterStatic]['code'] === T_VARIABLE && PropertyHelper::isProperty($phpcsFile, $pointerAfterStatic)) {
return;
}
}
}
if ($tokens[$commentOpenPointer]['code'] === T_COMMENT) {
$this->checkCommentType($phpcsFile, $commentOpenPointer);
return;
}
/** @var list<Annotation<VarTagValueNode>> $annotations */
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $commentOpenPointer, '@var');
if ($annotations === []) {
return;
}
if ($this->allowDocCommentAboveReturn) {
$pointerAfterCommentClosePointer = TokenHelper::findNextEffective($phpcsFile, $commentClosePointer + 1);
if ($tokens[$pointerAfterCommentClosePointer]['code'] === T_RETURN) {
return;
}
}
$this->checkFormat($phpcsFile, $annotations);
$this->checkVariable($phpcsFile, $annotations, $commentOpenPointer, $commentClosePointer);
}
private function checkCommentType(File $phpcsFile, int $commentOpenPointer): void
{
$tokens = $phpcsFile->getTokens();
if (preg_match('~^/\*\\s*@var\\s+~', $tokens[$commentOpenPointer]['content']) === 0) {
return;
}
$fix = $phpcsFile->addFixableError(
'Invalid comment type /* */ for inline documentation comment, use /** */.',
$commentOpenPointer,
self::CODE_INVALID_COMMENT_TYPE
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($commentOpenPointer, sprintf('/**%s', substr($tokens[$commentOpenPointer]['content'], 2)));
$phpcsFile->fixer->endChangeset();
}
/**
* @param list<Annotation<VarTagValueNode>> $annotations
*/
private function checkFormat(File $phpcsFile, array $annotations): void
{
foreach ($annotations as $annotation) {
if (!$annotation->isInvalid() && $annotation->getValue()->variableName !== '') {
continue;
}
$variableName = '$variableName';
$annotationContent = (string) $annotation->getValue();
$type = null;
if (
$annotationContent !== ''
&& preg_match('~(\$\w+)(?:\s+(.+))?$~i', $annotationContent, $matches) === 1
) {
$variableName = $matches[1];
$type = $matches[2] ?? null;
}
// It may be description when it contains whitespaces
$isFixable = $type !== null && preg_match('~\s~', $type) === 0;
if (!$isFixable) {
$phpcsFile->addError(
sprintf(
'Invalid inline documentation comment format "@var %1$s", expected "@var type %2$s Optional description".',
$annotationContent,
$variableName
),
$annotation->getStartPointer(),
self::CODE_INVALID_FORMAT
);
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Invalid inline documentation comment format "@var %1$s", expected "@var %2$s %3$s".',
$annotationContent,
$type,
$variableName
),
$annotation->getStartPointer(),
self::CODE_INVALID_FORMAT
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addContent(
$annotation->getStartPointer(),
sprintf(
' %s %s ',
$type,
$variableName
)
);
FixerHelper::removeBetweenIncluding($phpcsFile, $annotation->getStartPointer() + 1, $annotation->getEndPointer());
$phpcsFile->fixer->endChangeset();
}
}
/**
* @param list<Annotation<VarTagValueNode>> $annotations
*/
private function checkVariable(File $phpcsFile, array $annotations, int $docCommentOpenerPointer, int $docCommentCloserPointer): void
{
$tokens = $phpcsFile->getTokens();
$checkedTokens = [T_VARIABLE, T_FOREACH, T_WHILE, T_LIST, T_OPEN_SHORT_ARRAY, T_CLOSURE, T_FN];
$variableNames = [];
foreach ($annotations as $variableAnnotation) {
if ($variableAnnotation->isInvalid()) {
continue;
}
$variableName = $variableAnnotation->getValue()->variableName;
if ($variableName === '') {
continue;
}
$variableNames[] = $variableName;
}
$improveCodePointer = function (int $codePointer) use ($phpcsFile, $tokens, $checkedTokens, $variableNames): int {
$shouldSearchClosure = false;
if (!in_array($tokens[$codePointer]['code'], $checkedTokens, true)) {
$shouldSearchClosure = true;
} elseif (
$tokens[$codePointer]['code'] === T_VARIABLE
&& (
!$this->isAssignment($phpcsFile, $codePointer)
|| !in_array($tokens[$codePointer]['content'], $variableNames, true)
)
) {
$shouldSearchClosure = true;
}
if (!$shouldSearchClosure) {
return $codePointer;
}
$closurePointer = TokenHelper::findNext($phpcsFile, [T_CLOSURE, T_FN], $codePointer + 1);
if ($closurePointer !== null && $tokens[$codePointer]['line'] === $tokens[$closurePointer]['line']) {
return $closurePointer;
}
return $codePointer;
};
$firstPointerOnNextLine = TokenHelper::findFirstNonWhitespaceOnNextLine($phpcsFile, $docCommentCloserPointer);
$codePointerAfter = $firstPointerOnNextLine;
while ($codePointerAfter !== null && $tokens[$codePointerAfter]['code'] === T_DOC_COMMENT_OPEN_TAG) {
$codePointerAfter = TokenHelper::findFirstNonWhitespaceOnNextLine($phpcsFile, $codePointerAfter + 1);
}
if ($codePointerAfter !== null) {
if ($tokens[$codePointerAfter]['code'] === T_STATIC) {
$codePointerAfter = TokenHelper::findNextEffective($phpcsFile, $codePointerAfter + 1);
}
$codePointerAfter = $improveCodePointer($codePointerAfter);
}
$codePointerBefore = TokenHelper::findFirstNonWhitespaceOnPreviousLine($phpcsFile, $docCommentOpenerPointer);
while ($codePointerBefore !== null && $tokens[$codePointerBefore]['code'] === T_DOC_COMMENT_OPEN_TAG) {
$codePointerBefore = TokenHelper::findFirstNonWhitespaceOnPreviousLine($phpcsFile, $codePointerBefore - 1);
}
if ($codePointerBefore !== null) {
$codePointerBefore = $improveCodePointer($codePointerBefore);
}
foreach ($annotations as $variableAnnotation) {
if ($variableAnnotation->isInvalid()) {
continue;
}
$variableName = $variableAnnotation->getValue()->variableName;
if ($variableName === '') {
continue;
}
$missingVariableErrorParameters = [
sprintf('Missing variable %s before or after the documentation comment.', $variableName),
$docCommentOpenerPointer,
self::CODE_MISSING_VARIABLE,
];
$noAssignmentErrorParameters = [
sprintf('No assignment to %s variable before or after the documentation comment.', $variableName),
$docCommentOpenerPointer,
self::CODE_NO_ASSIGNMENT,
];
if ($this->allowAboveNonAssignment && $firstPointerOnNextLine !== null) {
for ($i = $firstPointerOnNextLine; $i < count($tokens); $i++) {
if ($tokens[$i]['line'] > $tokens[$firstPointerOnNextLine]['line']) {
break;
}
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
if ($tokens[$i]['content'] === $variableName) {
return;
}
}
}
foreach ([1 => $codePointerBefore, 2 => $codePointerAfter] as $tryNo => $codePointer) {
if ($codePointer === null || !in_array($tokens[$codePointer]['code'], $checkedTokens, true)) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
if ($tokens[$codePointer]['code'] === T_VARIABLE) {
if ($tokens[$codePointer]['content'] !== '$this' && !$this->isAssignment($phpcsFile, $codePointer)) {
if ($tryNo === 2) {
$phpcsFile->addError(...$noAssignmentErrorParameters);
}
continue;
}
if ($variableName !== $tokens[$codePointer]['content']) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
} elseif ($tokens[$codePointer]['code'] === T_LIST) {
$listParenthesisOpener = TokenHelper::findNextEffective($phpcsFile, $codePointer + 1);
$variablePointerInList = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$listParenthesisOpener + 1,
$tokens[$listParenthesisOpener]['parenthesis_closer']
);
if ($variablePointerInList === null) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
} elseif ($tokens[$codePointer]['code'] === T_OPEN_SHORT_ARRAY) {
$pointerAfterList = TokenHelper::findNextEffective($phpcsFile, $tokens[$codePointer]['bracket_closer'] + 1);
if ($tokens[$pointerAfterList]['code'] !== T_EQUAL) {
if ($tryNo === 2) {
$phpcsFile->addError(...$noAssignmentErrorParameters);
}
continue;
}
$variablePointerInList = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$codePointer + 1,
$tokens[$codePointer]['bracket_closer']
);
if ($variablePointerInList === null) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
} elseif (in_array($tokens[$codePointer]['code'], [T_CLOSURE, T_FN], true)) {
$parameterPointer = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$tokens[$codePointer]['parenthesis_opener'] + 1,
$tokens[$codePointer]['parenthesis_closer']
);
if ($parameterPointer === null) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
} else {
if ($tokens[$codePointer]['code'] === T_WHILE) {
$variablePointerInWhile = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$tokens[$codePointer]['parenthesis_opener'] + 1,
$tokens[$codePointer]['parenthesis_closer']
);
if ($variablePointerInWhile === null) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
$pointerAfterVariableInWhile = TokenHelper::findNextEffective($phpcsFile, $variablePointerInWhile + 1);
if ($tokens[$pointerAfterVariableInWhile]['code'] !== T_EQUAL) {
if ($tryNo === 2) {
$phpcsFile->addError(...$noAssignmentErrorParameters);
}
continue;
}
} else {
$asPointer = TokenHelper::findNext(
$phpcsFile,
T_AS,
$tokens[$codePointer]['parenthesis_opener'] + 1,
$tokens[$codePointer]['parenthesis_closer']
);
$variablePointerInForeach = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$asPointer + 1,
$tokens[$codePointer]['parenthesis_closer']
);
if ($variablePointerInForeach === null) {
if ($tryNo === 2) {
$phpcsFile->addError(...$missingVariableErrorParameters);
}
continue;
}
}
}
// No error, don't check second $codePointer
continue 2;
}
}
}
private function isAssignment(File $phpcsFile, int $pointer): bool
{
$tokens = $phpcsFile->getTokens();
$pointerAfterVariable = TokenHelper::findNextEffective($phpcsFile, $pointer + 1);
if ($tokens[$pointerAfterVariable]['code'] === T_SEMICOLON) {
$pointerBeforeVariable = TokenHelper::findPreviousEffective($phpcsFile, $pointer - 1);
return $tokens[$pointerBeforeVariable]['code'] === T_STATIC;
}
return in_array($tokens[$pointerAfterVariable]['code'], [T_EQUAL, T_COALESCE_EQUAL], true);
}
}
@@ -0,0 +1,19 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
class RequireOneLineDocCommentSniff extends AbstractRequireOneLineDocComment
{
public const CODE_MULTI_LINE_DOC_COMMENT = 'MultiLineDocComment';
protected function addError(File $phpcsFile, int $docCommentStartPointer): bool
{
$error = 'Found multi-line doc comment with single line content, use one-line doc comment instead.';
return $phpcsFile->addFixableError($error, $docCommentStartPointer, self::CODE_MULTI_LINE_DOC_COMMENT);
}
}
@@ -0,0 +1,61 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\PropertyHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function sprintf;
use const T_VARIABLE;
class RequireOneLinePropertyDocCommentSniff extends AbstractRequireOneLineDocComment
{
public const CODE_MULTI_LINE_PROPERTY_COMMENT = 'MultiLinePropertyComment';
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentStartPointer
*/
public function process(File $phpcsFile, $docCommentStartPointer): void
{
$propertyPointer = TokenHelper::findNext($phpcsFile, T_VARIABLE, $docCommentStartPointer + 1);
if ($propertyPointer === null) {
return;
}
// Not a property
if (!PropertyHelper::isProperty($phpcsFile, $propertyPointer)) {
return;
}
// Check that doc comment belongs to the found property
$propertyDocCommentStartPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $propertyPointer);
if ($propertyDocCommentStartPointer !== $docCommentStartPointer) {
return;
}
// Only validate properties without description
if (DocCommentHelper::hasDocCommentDescription($phpcsFile, $propertyPointer)) {
return;
}
parent::process($phpcsFile, $docCommentStartPointer);
}
protected function addError(File $phpcsFile, int $docCommentStartPointer): bool
{
$error = 'Found multi-line comment for property %s with single line content, use one-line comment instead.';
/** @var int $propertyPointer */
$propertyPointer = $phpcsFile->findNext(T_VARIABLE, $docCommentStartPointer);
return $phpcsFile->addFixableError(
sprintf($error, PropertyHelper::getFullyQualifiedName($phpcsFile, $propertyPointer)),
$docCommentStartPointer,
self::CODE_MULTI_LINE_PROPERTY_COMMENT
);
}
}
@@ -0,0 +1,143 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\FunctionHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function array_map;
use function in_array;
use function sprintf;
use const T_FUNCTION;
class UselessFunctionDocCommentSniff implements Sniff
{
public const CODE_USELESS_DOC_COMMENT = 'UselessDocComment';
/** @var list<string> */
public $traversableTypeHints = [];
/** @var array<int, string>|null */
private $normalizedTraversableTypeHints;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_FUNCTION,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $functionPointer
*/
public function process(File $phpcsFile, $functionPointer): void
{
if (!DocCommentHelper::hasDocComment($phpcsFile, $functionPointer)) {
return;
}
if (DocCommentHelper::hasInheritdocAnnotation($phpcsFile, $functionPointer)) {
return;
}
if (DocCommentHelper::hasDocCommentDescription($phpcsFile, $functionPointer)) {
return;
}
$returnTypeHint = FunctionHelper::findReturnTypeHint($phpcsFile, $functionPointer);
$returnAnnotation = FunctionHelper::findReturnAnnotation($phpcsFile, $functionPointer);
if (
$returnAnnotation !== null
&& !AnnotationHelper::isAnnotationUseless(
$phpcsFile,
$functionPointer,
$returnTypeHint,
$returnAnnotation,
$this->getTraversableTypeHints()
)
) {
return;
}
$parameterTypeHints = FunctionHelper::getParametersTypeHints($phpcsFile, $functionPointer);
$parametersAnnotations = FunctionHelper::getValidParametersAnnotations($phpcsFile, $functionPointer);
foreach ($parametersAnnotations as $parameterName => $parameterAnnotation) {
if (!array_key_exists($parameterName, $parameterTypeHints)) {
return;
}
if (!AnnotationHelper::isAnnotationUseless(
$phpcsFile,
$functionPointer,
$parameterTypeHints[$parameterName],
$parameterAnnotation,
$this->getTraversableTypeHints()
)) {
return;
}
}
foreach (AnnotationHelper::getAnnotations($phpcsFile, $functionPointer) as $annotation) {
if (!in_array($annotation->getName(), ['@param', '@return'], true)) {
return;
}
}
$fix = $phpcsFile->addFixableError(
sprintf(
'%s %s() does not need documentation comment.',
FunctionHelper::getTypeLabel($phpcsFile, $functionPointer),
FunctionHelper::getFullyQualifiedName($phpcsFile, $functionPointer)
),
$functionPointer,
self::CODE_USELESS_DOC_COMMENT
);
if (!$fix) {
return;
}
/** @var int $docCommentOpenPointer */
$docCommentOpenPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $functionPointer);
$docCommentClosePointer = $phpcsFile->getTokens()[$docCommentOpenPointer]['comment_closer'];
$changeStart = $docCommentOpenPointer;
/** @var int $changeEnd */
$changeEnd = TokenHelper::findNextEffective($phpcsFile, $docCommentClosePointer + 1) - 1;
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $changeStart, $changeEnd);
$phpcsFile->fixer->endChangeset();
}
/**
* @return array<int, string>
*/
private function getTraversableTypeHints(): array
{
if ($this->normalizedTraversableTypeHints === null) {
$this->normalizedTraversableTypeHints = array_map(static function (string $typeHint): string {
return NamespaceHelper::isFullyQualifiedName($typeHint)
? $typeHint
: sprintf('%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $typeHint);
}, SniffSettingsHelper::normalizeArray($this->traversableTypeHints));
}
return $this->normalizedTraversableTypeHints;
}
}
@@ -0,0 +1,118 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Commenting;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\FunctionHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\TypeHintHelper;
use function array_merge;
use function in_array;
use function preg_match;
use const T_ATTRIBUTE;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_WHITESPACE;
class UselessInheritDocCommentSniff implements Sniff
{
public const CODE_USELESS_INHERIT_DOC_COMMENT = 'UselessInheritDocComment';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_DOC_COMMENT_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $docCommentOpenPointer
*/
public function process(File $phpcsFile, $docCommentOpenPointer): void
{
$tokens = $phpcsFile->getTokens();
$docCommentContent = '';
for ($i = $docCommentOpenPointer + 1; $i < $tokens[$docCommentOpenPointer]['comment_closer']; $i++) {
if (in_array($tokens[$i]['code'], [T_DOC_COMMENT_WHITESPACE, T_DOC_COMMENT_STAR], true)) {
continue;
}
$docCommentContent .= $tokens[$i]['content'];
}
if (preg_match('~^(?:\{@inheritDoc\}|@inheritDoc)$~i', $docCommentContent) === 0) {
return;
}
$searchPointer = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
do {
$docCommentOwnerPointer = TokenHelper::findNext(
$phpcsFile,
array_merge(TokenHelper::$functionTokenCodes, TokenHelper::getTypeHintTokenCodes(), [T_ATTRIBUTE]),
$searchPointer
);
if ($docCommentOwnerPointer === null) {
return;
}
if ($tokens[$docCommentOwnerPointer]['code'] === T_ATTRIBUTE) {
$searchPointer = $tokens[$docCommentOwnerPointer]['attribute_closer'] + 1;
continue;
}
break;
} while (true);
if (in_array($tokens[$docCommentOwnerPointer]['code'], TokenHelper::$functionTokenCodes, true)) {
$returnTypeHint = FunctionHelper::findReturnTypeHint($phpcsFile, $docCommentOwnerPointer);
if ($returnTypeHint === null) {
return;
}
if (TypeHintHelper::isSimpleIterableTypeHint($returnTypeHint->getTypeHintWithoutNullabilitySymbol())) {
return;
}
$parametersTypeHints = FunctionHelper::getParametersTypeHints($phpcsFile, $docCommentOwnerPointer);
foreach ($parametersTypeHints as $parameterTypeHint) {
if ($parameterTypeHint === null) {
return;
}
if (TypeHintHelper::isSimpleIterableTypeHint($parameterTypeHint->getTypeHint())) {
return;
}
}
}
$fix = $phpcsFile->addFixableError(
'Useless documentation comment with @inheritDoc.',
$docCommentOpenPointer,
self::CODE_USELESS_INHERIT_DOC_COMMENT
);
if (!$fix) {
return;
}
/** @var int $fixerStart */
$fixerStart = TokenHelper::findLastTokenOnPreviousLine($phpcsFile, $docCommentOpenPointer);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $fixerStart, $tokens[$docCommentOpenPointer]['comment_closer']);
$phpcsFile->fixer->endChangeset();
}
}