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,67 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function strtolower;
use const T_OBJECT_OPERATOR;
use const T_OPEN_PARENTHESIS;
use const T_STRING;
class DisallowDirectMagicInvokeCallSniff implements Sniff
{
public const CODE_DISALLOWED_DIRECT_MAGIC_INVOKE_CALL = 'DisallowDirectMagicInvokeCall';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_STRING,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $stringPointer
*/
public function process(File $phpcsFile, $stringPointer): void
{
$tokens = $phpcsFile->getTokens();
$parenthesisOpenerPointer = TokenHelper::findNextEffective($phpcsFile, $stringPointer + 1);
if ($tokens[$parenthesisOpenerPointer]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
if (strtolower($tokens[$stringPointer]['content']) !== '__invoke') {
return;
}
$objectOperator = TokenHelper::findPreviousEffective($phpcsFile, $stringPointer - 1);
if ($tokens[$objectOperator]['code'] !== T_OBJECT_OPERATOR) {
return;
}
$fix = $phpcsFile->addFixableError(
'Direct call of __invoke() is disallowed.',
$stringPointer,
self::CODE_DISALLOWED_DIRECT_MAGIC_INVOKE_CALL
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $objectOperator, $parenthesisOpenerPointer - 1);
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,99 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\IdentificatorHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function in_array;
use const T_AS;
use const T_BITWISE_AND;
use const T_COMMA;
use const T_DOUBLE_ARROW;
use const T_EQUAL;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_USE;
class DisallowReferenceSniff implements Sniff
{
public const CODE_DISALLOWED_PASSING_BY_REFERENCE = 'DisallowedPassingByReference';
public const CODE_DISALLOWED_RETURNING_REFERENCE = 'DisallowedReturningReference';
public const CODE_DISALLOWED_INHERITING_VARIABLE_BY_REFERENCE = 'DisallowedInheritingVariableByReference';
public const CODE_DISALLOWED_ASSIGNING_BY_REFERENCE = 'DisallowedAssigningByReference';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_BITWISE_AND,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $referencePointer
*/
public function process(File $phpcsFile, $referencePointer): void
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $referencePointer - 1);
if (in_array($tokens[$previousPointer]['code'], TokenHelper::$functionTokenCodes, true)) {
$phpcsFile->addError('Returning reference is disallowed.', $referencePointer, self::CODE_DISALLOWED_RETURNING_REFERENCE);
return;
}
$previousParenthesisOpenerPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_PARENTHESIS, $referencePointer - 1);
if (
$previousParenthesisOpenerPointer !== null
&& $tokens[$previousParenthesisOpenerPointer]['parenthesis_closer'] > $referencePointer
) {
if (array_key_exists('parenthesis_owner', $tokens[$previousParenthesisOpenerPointer])) {
$parenthesisOwnerPointer = $tokens[$previousParenthesisOpenerPointer]['parenthesis_owner'];
if (in_array($tokens[$parenthesisOwnerPointer]['code'], TokenHelper::$functionTokenCodes, true)) {
$phpcsFile->addError(
'Passing by reference is disallowed.',
$referencePointer,
self::CODE_DISALLOWED_PASSING_BY_REFERENCE
);
return;
}
}
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $previousParenthesisOpenerPointer - 1);
if (
$pointerBeforeParenthesisOpener !== null
&& $tokens[$pointerBeforeParenthesisOpener]['code'] === T_USE
) {
$phpcsFile->addError(
'Inheriting variable by reference is disallowed.',
$referencePointer,
self::CODE_DISALLOWED_INHERITING_VARIABLE_BY_REFERENCE
);
return;
}
}
/** @var int $variableStartPointer */
$variableStartPointer = TokenHelper::findNextEffective($phpcsFile, $referencePointer + 1);
$variableEndPointer = IdentificatorHelper::findEndPointer($phpcsFile, $variableStartPointer);
if ($variableEndPointer === null) {
return;
}
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $referencePointer - 1);
if (!in_array($tokens[$previousPointer]['code'], [T_EQUAL, T_DOUBLE_ARROW, T_OPEN_SHORT_ARRAY, T_COMMA, T_AS], true)) {
return;
}
$phpcsFile->addError('Assigning by reference is disallowed.', $referencePointer, self::CODE_DISALLOWED_ASSIGNING_BY_REFERENCE);
}
}
@@ -0,0 +1,272 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
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\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_key_exists;
use function array_merge;
use function array_pop;
use function count;
use function in_array;
use function is_array;
use function min;
use function sprintf;
use function strlen;
use function strtolower;
use const PHP_INT_MAX;
use const T_COMMA;
use const T_DOUBLE_COLON;
use const T_EXTENDS;
use const T_IMPLEMENTS;
use const T_NEW;
use const T_OPEN_CURLY_BRACKET;
use const T_SEMICOLON;
use const T_USE;
class ForbiddenClassesSniff implements Sniff
{
public const CODE_FORBIDDEN_CLASS = 'ForbiddenClass';
public const CODE_FORBIDDEN_PARENT_CLASS = 'ForbiddenParentClass';
public const CODE_FORBIDDEN_INTERFACE = 'ForbiddenInterface';
public const CODE_FORBIDDEN_TRAIT = 'ForbiddenTrait';
/** @var array<string, (string|null)> */
public $forbiddenClasses = [];
/** @var array<string, (string|null)> */
public $forbiddenExtends = [];
/** @var array<string, (string|null)> */
public $forbiddenInterfaces = [];
/** @var array<string, (string|null)> */
public $forbiddenTraits = [];
/** @var list<string> */
private static $keywordReferences = ['self', 'parent', 'static'];
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
$searchTokens = [];
if (count($this->forbiddenClasses) > 0) {
$this->forbiddenClasses = self::normalizeInputOption($this->forbiddenClasses);
$searchTokens[] = T_NEW;
$searchTokens[] = T_DOUBLE_COLON;
}
if (count($this->forbiddenExtends) > 0) {
$this->forbiddenExtends = self::normalizeInputOption($this->forbiddenExtends);
$searchTokens[] = T_EXTENDS;
}
if (count($this->forbiddenInterfaces) > 0) {
$this->forbiddenInterfaces = self::normalizeInputOption($this->forbiddenInterfaces);
$searchTokens[] = T_IMPLEMENTS;
}
if (count($this->forbiddenTraits) > 0) {
$this->forbiddenTraits = self::normalizeInputOption($this->forbiddenTraits);
$searchTokens[] = T_USE;
}
return $searchTokens;
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $tokenPointer
*/
public function process(File $phpcsFile, $tokenPointer): void
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$tokenPointer];
$nameTokens = array_merge(TokenHelper::getNameTokenCodes(), TokenHelper::$ineffectiveTokenCodes);
if (
$token['code'] === T_IMPLEMENTS
|| (
$token['code'] === T_USE
&& UseStatementHelper::isTraitUse($phpcsFile, $tokenPointer)
)
) {
$endTokenPointer = TokenHelper::findNext(
$phpcsFile,
[T_SEMICOLON, T_OPEN_CURLY_BRACKET],
$tokenPointer
);
$references = $this->getAllReferences($phpcsFile, $tokenPointer, $endTokenPointer);
if ($token['code'] === T_IMPLEMENTS) {
$this->checkReferences($phpcsFile, $tokenPointer, $references, $this->forbiddenInterfaces);
} else {
// Fixer does not work when traits contains aliases
$this->checkReferences(
$phpcsFile,
$tokenPointer,
$references,
$this->forbiddenTraits,
$tokens[$endTokenPointer]['code'] !== T_OPEN_CURLY_BRACKET
);
}
} elseif (in_array($token['code'], [T_NEW, T_EXTENDS], true)) {
$endTokenPointer = TokenHelper::findNextExcluding($phpcsFile, $nameTokens, $tokenPointer + 1);
$references = $this->getAllReferences($phpcsFile, $tokenPointer, $endTokenPointer);
$this->checkReferences(
$phpcsFile,
$tokenPointer,
$references,
$token['code'] === T_NEW ? $this->forbiddenClasses : $this->forbiddenExtends
);
} elseif ($token['code'] === T_DOUBLE_COLON && !$this->isTraitsConflictResolutionToken($token)) {
$startTokenPointer = TokenHelper::findPreviousExcluding($phpcsFile, $nameTokens, $tokenPointer - 1);
$references = $this->getAllReferences($phpcsFile, $startTokenPointer, $tokenPointer);
$this->checkReferences($phpcsFile, $tokenPointer, $references, $this->forbiddenClasses);
}
}
/**
* @param list<array{fullyQualifiedName: string, startPointer: int|null, endPointer: int|null}> $references
* @param array<string, (string|null)> $forbiddenNames
*/
private function checkReferences(
File $phpcsFile,
int $tokenPointer,
array $references,
array $forbiddenNames,
bool $isFixable = true
): void
{
$token = $phpcsFile->getTokens()[$tokenPointer];
$details = [
T_NEW => ['class', self::CODE_FORBIDDEN_CLASS],
T_DOUBLE_COLON => ['class', self::CODE_FORBIDDEN_CLASS],
T_EXTENDS => ['as a parent class', self::CODE_FORBIDDEN_PARENT_CLASS],
T_IMPLEMENTS => ['interface', self::CODE_FORBIDDEN_INTERFACE],
T_USE => ['trait', self::CODE_FORBIDDEN_TRAIT],
];
foreach ($references as $reference) {
if (!array_key_exists($reference['fullyQualifiedName'], $forbiddenNames)) {
continue;
}
$alternative = $forbiddenNames[$reference['fullyQualifiedName']];
[$nameType, $code] = $details[$token['code']];
if ($alternative === null) {
$phpcsFile->addError(
sprintf('Usage of %s %s is forbidden.', $reference['fullyQualifiedName'], $nameType),
$reference['startPointer'],
$code
);
} elseif (!$isFixable) {
$phpcsFile->addError(
sprintf(
'Usage of %s %s is forbidden, use %s instead.',
$reference['fullyQualifiedName'],
$nameType,
$alternative
),
$reference['startPointer'],
$code
);
} else {
$fix = $phpcsFile->addFixableError(
sprintf(
'Usage of %s %s is forbidden, use %s instead.',
$reference['fullyQualifiedName'],
$nameType,
$alternative
),
$reference['startPointer'],
$code
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::change($phpcsFile, $reference['startPointer'], $reference['endPointer'], $alternative);
$phpcsFile->fixer->endChangeset();
}
}
}
/**
* @param array<string, array<int, int|string>|int|string> $token
*/
private function isTraitsConflictResolutionToken(array $token): bool
{
return is_array($token['conditions']) && array_pop($token['conditions']) === T_USE;
}
/**
* @return list<array{fullyQualifiedName: string, startPointer: int|null, endPointer: int|null}>
*/
private function getAllReferences(File $phpcsFile, int $startPointer, int $endPointer): array
{
// Always ignore first token
$startPointer++;
$references = [];
while ($startPointer < $endPointer) {
$nextComma = TokenHelper::findNext($phpcsFile, [T_COMMA], $startPointer + 1);
$nextSeparator = min($endPointer, $nextComma ?? PHP_INT_MAX);
$reference = ReferencedNameHelper::getReferenceName($phpcsFile, $startPointer, $nextSeparator - 1);
if (
strlen($reference) !== 0
&& !in_array(strtolower($reference), self::$keywordReferences, true)
) {
$references[] = [
'fullyQualifiedName' => NamespaceHelper::resolveClassName($phpcsFile, $reference, $startPointer),
'startPointer' => TokenHelper::findNextEffective($phpcsFile, $startPointer, $endPointer),
'endPointer' => TokenHelper::findPreviousEffective($phpcsFile, $nextSeparator - 1, $startPointer),
];
}
$startPointer = $nextSeparator + 1;
}
return $references;
}
/**
* @param array<string, (string|null)> $option
* @return array<string, (string|null)>
*/
private static function normalizeInputOption(array $option): array
{
$forbiddenClasses = [];
foreach ($option as $forbiddenClass => $alternative) {
$forbiddenClasses[self::normalizeClassName($forbiddenClass)] = self::normalizeClassName($alternative);
}
return $forbiddenClasses;
}
private static function normalizeClassName(?string $typeName): ?string
{
if ($typeName === null || strlen($typeName) === 0 || strtolower($typeName) === 'null') {
return null;
}
return NamespaceHelper::getFullyQualifiedTypeName($typeName);
}
}
@@ -0,0 +1,114 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FunctionHelper;
use SlevomatCodingStandard\Helpers\NamespaceHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\UseStatementHelper;
use function array_key_exists;
use function in_array;
use function sprintf;
use function substr;
use const T_COMMA;
use const T_ELLIPSIS;
use const T_FUNCTION;
use const T_NEW;
use const T_OBJECT_OPERATOR;
use const T_OPEN_PARENTHESIS;
class OptimizedFunctionsWithoutUnpackingSniff implements Sniff
{
public const CODE_UNPACKING_USED = 'UnpackingUsed';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return TokenHelper::getOnlyNameTokenCodes();
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $pointer
*/
public function process(File $phpcsFile, $pointer): void
{
$previousTokenPointer = TokenHelper::findPreviousEffective($phpcsFile, $pointer - 1);
$openBracketPointer = TokenHelper::findNextEffective($phpcsFile, $pointer + 1);
$tokens = $phpcsFile->getTokens();
if ($openBracketPointer === null || $tokens[$openBracketPointer]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
if (in_array($tokens[$previousTokenPointer]['code'], [T_FUNCTION, T_NEW, T_OBJECT_OPERATOR], true)) {
return;
}
/** @var int $tokenBeforeInvocationPointer */
$tokenBeforeInvocationPointer = TokenHelper::findPreviousExcluding($phpcsFile, TokenHelper::getNameTokenCodes(), $pointer);
$invokedName = TokenHelper::getContent($phpcsFile, $tokenBeforeInvocationPointer + 1, $pointer);
$useName = sprintf('function %s', $invokedName);
$uses = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $pointer);
if ($invokedName[0] === '\\') {
$invokedName = substr($invokedName, 1);
} elseif (array_key_exists($useName, $uses) && $uses[$useName]->isFunction()) {
$invokedName = $uses[$useName]->getFullyQualifiedTypeName();
} elseif (NamespaceHelper::findCurrentNamespaceName($phpcsFile, $pointer) !== null) {
return;
}
if (!in_array($invokedName, FunctionHelper::SPECIAL_FUNCTIONS, true)) {
return;
}
$closeBracketPointer = $tokens[$openBracketPointer]['parenthesis_closer'];
if (TokenHelper::findNextEffective($phpcsFile, $openBracketPointer + 1, $closeBracketPointer + 1) === $closeBracketPointer) {
return;
}
$pointerBeforeCloseBracket = TokenHelper::findPreviousEffective($phpcsFile, $closeBracketPointer - 1);
$startPointer = $tokens[$pointerBeforeCloseBracket]['code'] === T_COMMA ? $pointerBeforeCloseBracket : $closeBracketPointer;
do {
$lastArgumentSeparatorPointer = TokenHelper::findPrevious($phpcsFile, [T_COMMA], $startPointer - 1, $openBracketPointer);
$startPointer = $lastArgumentSeparatorPointer;
} while (
$lastArgumentSeparatorPointer !== null
&& $tokens[$lastArgumentSeparatorPointer]['level'] !== $tokens[$openBracketPointer]['level']
);
if ($lastArgumentSeparatorPointer === null) {
$lastArgumentSeparatorPointer = $openBracketPointer;
}
/** @var int $nextTokenAfterSeparatorPointer */
$nextTokenAfterSeparatorPointer = TokenHelper::findNextEffective(
$phpcsFile,
$lastArgumentSeparatorPointer + 1,
$closeBracketPointer
);
if ($tokens[$nextTokenAfterSeparatorPointer]['code'] !== T_ELLIPSIS) {
return;
}
if (TokenHelper::findNextEffective($phpcsFile, $nextTokenAfterSeparatorPointer + 1) === $closeBracketPointer) {
// First class callables
return;
}
$phpcsFile->addError(
sprintf('Function %s is specialized by PHP and should not use argument unpacking.', $invokedName),
$nextTokenAfterSeparatorPointer,
self::CODE_UNPACKING_USED
);
}
}
@@ -0,0 +1,131 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\IdentificatorHelper;
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function in_array;
use function sprintf;
use function str_repeat;
use function strlen;
use const T_AS;
use const T_BITWISE_AND;
use const T_COMMA;
use const T_DOUBLE_ARROW;
use const T_EQUAL;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_USE;
class ReferenceSpacingSniff implements Sniff
{
public const CODE_INCORRECT_SPACES_AFTER_REFERENCE = 'IncorrectSpacesAfterReference';
/** @var int */
public $spacesCountAfterReference = 0;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_BITWISE_AND,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $referencePointer
*/
public function process(File $phpcsFile, $referencePointer): void
{
$this->spacesCountAfterReference = SniffSettingsHelper::normalizeInteger($this->spacesCountAfterReference);
if (!$this->isReference($phpcsFile, $referencePointer)) {
return;
}
$pointerAfterWhitespace = TokenHelper::findNextNonWhitespace($phpcsFile, $referencePointer + 1);
$whitespace = TokenHelper::getContent($phpcsFile, $referencePointer + 1, $pointerAfterWhitespace - 1);
$actualSpacesCount = strlen($whitespace);
if ($this->spacesCountAfterReference === $actualSpacesCount) {
return;
}
$errorMessage = $this->spacesCountAfterReference === 0
? 'There must be no whitespace after reference.'
: sprintf(
'There must be exactly %d whitespace%s after reference.',
$this->spacesCountAfterReference,
$this->spacesCountAfterReference !== 1 ? 's' : ''
);
$fix = $phpcsFile->addFixableError($errorMessage, $referencePointer, self::CODE_INCORRECT_SPACES_AFTER_REFERENCE);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addContent($referencePointer, str_repeat(' ', $this->spacesCountAfterReference));
FixerHelper::removeBetween($phpcsFile, $referencePointer, $pointerAfterWhitespace);
$phpcsFile->fixer->endChangeset();
}
private function isReference(File $phpcsFile, int $referencePointer): bool
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $referencePointer - 1);
if (in_array($tokens[$previousPointer]['code'], TokenHelper::$functionTokenCodes, true)) {
return true;
}
$previousParenthesisOpenerPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_PARENTHESIS, $referencePointer - 1);
if (
$previousParenthesisOpenerPointer !== null
&& $tokens[$previousParenthesisOpenerPointer]['parenthesis_closer'] > $referencePointer
) {
if (array_key_exists('parenthesis_owner', $tokens[$previousParenthesisOpenerPointer])) {
$parenthesisOwnerPointer = $tokens[$previousParenthesisOpenerPointer]['parenthesis_owner'];
if (in_array($tokens[$parenthesisOwnerPointer]['code'], TokenHelper::$functionTokenCodes, true)) {
return true;
}
}
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $previousParenthesisOpenerPointer - 1);
if (
$pointerBeforeParenthesisOpener !== null
&& $tokens[$pointerBeforeParenthesisOpener]['code'] === T_USE
) {
return true;
}
}
/** @var int $variableStartPointer */
$variableStartPointer = TokenHelper::findNextEffective($phpcsFile, $referencePointer + 1);
$variableEndPointer = IdentificatorHelper::findEndPointer($phpcsFile, $variableStartPointer);
if ($variableEndPointer === null) {
return false;
}
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $referencePointer - 1);
return in_array($tokens[$previousPointer]['code'], [T_EQUAL, T_DOUBLE_ARROW, T_OPEN_SHORT_ARRAY, T_COMMA, T_AS], true);
}
}
@@ -0,0 +1,472 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use SlevomatCodingStandard\Helpers\Annotation;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\IndentationHelper;
use SlevomatCodingStandard\Helpers\ScopeHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use SlevomatCodingStandard\Helpers\TypeHintHelper;
use function array_key_exists;
use function array_merge;
use function array_reverse;
use function array_unique;
use function count;
use function implode;
use function in_array;
use function sprintf;
use function strpos;
use function trim;
use const T_AS;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_EQUAL;
use const T_FOREACH;
use const T_LIST;
use const T_OPEN_SHORT_ARRAY;
use const T_SEMICOLON;
use const T_VARIABLE;
use const T_WHILE;
use const T_WHITESPACE;
class RequireExplicitAssertionSniff implements Sniff
{
public const CODE_REQUIRED_EXPLICIT_ASSERTION = 'RequiredExplicitAssertion';
/** @var bool */
public $enableIntegerRanges = false;
/** @var bool */
public $enableAdvancedStringTypes = false;
/**
* @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();
$tokenCodes = [T_VARIABLE, T_FOREACH, T_WHILE, T_LIST, T_OPEN_SHORT_ARRAY];
$commentClosePointer = $tokens[$docCommentOpenPointer]['comment_closer'];
$codePointer = TokenHelper::findFirstNonWhitespaceOnNextLine($phpcsFile, $commentClosePointer);
if ($codePointer === null || !in_array($tokens[$codePointer]['code'], $tokenCodes, true)) {
$firstPointerOnPreviousLine = TokenHelper::findFirstNonWhitespaceOnPreviousLine($phpcsFile, $docCommentOpenPointer);
if (
$firstPointerOnPreviousLine === null
|| !in_array($tokens[$firstPointerOnPreviousLine]['code'], $tokenCodes, true)
) {
return;
}
$codePointer = $firstPointerOnPreviousLine;
}
/** @var list<Annotation<VarTagValueNode>> $variableAnnotations */
$variableAnnotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer, '@var');
if (count($variableAnnotations) === 0) {
return;
}
foreach (array_reverse($variableAnnotations) as $variableAnnotation) {
if ($variableAnnotation->isInvalid()) {
continue;
}
$variableName = $variableAnnotation->getValue()->variableName;
if ($variableName === '') {
continue;
}
$variableAnnotationType = $variableAnnotation->getValue()->type;
if (
$variableAnnotationType instanceof UnionTypeNode
|| $variableAnnotationType instanceof IntersectionTypeNode
) {
foreach ($variableAnnotationType->types as $typeNode) {
if (!$this->isValidTypeNode($typeNode)) {
continue 2;
}
}
} elseif (!$this->isValidTypeNode($variableAnnotationType)) {
continue;
}
/** @var IdentifierTypeNode|ThisTypeNode|UnionTypeNode|GenericTypeNode $variableAnnotationType */
$variableAnnotationType = $variableAnnotationType;
$assertion = $this->createAssert($variableName, $variableAnnotationType);
if ($assertion === null) {
continue;
}
if ($tokens[$codePointer]['code'] === T_VARIABLE) {
$pointerAfterVariable = TokenHelper::findNextEffective($phpcsFile, $codePointer + 1);
if ($tokens[$pointerAfterVariable]['code'] !== T_EQUAL) {
continue;
}
if ($variableName !== $tokens[$codePointer]['content']) {
continue;
}
$pointerToAddAssertion = $this->getNextSemicolonInSameScope($phpcsFile, $codePointer, $codePointer + 1);
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenPointer);
} 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) {
continue;
}
$pointerToAddAssertion = $this->getNextSemicolonInSameScope($phpcsFile, $codePointer, $codePointer + 1);
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenPointer);
} elseif ($tokens[$codePointer]['code'] === T_OPEN_SHORT_ARRAY) {
$pointerAfterList = TokenHelper::findNextEffective($phpcsFile, $tokens[$codePointer]['bracket_closer'] + 1);
if ($tokens[$pointerAfterList]['code'] !== T_EQUAL) {
continue;
}
$variablePointerInList = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$variableName,
$codePointer + 1,
$tokens[$codePointer]['bracket_closer']
);
if ($variablePointerInList === null) {
continue;
}
$pointerToAddAssertion = $this->getNextSemicolonInSameScope(
$phpcsFile,
$codePointer,
$tokens[$codePointer]['bracket_closer'] + 1
);
$indentation = IndentationHelper::getIndentation($phpcsFile, $docCommentOpenPointer);
} 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) {
continue;
}
$pointerAfterVariableInWhile = TokenHelper::findNextEffective($phpcsFile, $variablePointerInWhile + 1);
if ($tokens[$pointerAfterVariableInWhile]['code'] !== T_EQUAL) {
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) {
continue;
}
}
$pointerToAddAssertion = $tokens[$codePointer]['scope_opener'];
$indentation = IndentationHelper::addIndentation(IndentationHelper::getIndentation($phpcsFile, $codePointer));
}
$fix = $phpcsFile->addFixableError(
'Use assertion instead of inline documentation comment.',
$variableAnnotation->getStartPointer(),
self::CODE_REQUIRED_EXPLICIT_ASSERTION
);
if (!$fix) {
continue;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $variableAnnotation->getStartPointer(), $variableAnnotation->getEndPointer());
$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;
}
$pointerBeforeDocComment = TokenHelper::findPreviousContent(
$phpcsFile,
T_WHITESPACE,
$phpcsFile->eolChar,
$docCommentOpenPointer - 1
);
$pointerAfterDocComment = TokenHelper::findNextContent(
$phpcsFile,
T_WHITESPACE,
$phpcsFile->eolChar,
$docCommentClosePointer + 1
);
if (!$docCommentUseful) {
FixerHelper::removeBetweenIncluding($phpcsFile, $pointerBeforeDocComment + 1, $pointerAfterDocComment);
}
if (
$pointerToAddAssertion < $docCommentClosePointer
&& array_key_exists($pointerAfterDocComment + 1, $tokens)
) {
$phpcsFile->fixer->addContentBefore($pointerAfterDocComment + 1, $indentation . $assertion . $phpcsFile->eolChar);
} else {
$phpcsFile->fixer->addContent($pointerToAddAssertion, $phpcsFile->eolChar . $indentation . $assertion);
}
$phpcsFile->fixer->endChangeset();
}
}
private function isValidTypeNode(TypeNode $typeNode): bool
{
if ($typeNode instanceof ThisTypeNode) {
return true;
}
if ($typeNode instanceof IdentifierTypeNode) {
return true;
}
if (
$this->enableIntegerRanges
&& $typeNode instanceof GenericTypeNode
&& $typeNode->type->name === 'int'
&& count($typeNode->genericTypes) === 2
) {
foreach ($typeNode->genericTypes as $genericType) {
$isValid = ($genericType instanceof IdentifierTypeNode && in_array($genericType->name, ['min', 'max'], true))
|| ($genericType instanceof ConstTypeNode && $genericType->constExpr instanceof ConstExprIntegerNode);
if (!$isValid) {
return false;
}
}
return true;
}
return false;
}
private function getNextSemicolonInSameScope(File $phpcsFile, int $scopePointer, int $searchAt): int
{
$semicolonPointer = null;
do {
$semicolonPointer = TokenHelper::findNext($phpcsFile, T_SEMICOLON, $searchAt);
if (ScopeHelper::isInSameScope($phpcsFile, $scopePointer, $semicolonPointer)) {
break;
}
$searchAt = $semicolonPointer + 1;
} while (true);
return $semicolonPointer;
}
/**
* @param IdentifierTypeNode|ThisTypeNode|UnionTypeNode|IntersectionTypeNode|GenericTypeNode $typeNode
*/
private function createAssert(string $variableName, TypeNode $typeNode): ?string
{
$conditions = [];
if (
$typeNode instanceof IdentifierTypeNode
|| $typeNode instanceof ThisTypeNode
|| $typeNode instanceof GenericTypeNode
) {
$conditions = $this->createConditions($variableName, $typeNode);
return $conditions !== [] ? sprintf('\assert(%s);', implode(' || ', $conditions)) : null;
}
/** @var IdentifierTypeNode|ThisTypeNode|GenericTypeNode $innerTypeNode */
foreach ($typeNode->types as $innerTypeNode) {
$innerTypeConditions = $this->createConditions($variableName, $innerTypeNode);
if ($innerTypeConditions === []) {
return null;
}
$conditions = array_merge($conditions, $innerTypeConditions);
}
$operator = $typeNode instanceof IntersectionTypeNode ? '&&' : '||';
$formattedConditions = [];
foreach (array_unique($conditions) as $condition) {
$formattedConditions[] = $operator === '||' && strpos($condition, '&&') !== false ? sprintf('(%s)', $condition) : $condition;
}
return sprintf('\assert(%s);', implode(sprintf(' %s ', $operator), $formattedConditions));
}
/**
* @param IdentifierTypeNode|ThisTypeNode|GenericTypeNode $typeNode
* @return list<string>
*/
private function createConditions(string $variableName, TypeNode $typeNode): array
{
if ($typeNode instanceof GenericTypeNode) {
$conditions = [sprintf('\is_int(%s)', $variableName)];
if ($typeNode->genericTypes[0] instanceof ConstTypeNode) {
$conditions[] = sprintf('%s >= %s', $variableName, (string) $typeNode->genericTypes[0]);
}
if ($typeNode->genericTypes[1] instanceof ConstTypeNode) {
$conditions[] = sprintf('%s <= %s', $variableName, (string) $typeNode->genericTypes[1]);
}
return [implode(' && ', $conditions)];
}
if ($typeNode instanceof ThisTypeNode) {
return [sprintf('%s instanceof $this', $variableName)];
}
if ($typeNode->name === 'self') {
return [sprintf('%s instanceof %s', $variableName, $typeNode->name)];
}
if ($typeNode->name === 'static') {
return [sprintf('%s instanceof static', $variableName)];
}
if (in_array($typeNode->name, ['true', 'false', 'null'], true)) {
return [sprintf('%s === %s', $variableName, $typeNode->name)];
}
if (
$typeNode->name === 'mixed'
|| TypeHintHelper::isVoidTypeHint($typeNode->name)
|| TypeHintHelper::isNeverTypeHint($typeNode->name)
) {
return [];
}
if (TypeHintHelper::isSimpleTypeHint($typeNode->name)) {
return [sprintf('\is_%s(%s)', TypeHintHelper::convertLongSimpleTypeHintToShort($typeNode->name), $variableName)];
}
if (in_array($typeNode->name, ['resource', 'object'], true)) {
return [sprintf('\is_%s(%s)', $typeNode->name, $variableName)];
}
if ($typeNode->name === 'numeric') {
return [
sprintf('\is_int(%s)', $variableName),
sprintf('\is_float(%s)', $variableName),
];
}
if ($typeNode->name === 'scalar') {
return [
sprintf('\is_int(%s)', $variableName),
sprintf('\is_float(%s)', $variableName),
sprintf('\is_bool(%s)', $variableName),
sprintf('\is_string(%s)', $variableName),
];
}
if ($this->enableIntegerRanges) {
if ($typeNode->name === 'positive-int') {
return [sprintf('\is_int(%1$s) && %1$s > 0', $variableName)];
}
if ($typeNode->name === 'negative-int') {
return [sprintf('\is_int(%1$s) && %1$s < 0', $variableName)];
}
}
if (
$this->enableAdvancedStringTypes
&& in_array($typeNode->name, ['non-empty-string', 'non-falsy-string', 'callable-string', 'numeric-string'], true)
) {
$conditions = [sprintf('\is_string(%s)', $variableName)];
if ($typeNode->name === 'non-empty-string') {
$conditions[] = sprintf("%s !== ''", $variableName);
} elseif ($typeNode->name === 'non-falsy-string') {
$conditions[] = sprintf('(bool) %s === true', $variableName);
} elseif ($typeNode->name === 'callable-string') {
$conditions[] = sprintf('\is_callable(%s)', $variableName);
} else {
$conditions[] = sprintf('\is_numeric(%s)', $variableName);
}
return [implode(' && ', $conditions)];
}
if (TypeHintHelper::isSimpleUnofficialTypeHints($typeNode->name)) {
return [];
}
return [sprintf('%s instanceof %s', $variableName, $typeNode->name)];
}
}
@@ -0,0 +1,74 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function preg_match;
use function preg_replace;
use const T_END_HEREDOC;
use const T_HEREDOC;
use const T_START_HEREDOC;
class RequireNowdocSniff implements Sniff
{
public const CODE_REQUIRED_NOWDOC = 'RequiredNowdoc';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_START_HEREDOC,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $heredocStartPointer
*/
public function process(File $phpcsFile, $heredocStartPointer): void
{
$tokens = $phpcsFile->getTokens();
$heredocEndPointer = TokenHelper::findNext($phpcsFile, T_END_HEREDOC, $heredocStartPointer + 1);
$heredocContentPointers = [];
for ($i = $heredocStartPointer + 1; $i < $heredocEndPointer; $i++) {
if ($tokens[$i]['code'] === T_HEREDOC) {
if (preg_match('~^([^\\\\$]|\\\\[^nrtvef0-7xu])*$~', $tokens[$i]['content']) === 0) {
return;
}
$heredocContentPointers[] = $i;
}
}
$fix = $phpcsFile->addFixableError('Use nowdoc syntax instead of heredoc.', $heredocStartPointer, self::CODE_REQUIRED_NOWDOC);
if (!$fix) {
return;
}
$nowdocStart = preg_replace('~^<<<"?(\w+)"?~', '<<<\'$1\'', $tokens[$heredocStartPointer]['content']);
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($heredocStartPointer, $nowdocStart);
foreach ($heredocContentPointers as $heredocContentPointer) {
$heredocContent = $tokens[$heredocContentPointer]['content'];
$nowdocContent = preg_replace(
'~\\\\(\\\\[nrtvef]|\$|\\\\|\\\\[0-7]{1,3}|\\\\x[0-9A-Fa-f]{1,2}|\\\\u\{[0-9A-Fa-f]+\})~',
'$1',
$heredocContent
);
$phpcsFile->fixer->replaceToken($heredocContentPointer, $nowdocContent);
}
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,50 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use const T_LIST;
use const T_OPEN_PARENTHESIS;
class ShortListSniff implements Sniff
{
public const CODE_LONG_LIST_USED = 'LongListUsed';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [T_LIST];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $pointer
*/
public function process(File $phpcsFile, $pointer): void
{
$fix = $phpcsFile->addFixableError('list(...) is forbidden, use [...] instead.', $pointer, self::CODE_LONG_LIST_USED);
if (!$fix) {
return;
}
$tokens = $phpcsFile->getTokens();
/** @var int $startPointer */
$startPointer = TokenHelper::findNext($phpcsFile, [T_OPEN_PARENTHESIS], $pointer + 1);
$endPointer = $tokens[$startPointer]['parenthesis_closer'];
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $pointer, $startPointer - 1);
$phpcsFile->fixer->replaceToken($startPointer, '[');
$phpcsFile->fixer->replaceToken($endPointer, ']');
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,119 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
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 preg_match;
use function sprintf;
use function strtolower;
use const T_BINARY_CAST;
use const T_BOOL_CAST;
use const T_DOUBLE_CAST;
use const T_INT_CAST;
use const T_STRING_CAST;
use const T_UNSET_CAST;
class TypeCastSniff implements Sniff
{
public const CODE_FORBIDDEN_CAST_USED = 'ForbiddenCastUsed';
public const CODE_INVALID_CAST_USED = 'InvalidCastUsed';
private const INVALID_CASTS = [
'binary' => null,
'boolean' => 'bool',
'double' => 'float',
'integer' => 'int',
'real' => 'float',
'unset' => null,
];
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_STRING_CAST,
T_BOOL_CAST,
T_DOUBLE_CAST,
T_INT_CAST,
T_UNSET_CAST,
T_BINARY_CAST,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $pointer
*/
public function process(File $phpcsFile, $pointer): void
{
$tokens = $phpcsFile->getTokens();
$cast = $tokens[$pointer]['content'];
preg_match('~^\(\s*(\S+)\s*\)\z~i', $cast, $matches);
if (!array_key_exists(1, $matches)) {
return;
}
$castName = $matches[1];
$castNameLower = strtolower($castName);
if (!array_key_exists($castNameLower, self::INVALID_CASTS)) {
return;
}
if ($castNameLower === 'unset') {
$phpcsFile->addError(
sprintf('Cast "%s" is forbidden, use "unset(...)" or assign "null" instead.', $cast),
$pointer,
self::CODE_FORBIDDEN_CAST_USED
);
return;
}
if ($castNameLower === 'binary') {
$fix = $phpcsFile->addFixableError(
sprintf('"Cast "%s" is forbidden and has no effect.', $cast),
$pointer,
self::CODE_FORBIDDEN_CAST_USED
);
if (!$fix) {
return;
}
$end = TokenHelper::findNextEffective($phpcsFile, $pointer + 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $pointer, $end - 1);
$phpcsFile->fixer->endChangeset();
return;
}
$fix = $phpcsFile->addFixableError(
sprintf('Cast "%s" is forbidden, use "(%s)" instead.', $cast, self::INVALID_CASTS[$castNameLower]),
$pointer,
self::CODE_INVALID_CAST_USED
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->replaceToken($pointer, '(' . self::INVALID_CASTS[$castNameLower] . ')');
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,579 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\IdentificatorHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_key_exists;
use function array_map;
use function array_merge;
use function count;
use function in_array;
use const T_ANON_CLASS;
use const T_ARRAY_CAST;
use const T_BITWISE_AND;
use const T_BITWISE_OR;
use const T_BITWISE_XOR;
use const T_BOOL_CAST;
use const T_BOOLEAN_NOT;
use const T_CASE;
use const T_CLONE;
use const T_CLOSE_PARENTHESIS;
use const T_CLOSURE;
use const T_COALESCE;
use const T_COLON;
use const T_CONSTANT_ENCAPSED_STRING;
use const T_DIVIDE;
use const T_DNUMBER;
use const T_DOLLAR;
use const T_DOUBLE_CAST;
use const T_EMPTY;
use const T_EQUAL;
use const T_EVAL;
use const T_EXIT;
use const T_FN;
use const T_INCLUDE;
use const T_INCLUDE_ONCE;
use const T_INLINE_THEN;
use const T_INT_CAST;
use const T_ISSET;
use const T_LIST;
use const T_LNUMBER;
use const T_LOGICAL_AND;
use const T_LOGICAL_OR;
use const T_LOGICAL_XOR;
use const T_MATCH;
use const T_MINUS;
use const T_MODULUS;
use const T_MULTIPLY;
use const T_NEW;
use const T_OBJECT_CAST;
use const T_OPEN_PARENTHESIS;
use const T_PARENT;
use const T_PLUS;
use const T_POW;
use const T_REQUIRE;
use const T_REQUIRE_ONCE;
use const T_SELF;
use const T_SEMICOLON;
use const T_SR;
use const T_STATIC;
use const T_STRING_CAST;
use const T_STRING_CONCAT;
use const T_UNSET;
use const T_UNSET_CAST;
use const T_USE;
use const T_VARIABLE;
use const T_WHITESPACE;
use const T_YIELD;
use const T_YIELD_FROM;
class UselessParenthesesSniff implements Sniff
{
public const CODE_USELESS_PARENTHESES = 'UselessParentheses';
private const OPERATORS = [
T_POW,
T_MULTIPLY,
T_DIVIDE,
T_MODULUS,
T_PLUS,
T_MINUS,
T_STRING_CONCAT,
];
private const OPERATOR_GROUPS = [
T_POW => 1,
T_MULTIPLY => 2,
T_DIVIDE => 2,
T_MODULUS => 3,
T_PLUS => 4,
T_MINUS => 4,
T_STRING_CONCAT => 5,
];
/** @var bool */
public $ignoreComplexTernaryConditions = false;
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_OPEN_PARENTHESIS,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $parenthesisOpenerPointer
*/
public function process(File $phpcsFile, $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
if (array_key_exists('parenthesis_owner', $tokens[$parenthesisOpenerPointer])) {
return;
}
if (!array_key_exists('parenthesis_closer', $tokens[$parenthesisOpenerPointer])) {
return;
}
/** @var int $pointerBeforeParenthesisOpener */
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
if (in_array($tokens[$pointerBeforeParenthesisOpener]['code'], array_merge(
TokenHelper::getNameTokenCodes(),
[
T_VARIABLE,
T_ISSET,
T_UNSET,
T_EMPTY,
T_CLOSURE,
T_FN,
T_USE,
T_ANON_CLASS,
T_NEW,
T_SELF,
T_STATIC,
T_PARENT,
T_EXIT,
T_CLOSE_PARENTHESIS,
T_EVAL,
T_LIST,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_INT_CAST,
T_DOUBLE_CAST,
T_STRING_CAST,
T_ARRAY_CAST,
T_OBJECT_CAST,
T_BOOL_CAST,
T_UNSET_CAST,
T_MATCH,
]
), true)
) {
return;
}
/** @var int $pointerAfterParenthesisOpener */
$pointerAfterParenthesisOpener = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
if (in_array(
$tokens[$pointerAfterParenthesisOpener]['code'],
[T_NEW, T_CLONE, T_YIELD, T_YIELD_FROM, T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE, T_ARRAY_CAST],
true
)) {
return;
}
if (TokenHelper::findNext(
$phpcsFile,
T_EQUAL,
$parenthesisOpenerPointer + 1,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer']
) !== null) {
return;
}
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer'] + 1
);
if (
$pointerAfterParenthesisCloser !== null
&& $tokens[$pointerAfterParenthesisCloser]['code'] === T_OPEN_PARENTHESIS
) {
return;
}
if (IdentificatorHelper::findStartPointer($phpcsFile, $pointerBeforeParenthesisOpener) !== null) {
return;
}
$this->checkParenthesesAroundConditionInTernaryOperator($phpcsFile, $parenthesisOpenerPointer);
$this->checkParenthesesAroundCaseInSwitch($phpcsFile, $parenthesisOpenerPointer);
$this->checkParenthesesAroundVariableOrFunctionCall($phpcsFile, $parenthesisOpenerPointer);
$this->checkParenthesesAroundString($phpcsFile, $parenthesisOpenerPointer);
$this->checkParenthesesAroundOperators($phpcsFile, $parenthesisOpenerPointer);
}
private function checkParenthesesAroundConditionInTernaryOperator(File $phpcsFile, int $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
$parenthesisCloserPointer = $tokens[$parenthesisOpenerPointer]['parenthesis_closer'];
$ternaryOperatorPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisCloserPointer + 1);
if ($tokens[$ternaryOperatorPointer]['code'] !== T_INLINE_THEN) {
return;
}
if (TokenHelper::findNext(
$phpcsFile,
[T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR],
$parenthesisOpenerPointer + 1,
$parenthesisCloserPointer
) !== null) {
return;
}
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
if ($tokens[$pointerBeforeParenthesisOpener]['code'] === T_BOOLEAN_NOT) {
return;
}
if (in_array($tokens[$pointerBeforeParenthesisOpener]['code'], Tokens::$comparisonTokens, true)) {
return;
}
if (in_array($tokens[$pointerBeforeParenthesisOpener]['code'], Tokens::$booleanOperators, true)) {
return;
}
if ($this->ignoreComplexTernaryConditions) {
if (TokenHelper::findNext(
$phpcsFile,
Tokens::$booleanOperators,
$parenthesisOpenerPointer + 1,
$parenthesisCloserPointer
) !== null) {
return;
}
if (TokenHelper::findNextContent(
$phpcsFile,
T_WHITESPACE,
$phpcsFile->eolChar,
$parenthesisOpenerPointer + 1,
$parenthesisCloserPointer
) !== null) {
return;
}
}
$contentStartPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
$contentEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisCloserPointer - 1);
for ($i = $contentStartPointer; $i <= $contentEndPointer; $i++) {
if ($tokens[$i]['code'] === T_INLINE_THEN) {
return;
}
}
$fix = $phpcsFile->addFixableError('Useless parentheses.', $parenthesisOpenerPointer, self::CODE_USELESS_PARENTHESES);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $parenthesisOpenerPointer, $contentStartPointer - 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $contentEndPointer + 1, $parenthesisCloserPointer);
$phpcsFile->fixer->endChangeset();
}
private function checkParenthesesAroundCaseInSwitch(File $phpcsFile, int $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
if ($tokens[$pointerBeforeParenthesisOpener]['code'] !== T_CASE) {
return;
}
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer'] + 1
);
if ($tokens[$pointerAfterParenthesisCloser]['code'] !== T_COLON) {
return;
}
$fix = $phpcsFile->addFixableError('Useless parentheses.', $parenthesisOpenerPointer, self::CODE_USELESS_PARENTHESES);
if (!$fix) {
return;
}
$contentStartPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
$contentEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $tokens[$parenthesisOpenerPointer]['parenthesis_closer'] - 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $parenthesisOpenerPointer, $contentStartPointer - 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $contentEndPointer + 1, $tokens[$parenthesisOpenerPointer]['parenthesis_closer']);
$phpcsFile->fixer->endChangeset();
}
private function checkParenthesesAroundVariableOrFunctionCall(File $phpcsFile, int $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
$operatorsPointers = TokenHelper::findNextAll(
$phpcsFile,
self::OPERATORS,
$parenthesisOpenerPointer + 1,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer']
);
if ($operatorsPointers !== []) {
return;
}
$casePointer = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
if ($tokens[$casePointer]['code'] === T_CASE) {
return;
}
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
if (in_array($tokens[$pointerBeforeParenthesisOpener]['code'], Tokens::$booleanOperators, true)) {
return;
}
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer'] + 1
);
if (in_array($tokens[$pointerAfterParenthesisCloser]['code'], [T_INLINE_THEN, T_OPEN_PARENTHESIS, T_SR], true)) {
return;
}
/** @var int $contentStartPointer */
$contentStartPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
if ($tokens[$contentStartPointer]['code'] === T_CONSTANT_ENCAPSED_STRING) {
return;
}
$notBooleanNotOperatorPointer = $contentStartPointer;
if ($tokens[$contentStartPointer]['code'] === T_BOOLEAN_NOT) {
/** @var int $notBooleanNotOperatorPointer */
$notBooleanNotOperatorPointer = TokenHelper::findNextEffective($phpcsFile, $contentStartPointer + 1);
}
if (in_array(
$tokens[$notBooleanNotOperatorPointer]['code'],
array_merge([T_SELF, T_STATIC, T_PARENT, T_VARIABLE, T_DOLLAR], TokenHelper::getNameTokenCodes()),
true
)) {
$contentEndPointer = IdentificatorHelper::findEndPointer($phpcsFile, $notBooleanNotOperatorPointer);
if (
$contentEndPointer === null
&& in_array($tokens[$notBooleanNotOperatorPointer]['code'], TokenHelper::getNameTokenCodes(), true)
) {
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $contentStartPointer + 1);
if ($tokens[$nextPointer]['code'] === T_OPEN_PARENTHESIS) {
$contentEndPointer = $contentStartPointer;
}
}
do {
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $contentEndPointer + 1);
if ($tokens[$nextPointer]['code'] !== T_OPEN_PARENTHESIS) {
break;
}
$contentEndPointer = $tokens[$nextPointer]['parenthesis_closer'];
} while (true);
} else {
$nextPointer = TokenHelper::findNext($phpcsFile, T_OPEN_PARENTHESIS, $notBooleanNotOperatorPointer + 1);
if ($nextPointer === null || !isset($tokens[$nextPointer]['parenthesis_closer'])) {
return;
}
$contentEndPointer = $tokens[$nextPointer]['parenthesis_closer'];
}
$pointerAfterContent = TokenHelper::findNextEffective($phpcsFile, $contentEndPointer + 1);
if ($pointerAfterContent !== $tokens[$parenthesisOpenerPointer]['parenthesis_closer']) {
return;
}
$fix = $phpcsFile->addFixableError('Useless parentheses.', $parenthesisOpenerPointer, self::CODE_USELESS_PARENTHESES);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $parenthesisOpenerPointer, $contentStartPointer - 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $contentEndPointer + 1, $tokens[$parenthesisOpenerPointer]['parenthesis_closer']);
$phpcsFile->fixer->endChangeset();
}
private function checkParenthesesAroundString(File $phpcsFile, int $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
/** @var int $stringPointer */
$stringPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
if ($tokens[$stringPointer]['code'] !== T_CONSTANT_ENCAPSED_STRING) {
return;
}
$pointerAfterString = TokenHelper::findNextEffective($phpcsFile, $stringPointer + 1);
if ($pointerAfterString !== $tokens[$parenthesisOpenerPointer]['parenthesis_closer']) {
return;
}
$fix = $phpcsFile->addFixableError('Useless parentheses.', $parenthesisOpenerPointer, self::CODE_USELESS_PARENTHESES);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $parenthesisOpenerPointer, $stringPointer - 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $stringPointer + 1, $tokens[$parenthesisOpenerPointer]['parenthesis_closer']);
$phpcsFile->fixer->endChangeset();
}
private function checkParenthesesAroundOperators(File $phpcsFile, int $parenthesisOpenerPointer): void
{
$tokens = $phpcsFile->getTokens();
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $parenthesisOpenerPointer - 1);
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer'] + 1
);
if ($tokens[$pointerBeforeParenthesisOpener]['code'] === T_MINUS) {
$pointerBeforeMinus = TokenHelper::findPreviousEffective($phpcsFile, $pointerBeforeParenthesisOpener - 1);
if (!in_array($tokens[$pointerBeforeMinus]['code'], [T_DNUMBER, T_LNUMBER], true)) {
return;
}
}
if (
in_array($tokens[$pointerBeforeParenthesisOpener]['code'], Tokens::$booleanOperators, true)
|| in_array($tokens[$pointerAfterParenthesisCloser]['code'], Tokens::$booleanOperators, true)
) {
return;
}
$operatorsPointers = [];
$actualStartPointer = $parenthesisOpenerPointer + 1;
while (true) {
$pointer = TokenHelper::findNext(
$phpcsFile,
array_merge(
self::OPERATORS,
[T_OPEN_PARENTHESIS, T_INLINE_THEN, T_COALESCE, T_BITWISE_AND, T_BITWISE_OR, T_BITWISE_XOR],
Tokens::$comparisonTokens
),
$actualStartPointer,
$tokens[$parenthesisOpenerPointer]['parenthesis_closer']
);
if ($pointer === null) {
break;
}
if (in_array($tokens[$pointer]['code'], [T_INLINE_THEN, T_COALESCE, T_BITWISE_AND, T_BITWISE_OR, T_BITWISE_XOR], true)) {
return;
}
if (in_array($tokens[$pointer]['code'], Tokens::$comparisonTokens, true)) {
return;
}
if ($tokens[$pointer]['code'] === T_OPEN_PARENTHESIS) {
$actualStartPointer = $tokens[$pointer]['parenthesis_closer'] + 1;
continue;
}
$operatorsPointers[] = $pointer;
$actualStartPointer = $pointer + 1;
}
if (count($operatorsPointers) === 0) {
return;
}
if (
$tokens[$pointerBeforeParenthesisOpener]['code'] !== T_EQUAL
|| $tokens[$pointerAfterParenthesisCloser]['code'] !== T_SEMICOLON
) {
$operatorsGroups = array_map(static function (int $operatorPointer) use ($tokens): int {
return self::OPERATOR_GROUPS[$tokens[$operatorPointer]['code']];
}, $operatorsPointers);
if (count($operatorsGroups) > 1) {
return;
}
}
$firstOperatorPointer = $operatorsPointers[0];
if (in_array($tokens[$pointerBeforeParenthesisOpener]['code'], self::OPERATORS, true)) {
if (self::OPERATOR_GROUPS[$tokens[$firstOperatorPointer]['code']] !== self::OPERATOR_GROUPS[$tokens[$pointerBeforeParenthesisOpener]['code']]) {
return;
}
if (
$tokens[$pointerBeforeParenthesisOpener]['code'] === T_MINUS
&& in_array($tokens[$firstOperatorPointer]['code'], [T_PLUS, T_MINUS], true)
) {
return;
}
if (
$tokens[$pointerBeforeParenthesisOpener]['code'] === T_DIVIDE
&& in_array($tokens[$firstOperatorPointer]['code'], [T_DIVIDE, T_MULTIPLY], true)
) {
return;
}
if (
$tokens[$pointerBeforeParenthesisOpener]['code'] === T_MODULUS
&& $tokens[$firstOperatorPointer]['code'] === T_MODULUS
) {
return;
}
}
$lastOperatorPointer = $operatorsPointers[count($operatorsPointers) - 1];
if (
in_array($tokens[$pointerAfterParenthesisCloser]['code'], self::OPERATORS, true)
&& self::OPERATOR_GROUPS[$tokens[$lastOperatorPointer]['code']] !== self::OPERATOR_GROUPS[$tokens[$pointerAfterParenthesisCloser]['code']]
) {
return;
}
$fix = $phpcsFile->addFixableError('Useless parentheses.', $parenthesisOpenerPointer, self::CODE_USELESS_PARENTHESES);
if (!$fix) {
return;
}
$contentStartPointer = TokenHelper::findNextEffective($phpcsFile, $parenthesisOpenerPointer + 1);
$contentEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $tokens[$parenthesisOpenerPointer]['parenthesis_closer'] - 1);
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $parenthesisOpenerPointer, $contentStartPointer - 1);
FixerHelper::removeBetweenIncluding($phpcsFile, $contentEndPointer + 1, $tokens[$parenthesisOpenerPointer]['parenthesis_closer']);
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,160 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\PHP;
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 count;
use function in_array;
use const T_ANON_CLASS;
use const T_CLOSE_CURLY_BRACKET;
use const T_CLOSE_PARENTHESIS;
use const T_CLOSURE;
use const T_FN;
use const T_FOR;
use const T_MATCH;
use const T_OPEN_CURLY_BRACKET;
use const T_OPEN_TAG;
use const T_SEMICOLON;
use const T_WHITESPACE;
class UselessSemicolonSniff implements Sniff
{
public const CODE_USELESS_SEMICOLON = 'UselessSemicolon';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [
T_SEMICOLON,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $semicolonPointer
*/
public function process(File $phpcsFile, $semicolonPointer): void
{
$this->checkMultipleSemicolons($phpcsFile, $semicolonPointer);
$this->checkSemicolonAtTheBeginningOfScope($phpcsFile, $semicolonPointer);
$this->checkSemicolonAfterScope($phpcsFile, $semicolonPointer);
}
private function checkMultipleSemicolons(File $phpcsFile, int $semicolonPointer): void
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $semicolonPointer - 1);
if ($tokens[$previousPointer]['code'] !== T_SEMICOLON) {
return;
}
$possibleEndScopePointer = TokenHelper::findNextLocal($phpcsFile, T_CLOSE_PARENTHESIS, $semicolonPointer + 1);
if (
$possibleEndScopePointer !== null
&& $tokens[$possibleEndScopePointer]['parenthesis_opener'] < $semicolonPointer
&& array_key_exists('parenthesis_owner', $tokens[$possibleEndScopePointer])
&& $tokens[$tokens[$possibleEndScopePointer]['parenthesis_owner']]['code'] === T_FOR
) {
return;
}
$fix = $phpcsFile->addFixableError('Useless semicolon.', $semicolonPointer, self::CODE_USELESS_SEMICOLON);
if (!$fix) {
return;
}
$this->removeUselessSemicolon($phpcsFile, $semicolonPointer);
}
private function checkSemicolonAtTheBeginningOfScope(File $phpcsFile, int $semicolonPointer): void
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $semicolonPointer - 1);
if (!in_array($tokens[$previousPointer]['code'], [T_OPEN_TAG, T_OPEN_CURLY_BRACKET], true)) {
return;
}
$fix = $phpcsFile->addFixableError('Useless semicolon.', $semicolonPointer, self::CODE_USELESS_SEMICOLON);
if (!$fix) {
return;
}
$this->removeUselessSemicolon($phpcsFile, $semicolonPointer);
}
private function checkSemicolonAfterScope(File $phpcsFile, int $semicolonPointer): void
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $semicolonPointer - 1);
if ($tokens[$previousPointer]['code'] !== T_CLOSE_CURLY_BRACKET) {
return;
}
if (!array_key_exists('scope_condition', $tokens[$previousPointer])) {
return;
}
$scopeOpenerPointer = $tokens[$previousPointer]['scope_condition'];
if (in_array($tokens[$scopeOpenerPointer]['code'], [T_CLOSURE, T_FN, T_ANON_CLASS, T_MATCH], true)) {
return;
}
$fix = $phpcsFile->addFixableError('Useless semicolon.', $semicolonPointer, self::CODE_USELESS_SEMICOLON);
if (!$fix) {
return;
}
$this->removeUselessSemicolon($phpcsFile, $semicolonPointer);
}
private function removeUselessSemicolon(File $phpcsFile, int $semicolonPointer): void
{
$tokens = $phpcsFile->getTokens();
$fixStartPointer = $semicolonPointer;
do {
if ($tokens[$fixStartPointer - 1]['code'] !== T_WHITESPACE) {
break;
}
$fixStartPointer--;
if ($tokens[$fixStartPointer]['content'] === $phpcsFile->eolChar) {
break;
}
} while (true);
$fixEndPointer = $semicolonPointer;
while ($fixEndPointer < count($tokens) - 1) {
if ($tokens[$fixEndPointer + 1]['code'] !== T_WHITESPACE) {
break;
}
if ($tokens[$fixEndPointer + 1]['content'] === $phpcsFile->eolChar) {
break;
}
$fixEndPointer++;
}
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $fixStartPointer, $fixEndPointer);
$phpcsFile->fixer->endChangeset();
}
}