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,172 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\ReferencedName;
use SlevomatCodingStandard\Helpers\ReferencedNameHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_flip;
use function array_key_exists;
use function array_map;
use function sprintf;
use function strtolower;
use const T_OPEN_TAG;
use const T_OPEN_USE_GROUP;
/**
* @internal
*/
abstract class AbstractFullyQualifiedGlobalReference implements Sniff
{
public const CODE_NON_FULLY_QUALIFIED = 'NonFullyQualified';
/** @var list<string> */
public $exclude = [];
/** @var list<string> */
public $include = [];
/** @var list<string>|null */
private $normalizedExclude;
/** @var list<string>|null */
private $normalizedInclude;
abstract protected function getNotFullyQualifiedMessage(): string;
abstract protected function isCaseSensitive(): bool;
abstract protected function isValidType(ReferencedName $name): bool;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
if (TokenHelper::findNext($phpcsFile, T_OPEN_USE_GROUP, $openTagPointer) !== null) {
return;
}
$tokens = $phpcsFile->getTokens();
$namespacePointers = NamespaceHelper::getAllNamespacesPointers($phpcsFile);
$referencedNames = ReferencedNameHelper::getAllReferencedNames($phpcsFile, $openTagPointer);
$include = array_flip($this->getNormalizedInclude());
$exclude = array_flip($this->getNormalizedExclude());
foreach ($referencedNames as $referencedName) {
$name = $referencedName->getNameAsReferencedInFile();
$namePointer = $referencedName->getStartPointer();
if (!$this->isValidType($referencedName)) {
continue;
}
if (NamespaceHelper::isFullyQualifiedName($name)) {
continue;
}
if (NamespaceHelper::hasNamespace($name)) {
continue;
}
if ($namespacePointers === []) {
continue;
}
$canonicalName = $this->isCaseSensitive() ? $name : strtolower($name);
$useStatements = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $namePointer);
if (array_key_exists(UseStatement::getUniqueId($referencedName->getType(), $canonicalName), $useStatements)) {
$fullyQualifiedName = NamespaceHelper::resolveName($phpcsFile, $name, $referencedName->getType(), $namePointer);
if (NamespaceHelper::hasNamespace($fullyQualifiedName)) {
continue;
}
}
if ($include !== [] && !array_key_exists($canonicalName, $include)) {
continue;
}
if (array_key_exists($canonicalName, $exclude)) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf($this->getNotFullyQualifiedMessage(), $tokens[$namePointer]['content']),
$namePointer,
self::CODE_NON_FULLY_QUALIFIED
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addContentBefore($namePointer, NamespaceHelper::NAMESPACE_SEPARATOR);
$phpcsFile->fixer->endChangeset();
}
}
/**
* @return list<string>
*/
protected function getNormalizedInclude(): array
{
if ($this->normalizedInclude === null) {
$this->normalizedInclude = $this->normalizeNames($this->include);
}
return $this->normalizedInclude;
}
/**
* @return list<string>
*/
private function getNormalizedExclude(): array
{
if ($this->normalizedExclude === null) {
$this->normalizedExclude = $this->normalizeNames($this->exclude);
}
return $this->normalizedExclude;
}
/**
* @param list<string> $names
* @return list<string>
*/
private function normalizeNames(array $names): array
{
$names = SniffSettingsHelper::normalizeArray($names);
if (!$this->isCaseSensitive()) {
$names = array_map(static function (string $name): string {
return strtolower($name);
}, $names);
}
return $names;
}
}
@@ -0,0 +1,240 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
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\NamespaceHelper;
use SlevomatCodingStandard\Helpers\StringHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_key_exists;
use function array_map;
use function count;
use function end;
use function explode;
use function implode;
use function in_array;
use function min;
use function reset;
use function sprintf;
use function strcasecmp;
use function strcmp;
use function uasort;
use const T_COMMA;
use const T_OPEN_TAG;
use const T_OPEN_USE_GROUP;
use const T_SEMICOLON;
class AlphabeticallySortedUsesSniff implements Sniff
{
public const CODE_INCORRECT_ORDER = 'IncorrectlyOrderedUses';
/** @var bool */
public $psr12Compatible = true;
/** @var bool */
public $caseSensitive = false;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
// If there are any 'use group' statements then we cannot sort and fix the file.
$groupUsePointer = TokenHelper::findNext($phpcsFile, T_OPEN_USE_GROUP, $openTagPointer);
if ($groupUsePointer !== null) {
return;
}
$fileUseStatements = UseStatementHelper::getFileUseStatements($phpcsFile);
foreach ($fileUseStatements as $useStatements) {
$lastUse = null;
foreach ($useStatements as $useStatement) {
if ($lastUse === null) {
$lastUse = $useStatement;
} else {
$order = $this->compareUseStatements($useStatement, $lastUse);
if ($order < 0) {
// The use statements are not ordered correctly. Go through all statements and if any are multi-part then
// we report the problem but cannot fix it, because this would lose the secondary parts of the statement.
$fixable = true;
$tokens = $phpcsFile->getTokens();
foreach ($useStatements as $statement) {
$nextBreaker = TokenHelper::findNext($phpcsFile, [T_SEMICOLON, T_COMMA], $statement->getPointer());
if ($tokens[$nextBreaker]['code'] === T_COMMA) {
$fixable = false;
break;
}
}
$errorParameters = [
sprintf(
'Use statements should be sorted alphabetically. The first wrong one is %s.',
$useStatement->getFullyQualifiedTypeName()
),
$useStatement->getPointer(),
self::CODE_INCORRECT_ORDER,
];
if (!$fixable) {
$phpcsFile->addError(...$errorParameters);
return;
}
$fix = $phpcsFile->addFixableError(...$errorParameters);
if ($fix) {
$this->fixAlphabeticalOrder($phpcsFile, $useStatements);
}
return;
}
$lastUse = $useStatement;
}
}
}
}
/**
* @param array<string, UseStatement> $useStatements
*/
private function fixAlphabeticalOrder(File $phpcsFile, array $useStatements): void
{
/** @var UseStatement $firstUseStatement */
$firstUseStatement = reset($useStatements);
/** @var UseStatement $lastUseStatement */
$lastUseStatement = end($useStatements);
$lastSemicolonPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $lastUseStatement->getPointer());
$firstPointer = $firstUseStatement->getPointer();
$tokens = $phpcsFile->getTokens();
$commentsBefore = [];
foreach ($useStatements as $useStatement) {
$pointerBeforeUseStatement = TokenHelper::findPreviousNonWhitespace($phpcsFile, $useStatement->getPointer() - 1);
if (!in_array($tokens[$pointerBeforeUseStatement]['code'], Tokens::$commentTokens, true)) {
continue;
}
$commentAndWhitespace = TokenHelper::getContent($phpcsFile, $pointerBeforeUseStatement, $useStatement->getPointer() - 1);
if (StringHelper::endsWith($commentAndWhitespace, $phpcsFile->eolChar . $phpcsFile->eolChar)) {
continue;
}
$commentStartPointer = in_array($tokens[$pointerBeforeUseStatement]['code'], TokenHelper::$inlineCommentTokenCodes, true)
? CommentHelper::getMultilineCommentStartPointer($phpcsFile, $pointerBeforeUseStatement)
: $tokens[$pointerBeforeUseStatement]['comment_opener'];
$commentsBefore[$useStatement->getPointer()] = TokenHelper::getContent(
$phpcsFile,
$commentStartPointer,
$pointerBeforeUseStatement
);
if ($firstPointer === $useStatement->getPointer()) {
$firstPointer = $commentStartPointer;
}
}
uasort($useStatements, function (UseStatement $a, UseStatement $b): int {
return $this->compareUseStatements($a, $b);
});
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $firstPointer, $lastSemicolonPointer);
$phpcsFile->fixer->addContent(
$firstPointer,
implode($phpcsFile->eolChar, array_map(static function (UseStatement $useStatement) use ($phpcsFile, $commentsBefore): string {
$unqualifiedName = NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($useStatement->getFullyQualifiedTypeName());
$useTypeName = UseStatement::getTypeName($useStatement->getType());
$useTypeFormatted = $useTypeName !== null ? sprintf('%s ', $useTypeName) : '';
$commentBefore = '';
if (array_key_exists($useStatement->getPointer(), $commentsBefore)) {
$commentBefore = $commentsBefore[$useStatement->getPointer()];
if (!StringHelper::endsWith($commentBefore, $phpcsFile->eolChar)) {
$commentBefore .= $phpcsFile->eolChar;
}
}
if ($unqualifiedName === $useStatement->getNameAsReferencedInFile()) {
return sprintf('%suse %s%s;', $commentBefore, $useTypeFormatted, $useStatement->getFullyQualifiedTypeName());
}
return sprintf(
'%suse %s%s as %s;',
$commentBefore,
$useTypeFormatted,
$useStatement->getFullyQualifiedTypeName(),
$useStatement->getNameAsReferencedInFile()
);
}, $useStatements))
);
$phpcsFile->fixer->endChangeset();
}
private function compareUseStatements(UseStatement $a, UseStatement $b): int
{
if (!$a->hasSameType($b)) {
$order = [
UseStatement::TYPE_CLASS => 1,
UseStatement::TYPE_FUNCTION => $this->psr12Compatible ? 2 : 3,
UseStatement::TYPE_CONSTANT => $this->psr12Compatible ? 3 : 2,
];
return $order[$a->getType()] <=> $order[$b->getType()];
}
$aNameParts = explode(NamespaceHelper::NAMESPACE_SEPARATOR, $a->getFullyQualifiedTypeName());
$bNameParts = explode(NamespaceHelper::NAMESPACE_SEPARATOR, $b->getFullyQualifiedTypeName());
$minPartsCount = min(count($aNameParts), count($bNameParts));
for ($i = 0; $i < $minPartsCount; $i++) {
$comparison = $this->compare($aNameParts[$i], $bNameParts[$i]);
if ($comparison === 0) {
continue;
}
return $comparison;
}
return count($aNameParts) <=> count($bNameParts);
}
private function compare(string $a, string $b): int
{
if ($this->caseSensitive) {
return strcmp($a, $b);
}
return strcasecmp($a, $b);
}
}
@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use const T_OPEN_USE_GROUP;
class DisallowGroupUseSniff implements Sniff
{
public const CODE_DISALLOWED_GROUP_USE = 'DisallowedGroupUse';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_USE_GROUP,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $usePointer
*/
public function process(File $phpcsFile, $usePointer): void
{
$phpcsFile->addError(
'Group use declaration is disallowed, use single use for every import.',
$usePointer,
self::CODE_DISALLOWED_GROUP_USE
);
}
}
@@ -0,0 +1,173 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\PhpDocParserHelper;
use SlevomatCodingStandard\Helpers\ReferencedName;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TypeHelper;
use SlevomatCodingStandard\Helpers\TypeHintHelper;
use function in_array;
use function sprintf;
use function strtolower;
use const T_DOC_COMMENT_OPEN_TAG;
class FullyQualifiedClassNameInAnnotationSniff implements Sniff
{
public const CODE_NON_FULLY_QUALIFIED_CLASS_NAME = 'NonFullyQualifiedClassName';
/** @var list<string> */
public $ignoredAnnotationNames = [];
/**
* @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);
$this->ignoredAnnotationNames = SniffSettingsHelper::normalizeArray($this->ignoredAnnotationNames);
foreach ($annotations as $annotation) {
/** @var list<IdentifierTypeNode> $identifierTypeNodes */
$identifierTypeNodes = AnnotationHelper::getAnnotationNodesByType($annotation->getNode(), IdentifierTypeNode::class);
$annotationName = $annotation->getName();
foreach ($identifierTypeNodes as $typeHintNode) {
$typeHint = $typeHintNode->name;
$lowercasedTypeHint = strtolower($typeHint);
if (
TypeHintHelper::isSimpleTypeHint($lowercasedTypeHint)
|| TypeHintHelper::isSimpleUnofficialTypeHints($lowercasedTypeHint)
|| !TypeHelper::isTypeName($typeHint)
|| TypeHintHelper::isTypeDefinedInAnnotation($phpcsFile, $docCommentOpenPointer, $typeHint)
) {
continue;
}
if (in_array($annotationName, $this->ignoredAnnotationNames, true)) {
continue;
}
$fullyQualifiedTypeHint = TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $docCommentOpenPointer, $typeHint);
if ($fullyQualifiedTypeHint === $typeHint) {
continue;
}
$fix = $phpcsFile->addFixableError(sprintf(
'Class name %s in %s should be referenced via a fully qualified name.',
$fullyQualifiedTypeHint,
$annotationName
), $annotation->getStartPointer(), self::CODE_NON_FULLY_QUALIFIED_CLASS_NAME);
if (!$fix) {
continue;
}
$parsedDocComment = DocCommentHelper::parseDocComment($phpcsFile, $docCommentOpenPointer);
$fixedDocComment = AnnotationHelper::fixAnnotation(
$parsedDocComment,
$annotation,
$typeHintNode,
new IdentifierTypeNode($fullyQualifiedTypeHint)
);
$phpcsFile->fixer->beginChangeset();
FixerHelper::change(
$phpcsFile,
$parsedDocComment->getOpenPointer(),
$parsedDocComment->getClosePointer(),
$fixedDocComment
);
$phpcsFile->fixer->endChangeset();
}
/** @var list<ConstFetchNode> $constantFetchNodes */
$constantFetchNodes = AnnotationHelper::getAnnotationNodesByType($annotation->getNode(), ConstFetchNode::class);
foreach ($constantFetchNodes as $constantFetchNode) {
$isClassConstant = $constantFetchNode->className !== '';
$typeHint = $isClassConstant
? $constantFetchNode->className
: $constantFetchNode->name;
if ($typeHint === 'self') {
continue;
}
$fullyQualifiedTypeHint = $isClassConstant
? NamespaceHelper::resolveClassName($phpcsFile, $typeHint, $docCommentOpenPointer)
: NamespaceHelper::resolveName($phpcsFile, $typeHint, ReferencedName::TYPE_CONSTANT, $docCommentOpenPointer);
if ($fullyQualifiedTypeHint === $typeHint) {
continue;
}
$fix = $phpcsFile->addFixableError(sprintf(
'%s name %s in %s should be referenced via a fully qualified name.',
$isClassConstant ? 'Class' : 'Constant',
$fullyQualifiedTypeHint,
$annotationName
), $annotation->getStartPointer(), self::CODE_NON_FULLY_QUALIFIED_CLASS_NAME);
if (!$fix) {
continue;
}
$fixedConstantFetchNode = PhpDocParserHelper::cloneNode($constantFetchNode);
if ($isClassConstant) {
$fixedConstantFetchNode->className = $fullyQualifiedTypeHint;
} else {
$fixedConstantFetchNode->name = $fullyQualifiedTypeHint;
}
$parsedDocComment = DocCommentHelper::parseDocComment($phpcsFile, $docCommentOpenPointer);
$fixedDocComment = AnnotationHelper::fixAnnotation(
$parsedDocComment,
$annotation,
$constantFetchNode,
$fixedConstantFetchNode
);
$phpcsFile->fixer->beginChangeset();
FixerHelper::change(
$phpcsFile,
$parsedDocComment->getOpenPointer(),
$parsedDocComment->getClosePointer(),
$fixedDocComment
);
$phpcsFile->fixer->endChangeset();
}
}
}
}
@@ -0,0 +1,162 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\ReferencedNameHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\StringHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use Throwable;
use function array_reverse;
use function in_array;
use function sprintf;
use const T_OPEN_TAG;
class FullyQualifiedExceptionsSniff implements Sniff
{
public const CODE_NON_FULLY_QUALIFIED_EXCEPTION = 'NonFullyQualifiedException';
/** @var list<string> */
public $specialExceptionNames = [];
/** @var list<string> */
public $ignoredNames = [];
/** @var list<string>|null */
private $normalizedSpecialExceptionNames;
/** @var list<string>|null */
private $normalizedIgnoredNames;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
$namespacePointers = array_reverse(NamespaceHelper::getAllNamespacesPointers($phpcsFile));
$referencedNames = ReferencedNameHelper::getAllReferencedNames($phpcsFile, $openTagPointer);
foreach ($referencedNames as $referencedName) {
$pointer = $referencedName->getStartPointer();
$name = $referencedName->getNameAsReferencedInFile();
$uniqueId = UseStatement::getUniqueId($referencedName->getType(), $name);
$useStatements = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $pointer);
if (
isset($useStatements[$uniqueId])
&& $referencedName->hasSameUseStatementType($useStatements[$uniqueId])
) {
$useStatement = $useStatements[$uniqueId];
if (
in_array($useStatement->getFullyQualifiedTypeName(), $this->getIgnoredNames(), true)
|| (
!StringHelper::endsWith($useStatement->getFullyQualifiedTypeName(), 'Exception')
&& $useStatement->getFullyQualifiedTypeName() !== Throwable::class
&& (!StringHelper::endsWith($useStatement->getFullyQualifiedTypeName(), 'Error') || NamespaceHelper::hasNamespace(
$useStatement->getFullyQualifiedTypeName()
))
&& !in_array($useStatement->getFullyQualifiedTypeName(), $this->getSpecialExceptionNames(), true)
)
) {
continue;
}
} else {
$fileNamespacePointer = null;
if ($namespacePointers !== []) {
foreach ($namespacePointers as $namespacePointer) {
if ($namespacePointer < $pointer) {
$fileNamespacePointer = $namespacePointer;
break;
}
}
}
$fileNamespace = $fileNamespacePointer !== null
? NamespaceHelper::getName($phpcsFile, $fileNamespacePointer)
: null;
$canonicalName = $name;
if (!NamespaceHelper::isFullyQualifiedName($name) && $fileNamespace !== null) {
$canonicalName = sprintf('%s%s%s', $fileNamespace, NamespaceHelper::NAMESPACE_SEPARATOR, $name);
}
if (
in_array($canonicalName, $this->getIgnoredNames(), true)
|| (
!StringHelper::endsWith($name, 'Exception')
&& $name !== Throwable::class
&& (!StringHelper::endsWith($canonicalName, 'Error') || NamespaceHelper::hasNamespace($canonicalName))
&& !in_array($canonicalName, $this->getSpecialExceptionNames(), true)
)
) {
continue;
}
}
if (NamespaceHelper::isFullyQualifiedName($name)) {
continue;
}
$fix = $phpcsFile->addFixableError(sprintf(
'Exception %s should be referenced via a fully qualified name.',
$name
), $pointer, self::CODE_NON_FULLY_QUALIFIED_EXCEPTION);
if (!$fix) {
continue;
}
$fullyQualifiedName = NamespaceHelper::resolveClassName($phpcsFile, $name, $pointer);
$phpcsFile->fixer->beginChangeset();
FixerHelper::change($phpcsFile, $referencedName->getStartPointer(), $referencedName->getEndPointer(), $fullyQualifiedName);
$phpcsFile->fixer->endChangeset();
}
}
/**
* @return list<string>
*/
private function getSpecialExceptionNames(): array
{
if ($this->normalizedSpecialExceptionNames === null) {
$this->normalizedSpecialExceptionNames = SniffSettingsHelper::normalizeArray($this->specialExceptionNames);
}
return $this->normalizedSpecialExceptionNames;
}
/**
* @return list<string>
*/
private function getIgnoredNames(): array
{
if ($this->normalizedIgnoredNames === null) {
$this->normalizedIgnoredNames = SniffSettingsHelper::normalizeArray($this->ignoredNames);
}
return $this->normalizedIgnoredNames;
}
}
@@ -0,0 +1,26 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use SlevomatCodingStandard\Helpers\ReferencedName;
class FullyQualifiedGlobalConstantsSniff
extends AbstractFullyQualifiedGlobalReference
{
protected function getNotFullyQualifiedMessage(): string
{
return 'Constant %s should be referenced via a fully qualified name.';
}
protected function isCaseSensitive(): bool
{
return true;
}
protected function isValidType(ReferencedName $name): bool
{
return $name->isConstant();
}
}
@@ -0,0 +1,45 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use SlevomatCodingStandard\Helpers\FunctionHelper;
use SlevomatCodingStandard\Helpers\ReferencedName;
use function array_merge;
class FullyQualifiedGlobalFunctionsSniff
extends AbstractFullyQualifiedGlobalReference
{
/** @var bool */
public $includeSpecialFunctions = false;
/**
* @return list<string>
*/
protected function getNormalizedInclude(): array
{
$include = parent::getNormalizedInclude();
if ($this->includeSpecialFunctions) {
$include = array_merge($include, FunctionHelper::SPECIAL_FUNCTIONS);
}
return $include;
}
protected function getNotFullyQualifiedMessage(): string
{
return 'Function %s() should be referenced via a fully qualified name.';
}
protected function isCaseSensitive(): bool
{
return false;
}
protected function isValidType(ReferencedName $name): bool
{
return $name->isFunction();
}
}
@@ -0,0 +1,48 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use const T_COMMA;
use const T_SEMICOLON;
use const T_USE;
class MultipleUsesPerLineSniff implements Sniff
{
public const CODE_MULTIPLE_USES_PER_LINE = 'MultipleUsesPerLine';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_USE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $usePointer
*/
public function process(File $phpcsFile, $usePointer): void
{
if (!UseStatementHelper::isImportUse($phpcsFile, $usePointer)) {
return;
}
$endPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $usePointer + 1);
$commaPointer = TokenHelper::findNext($phpcsFile, T_COMMA, $usePointer + 1, $endPointer);
if ($commaPointer === null) {
return;
}
$phpcsFile->addError('Multiple used types per use statement are forbidden.', $commaPointer, self::CODE_MULTIPLE_USES_PER_LINE);
}
}
@@ -0,0 +1,147 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function sprintf;
use function strlen;
use const T_NAMESPACE;
use const T_NS_SEPARATOR;
use const T_SEMICOLON;
use const T_WHITESPACE;
class NamespaceDeclarationSniff implements Sniff
{
public const CODE_INVALID_WHITESPACE_AFTER_NAMESPACE = 'InvalidWhitespaceAfterNamespace';
public const CODE_DISALLOWED_CONTENT_BETWEEN_NAMESPACE_NAME_AND_SEMICOLON = 'DisallowedContentBetweenNamespaceNameAndSemicolon';
public const CODE_DISALLOWED_BRACKETED_SYNTAX = 'DisallowedBracketedSyntax';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_NAMESPACE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $namespacePointer
*/
public function process(File $phpcsFile, $namespacePointer): void
{
$tokens = $phpcsFile->getTokens();
$pointerAfterNamespace = TokenHelper::findNextEffective($phpcsFile, $namespacePointer + 1);
if ($tokens[$pointerAfterNamespace]['code'] === T_NS_SEPARATOR) {
return;
}
$this->checkWhitespaceAfterNamespace($phpcsFile, $namespacePointer);
$this->checkDisallowedContentBetweenNamespaceNameAndSemicolon($phpcsFile, $namespacePointer);
$this->checkDisallowedBracketedSyntax($phpcsFile, $namespacePointer);
}
private function checkWhitespaceAfterNamespace(File $phpcsFile, int $namespacePointer): void
{
$tokens = $phpcsFile->getTokens();
$whitespacePointer = $namespacePointer + 1;
if ($tokens[$whitespacePointer]['code'] !== T_WHITESPACE) {
$phpcsFile->addError(
'Expected one space after namespace statement.',
$namespacePointer,
self::CODE_INVALID_WHITESPACE_AFTER_NAMESPACE
);
return;
}
if ($tokens[$whitespacePointer]['content'] === ' ') {
return;
}
$errorMessage = $tokens[$whitespacePointer]['content'][0] === "\t"
? 'Expected one space after namespace statement, found tab.'
: sprintf('Expected one space after namespace statement, found %d.', strlen($tokens[$whitespacePointer]['content']));
$fix = $phpcsFile->addFixableError($errorMessage, $namespacePointer, self::CODE_INVALID_WHITESPACE_AFTER_NAMESPACE);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($whitespacePointer, ' ');
$phpcsFile->fixer->endChangeset();
}
private function checkDisallowedContentBetweenNamespaceNameAndSemicolon(File $phpcsFile, int $namespacePointer): void
{
if (array_key_exists('scope_opener', $phpcsFile->getTokens()[$namespacePointer])) {
return;
}
$namespaceNameStartPointer = TokenHelper::findNextEffective($phpcsFile, $namespacePointer + 1);
$namespaceNameEndPointer = TokenHelper::findNextExcluding(
$phpcsFile,
TokenHelper::getNameTokenCodes(),
$namespaceNameStartPointer + 1
) - 1;
/** @var int $namespaceSemicolonPointer */
$namespaceSemicolonPointer = TokenHelper::findNextLocal($phpcsFile, T_SEMICOLON, $namespaceNameEndPointer + 1);
if ($namespaceNameEndPointer + 1 === $namespaceSemicolonPointer) {
return;
}
$fix = $phpcsFile->addFixableError(
'Disallowed content between namespace name and semicolon.',
$namespacePointer,
self::CODE_DISALLOWED_CONTENT_BETWEEN_NAMESPACE_NAME_AND_SEMICOLON
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $namespaceNameEndPointer, $namespaceSemicolonPointer);
$phpcsFile->fixer->endChangeset();
}
private function checkDisallowedBracketedSyntax(File $phpcsFile, int $namespacePointer): void
{
$tokens = $phpcsFile->getTokens();
if (!array_key_exists('scope_opener', $tokens[$namespacePointer])) {
return;
}
$fix = $phpcsFile->addFixableError(
'Bracketed syntax for namespaces is disallowed.',
$namespacePointer,
self::CODE_DISALLOWED_BRACKETED_SYNTAX
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($tokens[$namespacePointer]['scope_opener'], ';');
$phpcsFile->fixer->replaceToken($tokens[$namespacePointer]['scope_closer'], '');
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,164 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function preg_match;
use function rtrim;
use function sprintf;
use function strlen;
use function substr;
use function substr_count;
use const T_NAMESPACE;
use const T_OPEN_TAG;
use const T_SEMICOLON;
class NamespaceSpacingSniff implements Sniff
{
public const CODE_INCORRECT_LINES_COUNT_BEFORE_NAMESPACE = 'IncorrectLinesCountBeforeNamespace';
public const CODE_INCORRECT_LINES_COUNT_AFTER_NAMESPACE = 'IncorrectLinesCountAfterNamespace';
/** @var int */
public $linesCountBeforeNamespace = 1;
/** @var int */
public $linesCountAfterNamespace = 1;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_NAMESPACE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $namespacePointer
*/
public function process(File $phpcsFile, $namespacePointer): void
{
$this->linesCountBeforeNamespace = SniffSettingsHelper::normalizeInteger($this->linesCountBeforeNamespace);
$this->linesCountAfterNamespace = SniffSettingsHelper::normalizeInteger($this->linesCountAfterNamespace);
$this->checkLinesBeforeNamespace($phpcsFile, $namespacePointer);
$this->checkLinesAfterNamespace($phpcsFile, $namespacePointer);
}
private function checkLinesBeforeNamespace(File $phpcsFile, int $namespacePointer): void
{
$tokens = $phpcsFile->getTokens();
/** @var int $pointerBeforeNamespace */
$pointerBeforeNamespace = TokenHelper::findPreviousNonWhitespace($phpcsFile, $namespacePointer - 1);
$whitespaceBeforeNamespace = '';
$isInlineCommentBefore = (bool) preg_match('~^(?://|#)(.*)~', $tokens[$pointerBeforeNamespace]['content']);
if ($tokens[$pointerBeforeNamespace]['code'] === T_OPEN_TAG) {
$whitespaceBeforeNamespace .= substr($tokens[$pointerBeforeNamespace]['content'], strlen('<?php'));
} elseif ($isInlineCommentBefore) {
$whitespaceBeforeNamespace .= $phpcsFile->eolChar;
}
if ($pointerBeforeNamespace + 1 !== $namespacePointer) {
$whitespaceBeforeNamespace .= TokenHelper::getContent($phpcsFile, $pointerBeforeNamespace + 1, $namespacePointer - 1);
}
$actualLinesCountBeforeNamespace = substr_count($whitespaceBeforeNamespace, $phpcsFile->eolChar) - 1;
if ($actualLinesCountBeforeNamespace === $this->linesCountBeforeNamespace) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s before namespace statement, found %d.',
$this->linesCountBeforeNamespace,
$this->linesCountBeforeNamespace === 1 ? '' : 's',
$actualLinesCountBeforeNamespace
),
$namespacePointer,
self::CODE_INCORRECT_LINES_COUNT_BEFORE_NAMESPACE
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
if ($tokens[$pointerBeforeNamespace]['code'] === T_OPEN_TAG) {
$phpcsFile->fixer->replaceToken($pointerBeforeNamespace, '<?php');
} elseif ($isInlineCommentBefore) {
$phpcsFile->fixer->replaceToken(
$pointerBeforeNamespace,
rtrim($tokens[$pointerBeforeNamespace]['content'], $phpcsFile->eolChar)
);
}
FixerHelper::removeBetween($phpcsFile, $pointerBeforeNamespace, $namespacePointer);
for ($i = 0; $i <= $this->linesCountBeforeNamespace; $i++) {
$phpcsFile->fixer->addNewline($pointerBeforeNamespace);
}
$phpcsFile->fixer->endChangeset();
}
private function checkLinesAfterNamespace(File $phpcsFile, int $namespacePointer): void
{
if (array_key_exists('scope_opener', $phpcsFile->getTokens()[$namespacePointer])) {
return;
}
/** @var int $namespaceSemicolonPointer */
$namespaceSemicolonPointer = TokenHelper::findNextLocal($phpcsFile, T_SEMICOLON, $namespacePointer + 1);
$pointerAfterWhitespaceEnd = TokenHelper::findNextNonWhitespace($phpcsFile, $namespaceSemicolonPointer + 1);
if ($pointerAfterWhitespaceEnd === null) {
return;
}
$whitespaceAfterNamespace = TokenHelper::getContent($phpcsFile, $namespaceSemicolonPointer + 1, $pointerAfterWhitespaceEnd - 1);
$actualLinesCountAfterNamespace = substr_count($whitespaceAfterNamespace, $phpcsFile->eolChar) - 1;
if ($actualLinesCountAfterNamespace === $this->linesCountAfterNamespace) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s after namespace statement, found %d.',
$this->linesCountAfterNamespace,
$this->linesCountAfterNamespace === 1 ? '' : 's',
$actualLinesCountAfterNamespace
),
$namespacePointer,
self::CODE_INCORRECT_LINES_COUNT_AFTER_NAMESPACE
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $namespaceSemicolonPointer, $pointerAfterWhitespaceEnd);
for ($i = 0; $i <= $this->linesCountAfterNamespace; $i++) {
$phpcsFile->fixer->addNewline($namespaceSemicolonPointer);
}
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,779 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\ClassHelper;
use SlevomatCodingStandard\Helpers\CommentHelper;
use SlevomatCodingStandard\Helpers\ConstantHelper;
use SlevomatCodingStandard\Helpers\DocCommentHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\FunctionHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\ReferencedName;
use SlevomatCodingStandard\Helpers\ReferencedNameHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\StringHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\TypeHelper;
use SlevomatCodingStandard\Helpers\TypeHintHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use stdClass;
use function array_filter;
use function array_flip;
use function array_key_exists;
use function array_map;
use function array_reduce;
use function array_values;
use function count;
use function defined;
use function function_exists;
use function in_array;
use function preg_quote;
use function preg_replace;
use function sprintf;
use function strpos;
use function strtolower;
use function substr;
use const T_DECLARE;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_NAMESPACE;
use const T_OPEN_CURLY_BRACKET;
use const T_OPEN_TAG;
use const T_SEMICOLON;
use const T_WHITESPACE;
class ReferenceUsedNamesOnlySniff implements Sniff
{
public const CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME = 'ReferenceViaFullyQualifiedName';
public const CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME_WITHOUT_NAMESPACE = 'ReferenceViaFullyQualifiedNameWithoutNamespace';
public const CODE_REFERENCE_VIA_FALLBACK_GLOBAL_NAME = 'ReferenceViaFallbackGlobalName';
public const CODE_PARTIAL_USE = 'PartialUse';
private const SOURCE_CODE = 1;
private const SOURCE_ANNOTATION = 2;
private const SOURCE_ANNOTATION_CONSTANT_FETCH = 3;
private const SOURCE_ATTRIBUTE = 4;
/** @var bool */
public $searchAnnotations = false;
/** @var bool */
public $allowFullyQualifiedExceptions = false;
/** @var bool */
public $allowFullyQualifiedGlobalClasses = false;
/** @var bool */
public $allowFullyQualifiedGlobalFunctions = false;
/** @var bool */
public $allowFallbackGlobalFunctions = true;
/** @var bool */
public $allowFullyQualifiedGlobalConstants = false;
/** @var bool */
public $allowFallbackGlobalConstants = true;
/** @var list<string> */
public $specialExceptionNames = [];
/** @var list<string> */
public $ignoredNames = [];
/** @var bool */
public $allowPartialUses = true;
/**
* If empty, all namespaces are required to be used
*
* @var list<string>
*/
public $namespacesRequiredToUse = [];
/** @var bool */
public $allowFullyQualifiedNameForCollidingClasses = false;
/** @var bool */
public $allowFullyQualifiedNameForCollidingFunctions = false;
/** @var bool */
public $allowFullyQualifiedNameForCollidingConstants = false;
/** @var list<string>|null */
private $normalizedSpecialExceptionNames;
/** @var list<string>|null */
private $normalizedIgnoredNames;
/** @var list<string>|null */
private $normalizedNamespacesRequiredToUse;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
$tokens = $phpcsFile->getTokens();
$references = $this->getReferences($phpcsFile, $openTagPointer);
$definedClassesIndex = [];
foreach (ClassHelper::getAllNames($phpcsFile) as $definedClassPointer => $definedClassName) {
$definedClassesIndex[strtolower($definedClassName)] = NamespaceHelper::resolveClassName(
$phpcsFile,
$definedClassName,
$definedClassPointer
);
}
$definedFunctionsIndex = array_flip(array_map(static function (string $functionName): string {
return strtolower($functionName);
}, FunctionHelper::getAllFunctionNames($phpcsFile)));
$definedConstantsIndex = array_flip(ConstantHelper::getAllNames($phpcsFile));
$classReferencesIndex = [];
$classReferences = array_filter($references, static function (stdClass $reference): bool {
return $reference->source === self::SOURCE_CODE && $reference->isClass;
});
foreach ($classReferences as $classReference) {
$classReferencesIndex[strtolower($classReference->name)] = NamespaceHelper::resolveName(
$phpcsFile,
$classReference->name,
$classReference->type,
$classReference->startPointer
);
}
$namespacePointers = NamespaceHelper::getAllNamespacesPointers($phpcsFile);
$referenceErrors = [];
foreach ($references as $reference) {
$useStatements = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $reference->startPointer);
$name = $reference->name;
/** @var int $startPointer */
$startPointer = $reference->startPointer;
$canonicalName = NamespaceHelper::normalizeToCanonicalName($name);
$unqualifiedName = NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($name);
if (in_array(strtolower($unqualifiedName), ['true', 'false', 'null'], true)) {
continue;
}
$collidingUseStatementUniqueId = UseStatement::getUniqueId($reference->type, $unqualifiedName);
$isPartialUse = false;
foreach ($useStatements as $useStatement) {
$useStatementName = $useStatement->getAlias() ?? $useStatement->getNameAsReferencedInFile();
if (strpos($name, $useStatementName . '\\') === 0) {
$isPartialUse = true;
break;
}
}
$isFullyQualified = NamespaceHelper::isFullyQualifiedName($name)
|| ($namespacePointers === [] && NamespaceHelper::hasNamespace($name) && !$isPartialUse);
$isGlobalFallback = !$isFullyQualified
&& !NamespaceHelper::hasNamespace($name)
&& $namespacePointers !== []
&& !array_key_exists(UseStatement::getUniqueId($reference->type, $name), $useStatements);
$isGlobalFunctionFallback = false;
if ($reference->isFunction && $isGlobalFallback) {
$isGlobalFunctionFallback = !array_key_exists(strtolower($reference->name), $definedFunctionsIndex) && function_exists(
$reference->name
);
}
$isGlobalConstantFallback = false;
if ($reference->isConstant && $isGlobalFallback) {
$isGlobalConstantFallback = !array_key_exists($reference->name, $definedConstantsIndex) && defined($reference->name);
}
if ($isFullyQualified) {
if ($reference->isClass && $this->allowFullyQualifiedNameForCollidingClasses) {
$lowerCasedUnqualifiedClassName = strtolower($unqualifiedName);
if (
array_key_exists($lowerCasedUnqualifiedClassName, $definedClassesIndex)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName(
$definedClassesIndex[$lowerCasedUnqualifiedClassName]
)
) {
continue;
}
if (
array_key_exists($lowerCasedUnqualifiedClassName, $classReferencesIndex)
&& $name !== $classReferencesIndex[$lowerCasedUnqualifiedClassName]
) {
continue;
}
if (
array_key_exists($collidingUseStatementUniqueId, $useStatements)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName(
$useStatements[$collidingUseStatementUniqueId]->getFullyQualifiedTypeName()
)
) {
continue;
}
} elseif ($reference->isFunction && $this->allowFullyQualifiedNameForCollidingFunctions) {
$lowerCasedUnqualifiedFunctionName = strtolower($unqualifiedName);
if (array_key_exists($lowerCasedUnqualifiedFunctionName, $definedFunctionsIndex)) {
continue;
}
if (
array_key_exists($collidingUseStatementUniqueId, $useStatements)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName(
$useStatements[$collidingUseStatementUniqueId]->getFullyQualifiedTypeName()
)
) {
continue;
}
} elseif ($reference->isConstant && $this->allowFullyQualifiedNameForCollidingConstants) {
if (array_key_exists($unqualifiedName, $definedConstantsIndex)) {
continue;
}
if (
array_key_exists($collidingUseStatementUniqueId, $useStatements)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName(
$useStatements[$collidingUseStatementUniqueId]->getFullyQualifiedTypeName()
)
) {
continue;
}
}
}
if ($isFullyQualified || $isGlobalFunctionFallback || $isGlobalConstantFallback) {
if ($isFullyQualified && !$this->isRequiredToBeUsed($name)) {
continue;
}
$isExceptionByName = StringHelper::endsWith($name, 'Exception')
|| $name === '\Throwable'
|| (StringHelper::endsWith($name, 'Error') && !NamespaceHelper::hasNamespace($name))
|| in_array($canonicalName, $this->getSpecialExceptionNames(), true);
$inIgnoredNames = in_array($canonicalName, $this->getIgnoredNames(), true);
if ($isExceptionByName && !$inIgnoredNames && $this->allowFullyQualifiedExceptions) {
continue;
}
if (
$isFullyQualified
&& !NamespaceHelper::hasNamespace($name)
&& $namespacePointers === []
) {
$label = sprintf(
$reference->isConstant ? 'Constant %s' : ($reference->isFunction ? 'Function %s()' : 'Class %s'),
$name
);
$fix = $phpcsFile->addFixableError(sprintf(
'%s should not be referenced via a fully qualified name, but via an unqualified name without the leading \\, because the file does not have a namespace and the type cannot be put in a use statement.',
$label
), $startPointer, self::CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME_WITHOUT_NAMESPACE);
if ($fix) {
$phpcsFile->fixer->beginChangeset();
if ($reference->source === self::SOURCE_ANNOTATION) {
$fixedDocComment = AnnotationHelper::fixAnnotation(
$reference->parsedDocComment,
$reference->annotation,
$reference->nameNode,
new IdentifierTypeNode(substr($reference->name, 1))
);
FixerHelper::change(
$phpcsFile,
$reference->parsedDocComment->getOpenPointer(),
$reference->parsedDocComment->getClosePointer(),
$fixedDocComment
);
} elseif ($reference->source === self::SOURCE_ANNOTATION_CONSTANT_FETCH) {
$fixedDocComment = AnnotationHelper::fixAnnotation(
$reference->parsedDocComment,
$reference->annotation,
$reference->constantFetchNode,
new ConstFetchNode(substr($reference->name, 1), $reference->constantFetchNode->name)
);
FixerHelper::change(
$phpcsFile,
$reference->parsedDocComment->getOpenPointer(),
$reference->parsedDocComment->getClosePointer(),
$fixedDocComment
);
} else {
$phpcsFile->fixer->replaceToken($startPointer, substr($tokens[$startPointer]['content'], 1));
}
$phpcsFile->fixer->endChangeset();
}
} else {
$shouldBeUsed = NamespaceHelper::hasNamespace($name);
if (!$shouldBeUsed) {
if ($reference->isFunction) {
$shouldBeUsed = $isFullyQualified
? !$this->allowFullyQualifiedGlobalFunctions
: !$this->allowFallbackGlobalFunctions;
} elseif ($reference->isConstant) {
$shouldBeUsed = $isFullyQualified
? !$this->allowFullyQualifiedGlobalConstants
: !$this->allowFallbackGlobalConstants;
} else {
$shouldBeUsed = !$this->allowFullyQualifiedGlobalClasses;
}
}
if (!$shouldBeUsed) {
continue;
}
$referenceErrors[] = (object) [
'reference' => $reference,
'canonicalName' => $canonicalName,
'isGlobalConstantFallback' => $isGlobalConstantFallback,
'isGlobalFunctionFallback' => $isGlobalFunctionFallback,
];
}
} elseif (!$this->allowPartialUses) {
if (NamespaceHelper::isQualifiedName($name)) {
$phpcsFile->addError(sprintf(
'Partial use statements are not allowed, but referencing %s found.',
$name
), $startPointer, self::CODE_PARTIAL_USE);
}
}
}
if (count($referenceErrors) === 0) {
return;
}
$alreadyAddedUses = [
UseStatement::TYPE_CLASS => [],
UseStatement::TYPE_FUNCTION => [],
UseStatement::TYPE_CONSTANT => [],
];
$phpcsFile->fixer->beginChangeset();
foreach ($referenceErrors as $referenceData) {
$reference = $referenceData->reference;
/** @var int $startPointer */
$startPointer = $reference->startPointer;
$canonicalName = $referenceData->canonicalName;
$nameToReference = NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($reference->name);
$canonicalNameToReference = $reference->isConstant ? $nameToReference : strtolower($nameToReference);
$isGlobalConstantFallback = $referenceData->isGlobalConstantFallback;
$isGlobalFunctionFallback = $referenceData->isGlobalFunctionFallback;
$useStatements = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $reference->startPointer);
$canBeFixed = array_reduce(
$alreadyAddedUses[$reference->type],
static function (bool $carry, string $use) use ($canonicalName): bool {
$useLastName = strtolower(NamespaceHelper::getLastNamePart($use));
$canonicalLastName = strtolower(NamespaceHelper::getLastNamePart($canonicalName));
return $useLastName === $canonicalLastName ? false : $carry;
},
true
);
if (
(
$reference->isClass
&& array_key_exists($canonicalNameToReference, $definedClassesIndex)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName($definedClassesIndex[$canonicalNameToReference])
)
|| (
$reference->isClass
&& array_key_exists($canonicalNameToReference, $classReferencesIndex)
&& $canonicalName !== NamespaceHelper::normalizeToCanonicalName($classReferencesIndex[$canonicalNameToReference])
)
|| ($reference->isFunction && array_key_exists($canonicalNameToReference, $definedFunctionsIndex))
|| ($reference->isConstant && array_key_exists($canonicalNameToReference, $definedConstantsIndex))
) {
$canBeFixed = false;
}
foreach ($useStatements as $useStatement) {
if ($useStatement->getType() !== $reference->type) {
continue;
}
if ($useStatement->getFullyQualifiedTypeName() === $canonicalName) {
continue;
}
if ($useStatement->getCanonicalNameAsReferencedInFile() !== $canonicalNameToReference) {
continue;
}
$canBeFixed = false;
break;
}
$label = sprintf(
$reference->isConstant
? 'Constant %s'
: ($reference->isFunction ? 'Function %s()' : 'Class %s'),
$reference->name
);
$errorCode = $isGlobalConstantFallback || $isGlobalFunctionFallback
? self::CODE_REFERENCE_VIA_FALLBACK_GLOBAL_NAME
: self::CODE_REFERENCE_VIA_FULLY_QUALIFIED_NAME;
$errorMessage = $isGlobalConstantFallback || $isGlobalFunctionFallback
? sprintf('%s should not be referenced via a fallback global name, but via a use statement.', $label)
: sprintf('%s should not be referenced via a fully qualified name, but via a use statement.', $label);
if (!$canBeFixed) {
$phpcsFile->addError($errorMessage, $startPointer, $errorCode);
continue;
}
$fix = $phpcsFile->addFixableError($errorMessage, $startPointer, $errorCode);
if (!$fix) {
continue;
}
$addUse = !in_array($canonicalName, $alreadyAddedUses[$reference->type], true);
if (
$reference->isClass
&& array_key_exists($canonicalNameToReference, $definedClassesIndex)
) {
$addUse = false;
}
foreach ($useStatements as $useStatement) {
if (
$useStatement->getType() !== $reference->type
|| $useStatement->getFullyQualifiedTypeName() !== $canonicalName
) {
continue;
}
$nameToReference = $useStatement->getNameAsReferencedInFile();
$addUse = false;
// Lock the use statement, so it is not modified by other sniffs
$phpcsFile->fixer->replaceToken(
$useStatement->getPointer(),
$phpcsFile->fixer->getTokenContent($useStatement->getPointer())
);
break;
}
if ($addUse) {
$useStatementPlacePointer = $this->getUseStatementPlacePointer($phpcsFile, $openTagPointer, $useStatements);
$useTypeName = UseStatement::getTypeName($reference->type);
$useTypeFormatted = $useTypeName !== null ? sprintf('%s ', $useTypeName) : '';
$phpcsFile->fixer->addNewline($useStatementPlacePointer);
$phpcsFile->fixer->addContent($useStatementPlacePointer, sprintf('use %s%s;', $useTypeFormatted, $canonicalName));
$alreadyAddedUses[$reference->type][] = $canonicalName;
}
if ($reference->source === self::SOURCE_ANNOTATION) {
$fixedDocComment = AnnotationHelper::fixAnnotation(
$reference->parsedDocComment,
$reference->annotation,
$reference->nameNode,
new IdentifierTypeNode($nameToReference)
);
FixerHelper::change(
$phpcsFile,
$reference->parsedDocComment->getOpenPointer(),
$reference->parsedDocComment->getClosePointer(),
$fixedDocComment
);
} elseif ($reference->source === self::SOURCE_ANNOTATION_CONSTANT_FETCH) {
$fixedDocComment = AnnotationHelper::fixAnnotation(
$reference->parsedDocComment,
$reference->annotation,
$reference->constantFetchNode,
new ConstFetchNode($nameToReference, $reference->constantFetchNode->name)
);
FixerHelper::change(
$phpcsFile,
$reference->parsedDocComment->getOpenPointer(),
$reference->parsedDocComment->getClosePointer(),
$fixedDocComment
);
} elseif ($reference->source === self::SOURCE_ATTRIBUTE) {
$attributeContent = TokenHelper::getContent($phpcsFile, $startPointer, $reference->endPointer);
$fixedAttributeContent = preg_replace(
'~(?<=\W)' . preg_quote($reference->name, '~') . '(?=\W)~',
$nameToReference,
$attributeContent
);
FixerHelper::change($phpcsFile, $startPointer, $reference->endPointer, $fixedAttributeContent);
} else {
FixerHelper::change($phpcsFile, $startPointer, $reference->endPointer, $nameToReference);
}
}
$phpcsFile->fixer->endChangeset();
}
/**
* @return list<string>
*/
private function getSpecialExceptionNames(): array
{
if ($this->normalizedSpecialExceptionNames === null) {
$this->normalizedSpecialExceptionNames = SniffSettingsHelper::normalizeArray($this->specialExceptionNames);
}
return $this->normalizedSpecialExceptionNames;
}
/**
* @return list<string>
*/
private function getIgnoredNames(): array
{
if ($this->normalizedIgnoredNames === null) {
$this->normalizedIgnoredNames = SniffSettingsHelper::normalizeArray($this->ignoredNames);
}
return $this->normalizedIgnoredNames;
}
/**
* @return list<string>
*/
private function getNamespacesRequiredToUse(): array
{
if ($this->normalizedNamespacesRequiredToUse === null) {
$this->normalizedNamespacesRequiredToUse = SniffSettingsHelper::normalizeArray($this->namespacesRequiredToUse);
}
return $this->normalizedNamespacesRequiredToUse;
}
/**
* @param array<string, UseStatement> $useStatements
*/
private function getUseStatementPlacePointer(File $phpcsFile, int $openTagPointer, array $useStatements): int
{
if (count($useStatements) !== 0) {
$lastUseStatement = array_values($useStatements)[count($useStatements) - 1];
/** @var int $useStatementPlacePointer */
$useStatementPlacePointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $lastUseStatement->getPointer() + 1);
return $useStatementPlacePointer;
}
$namespacePointer = TokenHelper::findNext($phpcsFile, T_NAMESPACE, $openTagPointer + 1);
if ($namespacePointer !== null) {
/** @var int $useStatementPlacePointer */
$useStatementPlacePointer = TokenHelper::findNext($phpcsFile, [T_SEMICOLON, T_OPEN_CURLY_BRACKET], $namespacePointer + 1);
return $useStatementPlacePointer;
}
$tokens = $phpcsFile->getTokens();
$useStatementPlacePointer = $openTagPointer;
$nonWhitespacePointerAfterOpenTag = TokenHelper::findNextNonWhitespace($phpcsFile, $openTagPointer + 1);
if (in_array($tokens[$nonWhitespacePointerAfterOpenTag]['code'], Tokens::$commentTokens, true)) {
$commentEndPointer = CommentHelper::getCommentEndPointer($phpcsFile, $nonWhitespacePointerAfterOpenTag);
if (StringHelper::endsWith($tokens[$commentEndPointer]['content'], $phpcsFile->eolChar)) {
$useStatementPlacePointer = $commentEndPointer;
} else {
$newLineAfterComment = $commentEndPointer + 1;
if (array_key_exists($newLineAfterComment, $tokens) && $tokens[$newLineAfterComment]['content'] === $phpcsFile->eolChar) {
$pointerAfterCommentEnd = TokenHelper::findNextNonWhitespace($phpcsFile, $newLineAfterComment + 1);
if (TokenHelper::findNextContent(
$phpcsFile,
T_WHITESPACE,
$phpcsFile->eolChar,
$newLineAfterComment + 1,
$pointerAfterCommentEnd
) !== null) {
$useStatementPlacePointer = $commentEndPointer;
}
}
}
}
$pointerAfter = TokenHelper::findNextEffective($phpcsFile, $useStatementPlacePointer + 1);
if ($tokens[$pointerAfter]['code'] === T_DECLARE) {
return TokenHelper::findNext($phpcsFile, T_SEMICOLON, $pointerAfter + 1);
}
return $useStatementPlacePointer;
}
private function isRequiredToBeUsed(string $name): bool
{
if ($this->namespacesRequiredToUse === null || $this->namespacesRequiredToUse === []) {
return true;
}
foreach ($this->getNamespacesRequiredToUse() as $namespace) {
if (!NamespaceHelper::isTypeInNamespace($name, $namespace)) {
continue;
}
return true;
}
return false;
}
/**
* @return list<stdClass>
*/
private function getReferences(File $phpcsFile, int $openTagPointer): array
{
$tokens = $phpcsFile->getTokens();
$references = [];
foreach (ReferencedNameHelper::getAllReferencedNames($phpcsFile, $openTagPointer) as $referencedName) {
$reference = new stdClass();
$reference->source = self::SOURCE_CODE;
$reference->name = $referencedName->getNameAsReferencedInFile();
$reference->type = $referencedName->getType();
$reference->startPointer = $referencedName->getStartPointer();
$reference->endPointer = $referencedName->getEndPointer();
$reference->isClass = $referencedName->isClass();
$reference->isConstant = $referencedName->isConstant();
$reference->isFunction = $referencedName->isFunction();
$references[] = $reference;
}
foreach (ReferencedNameHelper::getAllReferencedNamesInAttributes($phpcsFile, $openTagPointer) as $referencedName) {
$reference = new stdClass();
$reference->source = self::SOURCE_ATTRIBUTE;
$reference->name = $referencedName->getNameAsReferencedInFile();
$reference->type = $referencedName->getType();
$reference->startPointer = $referencedName->getStartPointer();
$reference->endPointer = $referencedName->getEndPointer();
$reference->isClass = $referencedName->isClass();
$reference->isConstant = $referencedName->isConstant();
$reference->isFunction = $referencedName->isFunction();
$references[] = $reference;
}
if (!$this->searchAnnotations) {
return $references;
}
$searchAnnotationsPointer = $openTagPointer + 1;
while (true) {
$docCommentOpenPointer = TokenHelper::findNext($phpcsFile, T_DOC_COMMENT_OPEN_TAG, $searchAnnotationsPointer);
if ($docCommentOpenPointer === null) {
break;
}
$parsedDocComment = DocCommentHelper::parseDocComment($phpcsFile, $docCommentOpenPointer);
if ($parsedDocComment !== null) {
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer);
foreach ($annotations as $annotation) {
/** @var list<IdentifierTypeNode> $identifierTypeNodes */
$identifierTypeNodes = AnnotationHelper::getAnnotationNodesByType($annotation->getNode(), IdentifierTypeNode::class);
foreach ($identifierTypeNodes as $typeHintNode) {
$typeHint = $typeHintNode->name;
$lowercasedTypeHint = strtolower($typeHint);
if (
TypeHintHelper::isSimpleTypeHint($lowercasedTypeHint)
|| TypeHintHelper::isSimpleUnofficialTypeHints($lowercasedTypeHint)
|| !TypeHelper::isTypeName($typeHint)
) {
continue;
}
$reference = new stdClass();
$reference->source = self::SOURCE_ANNOTATION;
$reference->parsedDocComment = $parsedDocComment;
$reference->annotation = $annotation;
$reference->nameNode = $typeHintNode;
$reference->name = $typeHint;
$reference->type = ReferencedName::TYPE_CLASS;
$reference->startPointer = $annotation->getStartPointer();
$reference->endPointer = null;
$reference->isClass = true;
$reference->isConstant = false;
$reference->isFunction = false;
$references[] = $reference;
}
/** @var list<ConstFetchNode> $constantFetchNodes */
$constantFetchNodes = AnnotationHelper::getAnnotationNodesByType($annotation->getNode(), ConstFetchNode::class);
foreach ($constantFetchNodes as $constantFetchNode) {
$reference = new stdClass();
$reference->source = self::SOURCE_ANNOTATION_CONSTANT_FETCH;
$reference->parsedDocComment = $parsedDocComment;
$reference->annotation = $annotation;
$reference->constantFetchNode = $constantFetchNode;
$reference->name = $constantFetchNode->className;
$reference->type = ReferencedName::TYPE_CLASS;
$reference->startPointer = $annotation->getStartPointer();
$reference->endPointer = null;
$reference->isClass = true;
$reference->isConstant = false;
$reference->isFunction = false;
$references[] = $reference;
}
}
}
$searchAnnotationsPointer = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
}
return $references;
}
}
@@ -0,0 +1,58 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\TokenHelper;
use const T_NAMESPACE;
use const T_NS_SEPARATOR;
class RequireOneNamespaceInFileSniff implements Sniff
{
public const CODE_MORE_NAMESPACES_IN_FILE = 'MoreNamespacesInFile';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_NAMESPACE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $namespacePointer
*/
public function process(File $phpcsFile, $namespacePointer): void
{
$tokens = $phpcsFile->getTokens();
$pointerAfterNamespace = TokenHelper::findNextEffective($phpcsFile, $namespacePointer + 1);
if ($tokens[$pointerAfterNamespace]['code'] === T_NS_SEPARATOR) {
return;
}
$previousNamespacePointer = $namespacePointer;
do {
$previousNamespacePointer = TokenHelper::findPrevious($phpcsFile, T_NAMESPACE, $previousNamespacePointer - 1);
if ($previousNamespacePointer === null) {
return;
}
$pointerAfterPreviousNamespace = TokenHelper::findNextEffective($phpcsFile, $previousNamespacePointer + 1);
if ($tokens[$pointerAfterPreviousNamespace]['code'] === T_NS_SEPARATOR) {
continue;
}
break;
} while (true);
$phpcsFile->addError('Only one namespace in a file is allowed.', $namespacePointer, self::CODE_MORE_NAMESPACES_IN_FILE);
}
}
@@ -0,0 +1,294 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineAnnotation;
use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\ReferencedName;
use SlevomatCodingStandard\Helpers\ReferencedNameHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\TypeHelper;
use SlevomatCodingStandard\Helpers\TypeHintHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_diff_key;
use function array_filter;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_reverse;
use function count;
use function in_array;
use function preg_match;
use function preg_quote;
use function sprintf;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_NAMESPACE;
use const T_OPEN_TAG;
use const T_SEMICOLON;
class UnusedUsesSniff implements Sniff
{
public const CODE_UNUSED_USE = 'UnusedUse';
/** @var bool */
public $searchAnnotations = false;
/** @var list<string> */
public $ignoredAnnotationNames = [];
/** @var list<string> */
public $ignoredAnnotations = [];
/** @var list<string>|null */
private $normalizedIgnoredAnnotationNames;
/** @var list<string>|null */
private $normalizedIgnoredAnnotations;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
$startPointer = TokenHelper::findPrevious($phpcsFile, T_NAMESPACE, $openTagPointer - 1) ?? $openTagPointer;
$fileUnusedNames = UseStatementHelper::getFileUseStatements($phpcsFile);
$referencedNamesInCode = ReferencedNameHelper::getAllReferencedNames($phpcsFile, $startPointer);
$referencedNamesInAttributes = ReferencedNameHelper::getAllReferencedNamesInAttributes($phpcsFile, $startPointer);
$pointersBeforeUseStatements = array_reverse(NamespaceHelper::getAllNamespacesPointers($phpcsFile));
$allUsedNames = [];
foreach ([$referencedNamesInCode, $referencedNamesInAttributes] as $referencedNames) {
foreach ($referencedNames as $referencedName) {
$pointer = $referencedName->getStartPointer();
$pointerBeforeUseStatements = $this->firstPointerBefore($pointer, $pointersBeforeUseStatements, $startPointer);
$name = $referencedName->getNameAsReferencedInFile();
$nameParts = NamespaceHelper::getNameParts($name);
$nameAsReferencedInFile = $nameParts[0];
$nameReferencedWithoutSubNamespace = count($nameParts) === 1;
$uniqueId = $nameReferencedWithoutSubNamespace
? UseStatement::getUniqueId($referencedName->getType(), $nameAsReferencedInFile)
: UseStatement::getUniqueId(ReferencedName::TYPE_CLASS, $nameAsReferencedInFile);
if (
NamespaceHelper::isFullyQualifiedName($name)
|| !array_key_exists($pointerBeforeUseStatements, $fileUnusedNames)
|| !array_key_exists($uniqueId, $fileUnusedNames[$pointerBeforeUseStatements])
) {
continue;
}
$allUsedNames[$pointerBeforeUseStatements][$uniqueId] = true;
}
}
if ($this->searchAnnotations) {
$tokens = $phpcsFile->getTokens();
$searchAnnotationsPointer = $startPointer + 1;
while (true) {
$docCommentOpenPointer = TokenHelper::findNext($phpcsFile, T_DOC_COMMENT_OPEN_TAG, $searchAnnotationsPointer);
if ($docCommentOpenPointer === null) {
break;
}
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer);
if ($annotations === []) {
$searchAnnotationsPointer = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
continue;
}
$pointerBeforeUseStatements = $this->firstPointerBefore(
$docCommentOpenPointer - 1,
$pointersBeforeUseStatements,
$startPointer
);
if (!array_key_exists($pointerBeforeUseStatements, $fileUnusedNames)) {
$searchAnnotationsPointer = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
continue;
}
foreach ($fileUnusedNames[$pointerBeforeUseStatements] as $useStatement) {
if (!$useStatement->isClass()) {
continue;
}
$nameAsReferencedInFile = $useStatement->getNameAsReferencedInFile();
$uniqueId = UseStatement::getUniqueId($useStatement->getType(), $nameAsReferencedInFile);
foreach ($annotations as $annotation) {
if (in_array($annotation->getName(), $this->getIgnoredAnnotations(), true)) {
continue;
}
if ($annotation->isInvalid()) {
continue;
}
$contentsToCheck = [];
if ($annotation->getValue() instanceof GenericTagValueNode) {
$contentsToCheck[] = $annotation->getName();
$contentsToCheck[] = $annotation->getValue()->value;
} else {
/** @var list<IdentifierTypeNode> $identifierTypeNodes */
$identifierTypeNodes = AnnotationHelper::getAnnotationNodesByType(
$annotation->getNode(),
IdentifierTypeNode::class
);
/** @var list<DoctrineAnnotation> $doctrineAnnotations */
$doctrineAnnotations = AnnotationHelper::getAnnotationNodesByType(
$annotation->getNode(),
DoctrineAnnotation::class
);
/** @var list<ConstFetchNode> $constFetchNodes */
$constFetchNodes = AnnotationHelper::getAnnotationNodesByType($annotation->getNode(), ConstFetchNode::class);
$contentsToCheck = array_filter(array_merge(
$contentsToCheck,
array_map(static function (IdentifierTypeNode $identifierTypeNode): ?string {
if (
TypeHintHelper::isSimpleTypeHint($identifierTypeNode->name)
|| TypeHintHelper::isSimpleUnofficialTypeHints($identifierTypeNode->name)
|| !TypeHelper::isTypeName($identifierTypeNode->name)
) {
return null;
}
return $identifierTypeNode->name;
}, $identifierTypeNodes),
array_map(function (DoctrineAnnotation $doctrineAnnotation): ?string {
if (in_array($doctrineAnnotation->name, $this->getIgnoredAnnotationNames(), true)) {
return null;
}
return $doctrineAnnotation->name;
}, $doctrineAnnotations),
array_map(static function (ConstFetchNode $constFetchNode): string {
return $constFetchNode->className;
}, $constFetchNodes)
));
}
foreach ($contentsToCheck as $contentToCheck) {
if (preg_match(
'~(?<=^|[^a-z\\\\])(' . preg_quote($nameAsReferencedInFile, '~') . ')(?=\\s|::|\\\\|\||\[|$)~im',
$contentToCheck
) === 0) {
continue;
}
$allUsedNames[$pointerBeforeUseStatements][$uniqueId] = true;
}
}
}
$searchAnnotationsPointer = $tokens[$docCommentOpenPointer]['comment_closer'] + 1;
}
}
foreach ($fileUnusedNames as $pointerBeforeUnusedNames => $unusedNames) {
$usedNames = $allUsedNames[$pointerBeforeUnusedNames] ?? [];
foreach (array_diff_key($unusedNames, $usedNames) as $unusedUse) {
$fullName = $unusedUse->getFullyQualifiedTypeName();
if (
$unusedUse->getNameAsReferencedInFile() !== $fullName
&& $unusedUse->getNameAsReferencedInFile() !== NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($fullName)
) {
$fullName .= sprintf(' (as %s)', $unusedUse->getNameAsReferencedInFile());
}
$fix = $phpcsFile->addFixableError(sprintf(
'Type %s is not used in this file.',
$fullName
), $unusedUse->getPointer(), self::CODE_UNUSED_USE);
if (!$fix) {
continue;
}
$endPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $unusedUse->getPointer()) + 1;
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $unusedUse->getPointer(), $endPointer);
$phpcsFile->fixer->endChangeset();
}
}
}
/**
* @return list<string>
*/
private function getIgnoredAnnotationNames(): array
{
if ($this->normalizedIgnoredAnnotationNames === null) {
$this->normalizedIgnoredAnnotationNames = array_merge(
SniffSettingsHelper::normalizeArray($this->ignoredAnnotationNames),
[
'@param',
'@throws',
'@property',
'@method',
]
);
}
return $this->normalizedIgnoredAnnotationNames;
}
/**
* @return list<string>
*/
private function getIgnoredAnnotations(): array
{
if ($this->normalizedIgnoredAnnotations === null) {
$this->normalizedIgnoredAnnotations = SniffSettingsHelper::normalizeArray($this->ignoredAnnotations);
}
return $this->normalizedIgnoredAnnotations;
}
/**
* @param list<int> $pointersBeforeUseStatements
*/
private function firstPointerBefore(int $pointer, array $pointersBeforeUseStatements, int $startPointer): int
{
foreach ($pointersBeforeUseStatements as $pointerBeforeUseStatements) {
if ($pointerBeforeUseStatements < $pointer) {
return $pointerBeforeUseStatements;
}
}
return $startPointer;
}
}
@@ -0,0 +1,74 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function in_array;
use function ltrim;
use const T_USE;
class UseDoesNotStartWithBackslashSniff implements Sniff
{
public const CODE_STARTS_WITH_BACKSLASH = 'UseStartsWithBackslash';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_USE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $usePointer
*/
public function process(File $phpcsFile, $usePointer): void
{
if (!UseStatementHelper::isImportUse($phpcsFile, $usePointer)) {
return;
}
$tokens = $phpcsFile->getTokens();
/** @var int $nextTokenPointer */
$nextTokenPointer = TokenHelper::findNextEffective($phpcsFile, $usePointer + 1);
if (
in_array($tokens[$nextTokenPointer]['code'], TokenHelper::getOnlyNameTokenCodes(), true)
&& (
$tokens[$nextTokenPointer]['content'] === 'function'
|| $tokens[$nextTokenPointer]['content'] === 'const'
)
) {
/** @var int $nextTokenPointer */
$nextTokenPointer = TokenHelper::findNextEffective($phpcsFile, $nextTokenPointer + 1);
}
if (!NamespaceHelper::isFullyQualifiedPointer($phpcsFile, $nextTokenPointer)) {
return;
}
$fix = $phpcsFile->addFixableError(
'Use statement cannot start with a backslash.',
$nextTokenPointer,
self::CODE_STARTS_WITH_BACKSLASH
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($nextTokenPointer, ltrim($tokens[$nextTokenPointer]['content'], '\\'));
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,90 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\StringHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function sprintf;
use function strlen;
use function substr;
use const T_AS;
use const T_SEMICOLON;
use const T_USE;
class UseFromSameNamespaceSniff implements Sniff
{
public const CODE_USE_FROM_SAME_NAMESPACE = 'UseFromSameNamespace';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_USE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $usePointer
*/
public function process(File $phpcsFile, $usePointer): void
{
if (!UseStatementHelper::isImportUse($phpcsFile, $usePointer)) {
return;
}
$namespaceName = NamespaceHelper::findCurrentNamespaceName($phpcsFile, $usePointer);
if ($namespaceName === null) {
$namespaceName = '';
}
$usedTypeName = UseStatementHelper::getFullyQualifiedTypeNameFromUse($phpcsFile, $usePointer);
if (!StringHelper::startsWith($usedTypeName, $namespaceName)) {
return;
}
$asPointer = $this->findAsPointer($phpcsFile, $usePointer);
if ($asPointer !== null) {
return;
}
$usedTypeNameRest = substr($usedTypeName, strlen($namespaceName));
if (!NamespaceHelper::isFullyQualifiedName($usedTypeNameRest) && $namespaceName !== '') {
return;
}
if (NamespaceHelper::hasNamespace($usedTypeNameRest)) {
return;
}
$fix = $phpcsFile->addFixableError(sprintf(
'Use %s is from the same namespace – that is prohibited.',
$usedTypeName
), $usePointer, self::CODE_USE_FROM_SAME_NAMESPACE);
if (!$fix) {
return;
}
$endPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $usePointer) + 1;
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $usePointer, $endPointer);
$phpcsFile->fixer->endChangeset();
}
private function findAsPointer(File $phpcsFile, int $startPointer): ?int
{
return TokenHelper::findNextLocal($phpcsFile, T_AS, $startPointer);
}
}
@@ -0,0 +1,78 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function sprintf;
use const T_USE;
class UseOnlyWhitelistedNamespacesSniff implements Sniff
{
public const CODE_NON_FULLY_QUALIFIED = 'NonFullyQualified';
/** @var bool */
public $allowUseFromRootNamespace = false;
/** @var list<string> */
public $namespacesRequiredToUse = [];
/** @var list<string>|null */
private $normalizedNamespacesRequiredToUse;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_USE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $usePointer
*/
public function process(File $phpcsFile, $usePointer): void
{
if (!UseStatementHelper::isImportUse($phpcsFile, $usePointer)) {
return;
}
$className = UseStatementHelper::getFullyQualifiedTypeNameFromUse($phpcsFile, $usePointer);
if ($this->allowUseFromRootNamespace && !NamespaceHelper::isQualifiedName($className)) {
return;
}
foreach ($this->getNamespacesRequiredToUse() as $namespace) {
if (!NamespaceHelper::isTypeInNamespace($className, $namespace)) {
continue;
}
return;
}
$phpcsFile->addError(sprintf(
'Type %s should not be used, but referenced via a fully qualified name.',
$className
), $usePointer, self::CODE_NON_FULLY_QUALIFIED);
}
/**
* @return list<string>
*/
private function getNamespacesRequiredToUse(): array
{
if ($this->normalizedNamespacesRequiredToUse === null) {
$this->normalizedNamespacesRequiredToUse = SniffSettingsHelper::normalizeArray($this->namespacesRequiredToUse);
}
return $this->normalizedNamespacesRequiredToUse;
}
}
@@ -0,0 +1,343 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
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\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatement;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_key_exists;
use function array_values;
use function count;
use function in_array;
use function sprintf;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_OPEN_TAG;
use const T_SEMICOLON;
class UseSpacingSniff implements Sniff
{
public const CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE = 'IncorrectLinesCountBeforeFirstUse';
public const CODE_INCORRECT_LINES_COUNT_BETWEEN_SAME_TYPES_OF_USE = 'IncorrectLinesCountBetweenSameTypeOfUse';
public const CODE_INCORRECT_LINES_COUNT_BETWEEN_DIFFERENT_TYPES_OF_USE = 'IncorrectLinesCountBetweenDifferentTypeOfUse';
public const CODE_INCORRECT_LINES_COUNT_AFTER_LAST_USE = 'IncorrectLinesCountAfterLastUse';
/** @var int */
public $linesCountBeforeFirstUse = 1;
/** @var int */
public $linesCountBetweenUseTypes = 0;
/** @var int */
public $linesCountAfterLastUse = 1;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
$this->linesCountBeforeFirstUse = SniffSettingsHelper::normalizeInteger($this->linesCountBeforeFirstUse);
$this->linesCountBetweenUseTypes = SniffSettingsHelper::normalizeInteger($this->linesCountBetweenUseTypes);
$this->linesCountAfterLastUse = SniffSettingsHelper::normalizeInteger($this->linesCountAfterLastUse);
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
$fileUseStatements = UseStatementHelper::getFileUseStatements($phpcsFile);
if (count($fileUseStatements) === 0) {
return;
}
foreach ($fileUseStatements as $useStatementsByName) {
$useStatements = array_values($useStatementsByName);
$this->checkLinesBeforeFirstUse($phpcsFile, $useStatements[0]);
$this->checkLinesAfterLastUse($phpcsFile, $useStatements[count($useStatements) - 1]);
$this->checkLinesBetweenSameTypesOfUse($phpcsFile, $useStatements);
$this->checkLinesBetweenDifferentTypesOfUse($phpcsFile, $useStatements);
}
}
private function checkLinesBeforeFirstUse(File $phpcsFile, UseStatement $firstUse): void
{
$tokens = $phpcsFile->getTokens();
/** @var int $pointerBeforeFirstUse */
$pointerBeforeFirstUse = TokenHelper::findPreviousNonWhitespace($phpcsFile, $firstUse->getPointer() - 1);
$useStartPointer = $firstUse->getPointer();
if (
in_array($tokens[$pointerBeforeFirstUse]['code'], Tokens::$commentTokens, true)
&& $tokens[$pointerBeforeFirstUse]['line'] + 1 === $tokens[$useStartPointer]['line']
) {
$useStartPointer = array_key_exists('comment_opener', $tokens[$pointerBeforeFirstUse])
? $tokens[$pointerBeforeFirstUse]['comment_opener']
: CommentHelper::getMultilineCommentStartPointer($phpcsFile, $pointerBeforeFirstUse);
/** @var int $pointerBeforeFirstUse */
$pointerBeforeFirstUse = TokenHelper::findPreviousNonWhitespace($phpcsFile, $useStartPointer - 1);
}
$actualLinesCountBeforeFirstUse = $tokens[$useStartPointer]['line'] - $tokens[$pointerBeforeFirstUse]['line'] - 1;
if ($actualLinesCountBeforeFirstUse === $this->linesCountBeforeFirstUse) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s before first use statement, found %d.',
$this->linesCountBeforeFirstUse,
$this->linesCountBeforeFirstUse === 1 ? '' : 's',
$actualLinesCountBeforeFirstUse
),
$firstUse->getPointer(),
self::CODE_INCORRECT_LINES_COUNT_BEFORE_FIRST_USE
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
if ($tokens[$pointerBeforeFirstUse]['code'] === T_OPEN_TAG) {
$phpcsFile->fixer->replaceToken($pointerBeforeFirstUse, '<?php');
}
FixerHelper::removeBetween($phpcsFile, $pointerBeforeFirstUse, $useStartPointer);
for ($i = 0; $i <= $this->linesCountBeforeFirstUse; $i++) {
$phpcsFile->fixer->addNewline($pointerBeforeFirstUse);
}
$phpcsFile->fixer->endChangeset();
}
private function checkLinesAfterLastUse(File $phpcsFile, UseStatement $lastUse): void
{
$tokens = $phpcsFile->getTokens();
/** @var int $useEndPointer */
$useEndPointer = TokenHelper::findNextLocal($phpcsFile, T_SEMICOLON, $lastUse->getPointer() + 1);
$pointerAfterWhitespaceEnd = TokenHelper::findNextNonWhitespace($phpcsFile, $useEndPointer + 1);
if ($pointerAfterWhitespaceEnd === null) {
return;
}
if (
in_array($tokens[$pointerAfterWhitespaceEnd]['code'], Tokens::$commentTokens, true)
&& $tokens[$pointerAfterWhitespaceEnd]['code'] !== T_DOC_COMMENT_OPEN_TAG
&& (
$tokens[$useEndPointer]['line'] === $tokens[$pointerAfterWhitespaceEnd]['line']
|| $tokens[$useEndPointer]['line'] + 1 === $tokens[$pointerAfterWhitespaceEnd]['line']
)
) {
$useEndPointer = CommentHelper::getMultilineCommentEndPointer($phpcsFile, $pointerAfterWhitespaceEnd);
/** @var int $pointerAfterWhitespaceEnd */
$pointerAfterWhitespaceEnd = TokenHelper::findNextNonWhitespace($phpcsFile, $useEndPointer + 1);
}
$actualLinesCountAfterLastUse = $tokens[$pointerAfterWhitespaceEnd]['line'] - $tokens[$useEndPointer]['line'] - 1;
if ($actualLinesCountAfterLastUse === $this->linesCountAfterLastUse) {
return;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s after last use statement, found %d.',
$this->linesCountAfterLastUse,
$this->linesCountAfterLastUse === 1 ? '' : 's',
$actualLinesCountAfterLastUse
),
$lastUse->getPointer(),
self::CODE_INCORRECT_LINES_COUNT_AFTER_LAST_USE
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $useEndPointer, $pointerAfterWhitespaceEnd);
$linesToAdd = $this->linesCountAfterLastUse;
if (CommentHelper::isLineComment($phpcsFile, $useEndPointer)) {
$linesToAdd--;
}
for ($i = 0; $i <= $linesToAdd; $i++) {
$phpcsFile->fixer->addNewline($useEndPointer);
}
$phpcsFile->fixer->endChangeset();
}
/**
* @param list<UseStatement> $useStatements
*/
private function checkLinesBetweenSameTypesOfUse(File $phpcsFile, array $useStatements): void
{
if (count($useStatements) === 1) {
return;
}
$tokens = $phpcsFile->getTokens();
$requiredLinesCountBetweenUses = 0;
$previousUse = null;
foreach ($useStatements as $use) {
if ($previousUse === null) {
$previousUse = $use;
continue;
}
if (!$use->hasSameType($previousUse)) {
$previousUse = null;
continue;
}
/** @var int $pointerBeforeUse */
$pointerBeforeUse = TokenHelper::findPreviousNonWhitespace($phpcsFile, $use->getPointer() - 1);
$useStartPointer = $use->getPointer();
if (
in_array($tokens[$pointerBeforeUse]['code'], Tokens::$commentTokens, true)
&& TokenHelper::findFirstNonWhitespaceOnLine($phpcsFile, $pointerBeforeUse) === $pointerBeforeUse
&& $tokens[$pointerBeforeUse]['line'] + 1 === $tokens[$useStartPointer]['line']
) {
$useStartPointer = array_key_exists('comment_opener', $tokens[$pointerBeforeUse])
? $tokens[$pointerBeforeUse]['comment_opener']
: CommentHelper::getMultilineCommentStartPointer($phpcsFile, $pointerBeforeUse);
}
$actualLinesCountAfterPreviousUse = $tokens[$useStartPointer]['line'] - $tokens[$previousUse->getPointer()]['line'] - 1;
if ($actualLinesCountAfterPreviousUse === $requiredLinesCountBetweenUses) {
$previousUse = $use;
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected 0 lines between same types of use statement, found %d.',
$actualLinesCountAfterPreviousUse
),
$use->getPointer(),
self::CODE_INCORRECT_LINES_COUNT_BETWEEN_SAME_TYPES_OF_USE
);
if (!$fix) {
$previousUse = $use;
continue;
}
/** @var int $previousUseSemicolonPointer */
$previousUseSemicolonPointer = TokenHelper::findNextLocal($phpcsFile, T_SEMICOLON, $previousUse->getPointer() + 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $previousUseSemicolonPointer, $useStartPointer);
$phpcsFile->fixer->addNewline($previousUseSemicolonPointer);
$phpcsFile->fixer->endChangeset();
$previousUse = $use;
}
}
/**
* @param list<UseStatement> $useStatements
*/
private function checkLinesBetweenDifferentTypesOfUse(File $phpcsFile, array $useStatements): void
{
if (count($useStatements) === 1) {
return;
}
$tokens = $phpcsFile->getTokens();
$previousUse = null;
foreach ($useStatements as $use) {
if ($previousUse === null) {
$previousUse = $use;
continue;
}
if ($use->hasSameType($previousUse)) {
$previousUse = $use;
continue;
}
/** @var int $pointerBeforeUse */
$pointerBeforeUse = TokenHelper::findPreviousNonWhitespace($phpcsFile, $use->getPointer() - 1);
$useStartPointer = $use->getPointer();
if (
in_array($tokens[$pointerBeforeUse]['code'], Tokens::$commentTokens, true)
&& TokenHelper::findFirstNonWhitespaceOnLine($phpcsFile, $pointerBeforeUse) === $pointerBeforeUse
&& $tokens[$pointerBeforeUse]['line'] + 1 === $tokens[$useStartPointer]['line']
) {
$useStartPointer = array_key_exists('comment_opener', $tokens[$pointerBeforeUse])
? $tokens[$pointerBeforeUse]['comment_opener']
: CommentHelper::getMultilineCommentStartPointer($phpcsFile, $pointerBeforeUse);
}
$actualLinesCountAfterPreviousUse = $tokens[$useStartPointer]['line'] - $tokens[$previousUse->getPointer()]['line'] - 1;
if ($actualLinesCountAfterPreviousUse === $this->linesCountBetweenUseTypes) {
$previousUse = $use;
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf(
'Expected %d line%s between different types of use statement, found %d.',
$this->linesCountBetweenUseTypes,
$this->linesCountBetweenUseTypes === 1 ? '' : 's',
$actualLinesCountAfterPreviousUse
),
$use->getPointer(),
self::CODE_INCORRECT_LINES_COUNT_BETWEEN_DIFFERENT_TYPES_OF_USE
);
if (!$fix) {
$previousUse = $use;
continue;
}
/** @var int $previousUseSemicolonPointer */
$previousUseSemicolonPointer = TokenHelper::findNextLocal($phpcsFile, T_SEMICOLON, $previousUse->getPointer() + 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $previousUseSemicolonPointer, $useStartPointer);
for ($i = 0; $i <= $this->linesCountBetweenUseTypes; $i++) {
$phpcsFile->fixer->addNewline($previousUseSemicolonPointer);
}
$phpcsFile->fixer->endChangeset();
$previousUse = $use;
}
}
}
@@ -0,0 +1,82 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Namespaces;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function count;
use function sprintf;
use const T_AS;
use const T_OPEN_TAG;
use const T_SEMICOLON;
class UselessAliasSniff implements Sniff
{
public const CODE_USELESS_ALIAS = 'UselessAlias';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_TAG,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $openTagPointer
*/
public function process(File $phpcsFile, $openTagPointer): void
{
if (TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $openTagPointer - 1) !== null) {
return;
}
$fileUseStatements = UseStatementHelper::getFileUseStatements($phpcsFile);
if (count($fileUseStatements) === 0) {
return;
}
foreach ($fileUseStatements as $useStatements) {
foreach ($useStatements as $useStatement) {
if ($useStatement->getAlias() === null) {
continue;
}
$unqualifiedName = NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($useStatement->getFullyQualifiedTypeName());
if ($unqualifiedName !== $useStatement->getAlias()) {
continue;
}
$fix = $phpcsFile->addFixableError(
sprintf('Useless alias "%s" for use of "%s".', $useStatement->getAlias(), $useStatement->getFullyQualifiedTypeName()),
$useStatement->getPointer(),
self::CODE_USELESS_ALIAS
);
if (!$fix) {
continue;
}
$asPointer = TokenHelper::findNext($phpcsFile, T_AS, $useStatement->getPointer() + 1);
$nameEndPointer = TokenHelper::findPrevious($phpcsFile, TokenHelper::getOnlyNameTokenCodes(), $asPointer - 1);
$useSemicolonPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $asPointer + 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetween($phpcsFile, $nameEndPointer, $useSemicolonPointer);
$phpcsFile->fixer->endChangeset();
}
}
}
}