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,66 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHPStan\PhpDocParser\Ast\PhpDoc\InvalidTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode;
/**
* @internal
* @template T of PhpDocTagValueNode
*/
class Annotation
{
/** @var PhpDocTagNode */
private $node;
/** @var int */
private $startPointer;
/** @var int */
private $endPointer;
public function __construct(PhpDocTagNode $node, int $startPointer, int $endPointer)
{
$this->node = $node;
$this->startPointer = $startPointer;
$this->endPointer = $endPointer;
}
public function getNode(): PhpDocTagNode
{
return $this->node;
}
public function getName(): string
{
return $this->node->name;
}
/**
* @return T
*/
public function getValue(): PhpDocTagValueNode
{
/** @phpstan-ignore-next-line */
return $this->node->value;
}
public function getStartPointer(): int
{
return $this->startPointer;
}
public function getEndPointer(): int
{
return $this->endPointer;
}
public function isInvalid(): bool
{
return $this->node->value instanceof InvalidTagValueNode;
}
}
@@ -0,0 +1,366 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\AbstractNodeVisitor;
use PHPStan\PhpDocParser\Ast\Attribute;
use PHPStan\PhpDocParser\Ast\Node;
use PHPStan\PhpDocParser\Ast\NodeTraverser;
use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArgument;
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TypelessParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
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\ObjectShapeItemNode;
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use function in_array;
use function sprintf;
use function strtolower;
/**
* @internal
*/
class AnnotationHelper
{
public const STATIC_ANALYSIS_PREFIXES = ['psalm', 'phpstan'];
/**
* @return list<Annotation>
*/
public static function getAnnotations(File $phpcsFile, int $pointer, ?string $name = null): array
{
$docCommentOpenPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $pointer);
if ($docCommentOpenPointer === null) {
return [];
}
return SniffLocalCache::getAndSetIfNotCached(
$phpcsFile,
sprintf('annotations-%d-%s', $docCommentOpenPointer, $name ?? 'all'),
static function () use ($phpcsFile, $docCommentOpenPointer, $name): array {
$annotations = [];
if ($name !== null) {
foreach (self::getAnnotations($phpcsFile, $docCommentOpenPointer) as $annotation) {
if ($annotation->getName() === $name) {
$annotations[] = $annotation;
}
}
} else {
$parsedDocComment = DocCommentHelper::parseDocComment($phpcsFile, $docCommentOpenPointer);
if ($parsedDocComment !== null) {
foreach ($parsedDocComment->getNode()->getTags() as $node) {
$annotationStartPointer = $parsedDocComment->getNodeStartPointer($phpcsFile, $node);
$annotations[] = new Annotation(
$node,
$annotationStartPointer,
$parsedDocComment->getNodeEndPointer($phpcsFile, $node, $annotationStartPointer)
);
}
}
}
return $annotations;
}
);
}
/**
* @param class-string $type
* @return list<Node>
*/
public static function getAnnotationNodesByType(Node $node, string $type): array
{
static $visitor;
static $traverser;
if ($visitor === null) {
$visitor = new class extends AbstractNodeVisitor {
/** @var class-string */
private $type;
/** @var list<Node> */
private $nodes = [];
/** @var list<Node> */
private $nodesToIgnore = [];
/**
* @return Node|list<Node>|NodeTraverser::*|null
*/
public function enterNode(Node $node)
{
if ($this->type === IdentifierTypeNode::class) {
if ($node instanceof ArrayShapeItemNode || $node instanceof ObjectShapeItemNode) {
$this->nodesToIgnore[] = $node->keyName;
} elseif ($node instanceof DoctrineArgument) {
$this->nodesToIgnore[] = $node->key;
}
}
if ($node instanceof $this->type && !in_array($node, $this->nodesToIgnore, true)) {
$this->nodes[] = $node;
}
return null;
}
/**
* @param class-string $type
*/
public function setType(string $type): void
{
$this->type = $type;
}
public function clean(): void
{
$this->nodes = [];
$this->nodesToIgnore = [];
}
/**
* @return list<Node>
*/
public function getNodes(): array
{
return $this->nodes;
}
};
}
if ($traverser === null) {
$traverser = new NodeTraverser([$visitor]);
}
$visitor->setType($type);
$visitor->clean();
$traverser->traverse([$node]);
return $visitor->getNodes();
}
public static function fixAnnotation(
ParsedDocComment $parsedDocComment,
Annotation $annotation,
Node $nodeToFix,
Node $fixedNode
): string
{
$originalNode = $annotation->getNode();
/** @var PhpDocNode $newPhpDocNode */
$newPhpDocNode = PhpDocParserHelper::cloneNode($parsedDocComment->getNode());
foreach ($newPhpDocNode->getTags() as $node) {
if ($node->getAttribute(Attribute::ORIGINAL_NODE) === $originalNode) {
self::changeAnnotationNode($node, $nodeToFix, $fixedNode);
break;
}
}
return PhpDocParserHelper::getPrinter()->printFormatPreserving(
$newPhpDocNode,
$parsedDocComment->getNode(),
$parsedDocComment->getTokens()
);
}
/**
* @param array<int, string> $traversableTypeHints
*/
public static function isAnnotationUseless(
File $phpcsFile,
int $functionPointer,
?TypeHint $typeHint,
Annotation $annotation,
array $traversableTypeHints,
bool $enableUnionTypeHint = false,
bool $enableIntersectionTypeHint = false,
bool $enableStandaloneNullTrueFalseTypeHints = false
): bool
{
if ($annotation->isInvalid()) {
return false;
}
if ($typeHint === null) {
return false;
}
/** @var ParamTagValueNode|TypelessParamTagValueNode|ReturnTagValueNode|VarTagValueNode $annotationValue */
$annotationValue = $annotation->getValue();
if ($annotationValue->description !== '') {
return false;
}
if ($annotationValue instanceof TypelessParamTagValueNode) {
return true;
}
$annotationType = $annotationValue->type;
if (
TypeHintHelper::isTraversableType(
TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $functionPointer, $typeHint->getTypeHintWithoutNullabilitySymbol()),
$traversableTypeHints
)
&& !(
$annotationType instanceof IdentifierTypeNode
&& TypeHintHelper::isSimpleIterableTypeHint(strtolower($annotationType->name))
)
) {
return false;
}
if (AnnotationTypeHelper::containsStaticOrThisType($annotationType)) {
return false;
}
if (
AnnotationTypeHelper::containsJustTwoTypes($annotationType)
|| (
$enableUnionTypeHint
&& (
$annotationType instanceof UnionTypeNode
|| (
$annotationType instanceof IdentifierTypeNode
&& TypeHintHelper::isUnofficialUnionTypeHint($annotationType->name)
)
)
)
|| (
$enableIntersectionTypeHint
&& $annotationType instanceof IntersectionTypeNode
)
) {
$annotationTypeHint = AnnotationTypeHelper::print($annotationType);
return TypeHintHelper::typeHintEqualsAnnotation(
$phpcsFile,
$functionPointer,
$typeHint->getTypeHint(),
$annotationTypeHint
);
}
if ($annotationType instanceof ObjectShapeNode) {
return false;
}
if ($annotationType instanceof ConstTypeNode) {
return false;
}
if ($annotationType instanceof GenericTypeNode) {
return false;
}
if ($annotationType instanceof CallableTypeNode) {
return false;
}
if ($annotationType instanceof ConditionalTypeNode) {
return false;
}
if ($annotationType instanceof ConditionalTypeForParameterNode) {
return false;
}
if ($annotationType instanceof IdentifierTypeNode) {
if (in_array(
strtolower($annotationType->name),
['true', 'false', 'null'],
true
)) {
return $enableStandaloneNullTrueFalseTypeHints;
}
if (in_array(
strtolower($annotationType->name),
['class-string', 'trait-string', 'callable-string', 'numeric-string', 'non-empty-string', 'non-falsy-string', 'literal-string', 'positive-int', 'negative-int'],
true
)) {
return false;
}
}
$annotationTypeHint = AnnotationTypeHelper::getTypeHintFromOneType($annotationType);
return TypeHintHelper::typeHintEqualsAnnotation(
$phpcsFile,
$functionPointer,
$typeHint->getTypeHintWithoutNullabilitySymbol(),
$annotationTypeHint
);
}
private static function changeAnnotationNode(PhpDocTagNode $tagNode, Node $nodeToChange, Node $changedNode): PhpDocTagNode
{
static $visitor;
static $traverser;
if ($visitor === null) {
$visitor = new class extends AbstractNodeVisitor {
/** @var Node */
private $nodeToChange;
/** @var Node */
private $changedNode;
/**
* @return Node|list<Node>|NodeTraverser::*|null
*/
public function enterNode(Node $node)
{
if ($node->getAttribute(Attribute::ORIGINAL_NODE) === $this->nodeToChange) {
return $this->changedNode;
}
return null;
}
public function setNodeToChange(Node $nodeToChange): void
{
$this->nodeToChange = $nodeToChange;
}
public function setChangedNode(Node $changedNode): void
{
$this->changedNode = $changedNode;
}
};
}
if ($traverser === null) {
$traverser = new NodeTraverser([$visitor]);
}
$visitor->setNodeToChange($nodeToChange);
$visitor->setChangedNode($changedNode);
[$changedTagNode] = $traverser->traverse([$tagNode]);
return $changedTagNode;
}
}
@@ -0,0 +1,409 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
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\NullableTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use function count;
use function in_array;
use function strtolower;
/**
* @internal
*/
class AnnotationTypeHelper
{
public static function print(TypeNode $typeNode): string
{
return PhpDocParserHelper::getPrinter()->print($typeNode);
}
public static function containsStaticOrThisType(TypeNode $typeNode): bool
{
if ($typeNode instanceof ThisTypeNode) {
return true;
}
if ($typeNode instanceof IdentifierTypeNode) {
return strtolower($typeNode->name) === 'static';
}
if (
$typeNode instanceof UnionTypeNode
|| $typeNode instanceof IntersectionTypeNode
) {
foreach ($typeNode->types as $innerTypeNode) {
if (self::containsStaticOrThisType($innerTypeNode)) {
return true;
}
}
}
return false;
}
public static function containsOneType(TypeNode $typeNode): bool
{
if ($typeNode instanceof IdentifierTypeNode) {
return true;
}
if ($typeNode instanceof ThisTypeNode) {
return true;
}
if ($typeNode instanceof GenericTypeNode) {
return true;
}
if ($typeNode instanceof CallableTypeNode) {
return true;
}
if ($typeNode instanceof ObjectShapeNode) {
return true;
}
if ($typeNode instanceof ArrayShapeNode) {
return true;
}
if ($typeNode instanceof ArrayTypeNode) {
return true;
}
if ($typeNode instanceof ConstTypeNode) {
if ($typeNode->constExpr instanceof ConstExprIntegerNode) {
return true;
}
if ($typeNode->constExpr instanceof ConstExprFloatNode) {
return true;
}
if ($typeNode->constExpr instanceof ConstExprStringNode) {
return true;
}
}
return false;
}
public static function containsJustTwoTypes(TypeNode $typeNode): bool
{
if ($typeNode instanceof NullableTypeNode && self::containsOneType($typeNode->type)) {
return true;
}
if (
!$typeNode instanceof UnionTypeNode
&& !$typeNode instanceof IntersectionTypeNode
) {
return false;
}
return count($typeNode->types) === 2;
}
/**
* @param array<int, string> $traversableTypeHints
*/
public static function containsTraversableType(TypeNode $typeNode, File $phpcsFile, int $pointer, array $traversableTypeHints): bool
{
if ($typeNode instanceof GenericTypeNode) {
return true;
}
if ($typeNode instanceof ObjectShapeNode) {
return false;
}
if ($typeNode instanceof ArrayShapeNode) {
return true;
}
if ($typeNode instanceof ArrayTypeNode) {
return true;
}
if ($typeNode instanceof IdentifierTypeNode) {
$fullyQualifiedType = TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $pointer, $typeNode->name);
return TypeHintHelper::isTraversableType($fullyQualifiedType, $traversableTypeHints);
}
if (
$typeNode instanceof UnionTypeNode
|| $typeNode instanceof IntersectionTypeNode
) {
foreach ($typeNode->types as $innerTypeNode) {
if (self::containsTraversableType($innerTypeNode, $phpcsFile, $pointer, $traversableTypeHints)) {
return true;
}
}
}
return
(
$typeNode instanceof ConditionalTypeNode
|| $typeNode instanceof ConditionalTypeForParameterNode
) && (
self::containsTraversableType($typeNode->if, $phpcsFile, $pointer, $traversableTypeHints)
|| self::containsTraversableType($typeNode->else, $phpcsFile, $pointer, $traversableTypeHints)
);
}
/**
* @param array<int, string> $traversableTypeHints
*/
public static function containsItemsSpecificationForTraversable(
TypeNode $typeNode,
File $phpcsFile,
int $pointer,
array $traversableTypeHints,
bool $inTraversable = false
): bool
{
if ($typeNode instanceof GenericTypeNode) {
foreach ($typeNode->genericTypes as $genericType) {
if (!self::containsItemsSpecificationForTraversable($genericType, $phpcsFile, $pointer, $traversableTypeHints, true)) {
return false;
}
}
return true;
}
if ($typeNode instanceof ArrayShapeNode) {
foreach ($typeNode->items as $arrayShapeItemNode) {
if (!self::containsItemsSpecificationForTraversable(
$arrayShapeItemNode->valueType,
$phpcsFile,
$pointer,
$traversableTypeHints,
true
)) {
return false;
}
}
return true;
}
if ($typeNode instanceof NullableTypeNode) {
return self::containsItemsSpecificationForTraversable($typeNode->type, $phpcsFile, $pointer, $traversableTypeHints, true);
}
if ($typeNode instanceof IdentifierTypeNode) {
if (TypeHintHelper::isTypeDefinedInAnnotation($phpcsFile, $pointer, $typeNode->name)) {
// We can expect it's better type for traversable
return true;
}
if (!$inTraversable) {
return false;
}
return !TypeHintHelper::isTraversableType(
TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $pointer, $typeNode->name),
$traversableTypeHints
);
}
if ($typeNode instanceof ConstTypeNode) {
return $inTraversable;
}
if ($typeNode instanceof CallableTypeNode) {
return $inTraversable;
}
if ($typeNode instanceof ArrayTypeNode) {
return self::containsItemsSpecificationForTraversable($typeNode->type, $phpcsFile, $pointer, $traversableTypeHints, true);
}
if (
$typeNode instanceof UnionTypeNode
|| $typeNode instanceof IntersectionTypeNode
) {
foreach ($typeNode->types as $innerTypeNode) {
if (
!$inTraversable
&& $innerTypeNode instanceof IdentifierTypeNode
&& strtolower($innerTypeNode->name) === 'null'
) {
continue;
}
if (self::containsItemsSpecificationForTraversable(
$innerTypeNode,
$phpcsFile,
$pointer,
$traversableTypeHints,
$inTraversable
)) {
return true;
}
}
}
if ($typeNode instanceof ConditionalTypeNode || $typeNode instanceof ConditionalTypeForParameterNode) {
return
self::containsItemsSpecificationForTraversable($typeNode->if, $phpcsFile, $pointer, $traversableTypeHints, $inTraversable)
|| self::containsItemsSpecificationForTraversable(
$typeNode->else,
$phpcsFile,
$pointer,
$traversableTypeHints,
$inTraversable
);
}
return false;
}
public static function getTypeHintFromOneType(
TypeNode $typeNode,
bool $enableUnionTypeHint = false,
bool $enableStandaloneNullTrueFalseTypeHints = false
): string
{
if ($typeNode instanceof GenericTypeNode) {
$genericName = $typeNode->type->name;
if (in_array(strtolower($genericName), ['non-empty-array', 'list', 'non-empty-list'], true)) {
return 'array';
}
return $genericName;
}
if ($typeNode instanceof IdentifierTypeNode) {
if (strtolower($typeNode->name) === 'true') {
return $enableStandaloneNullTrueFalseTypeHints ? 'true' : 'bool';
}
if (strtolower($typeNode->name) === 'false') {
return $enableUnionTypeHint || $enableStandaloneNullTrueFalseTypeHints ? 'false' : 'bool';
}
if (in_array(strtolower($typeNode->name), ['positive-int', 'negative-int'], true)) {
return 'int';
}
if (in_array(
strtolower($typeNode->name),
['class-string', 'trait-string', 'callable-string', 'numeric-string', 'non-empty-string', 'non-falsy-string', 'literal-string'],
true
)) {
return 'string';
}
return $typeNode->name;
}
if ($typeNode instanceof CallableTypeNode) {
return $typeNode->identifier->name;
}
if ($typeNode instanceof ArrayTypeNode) {
return 'array';
}
if ($typeNode instanceof ArrayShapeNode) {
return 'array';
}
if ($typeNode instanceof ObjectShapeNode) {
return 'object';
}
if ($typeNode instanceof ConstTypeNode) {
if ($typeNode->constExpr instanceof ConstExprIntegerNode) {
return 'int';
}
if ($typeNode->constExpr instanceof ConstExprFloatNode) {
return 'float';
}
if ($typeNode->constExpr instanceof ConstExprStringNode) {
return 'string';
}
}
return (string) $typeNode;
}
/**
* @param UnionTypeNode|IntersectionTypeNode $typeNode
* @param array<int, string> $traversableTypeHints
* @return list<string>
*/
public static function getTraversableTypeHintsFromType(
TypeNode $typeNode,
File $phpcsFile,
int $pointer,
array $traversableTypeHints,
bool $enableUnionTypeHint = false
): array
{
$typeHints = [];
foreach ($typeNode->types as $type) {
if (
$type instanceof GenericTypeNode
|| $type instanceof ThisTypeNode
|| $type instanceof IdentifierTypeNode
) {
$typeHints[] = self::getTypeHintFromOneType($type);
}
}
if (!$enableUnionTypeHint && count($typeHints) > 1) {
return [];
}
foreach ($typeHints as $typeHint) {
if (!TypeHintHelper::isTraversableType(
TypeHintHelper::getFullyQualifiedTypeHint($phpcsFile, $pointer, $typeHint),
$traversableTypeHints
)) {
return [];
}
}
return $typeHints;
}
/**
* @param UnionTypeNode|IntersectionTypeNode $typeNode
*/
public static function getItemsSpecificationTypeFromType(TypeNode $typeNode): ?TypeNode
{
foreach ($typeNode->types as $type) {
if ($type instanceof ArrayTypeNode) {
return $type;
}
}
return null;
}
}
@@ -0,0 +1,232 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function arsort;
use function in_array;
use function key;
use function strnatcasecmp;
use const T_COMMA;
use const T_OPEN_SHORT_ARRAY;
/**
* @internal
*/
class ArrayHelper
{
/**
* @return list<ArrayKeyValue>
*/
public static function parse(File $phpcsFile, int $arrayPointer): array
{
$tokens = $phpcsFile->getTokens();
$arrayToken = $tokens[$arrayPointer];
[$arrayOpenerPointer, $arrayCloserPointer] = self::openClosePointers($arrayToken);
$keyValues = [];
$firstPointerOnNextLine = TokenHelper::findFirstTokenOnNextLine($phpcsFile, $arrayOpenerPointer + 1);
$firstEffectivePointer = TokenHelper::findNextEffective($phpcsFile, $arrayOpenerPointer + 1);
$arrayKeyValueStartPointer = $firstPointerOnNextLine !== null && $firstPointerOnNextLine < $firstEffectivePointer
? $firstPointerOnNextLine
: $firstEffectivePointer;
$arrayKeyValueEndPointer = $arrayKeyValueStartPointer;
$indentation = $tokens[$arrayOpenerPointer]['line'] < $tokens[$firstEffectivePointer]['line']
? IndentationHelper::getIndentation($phpcsFile, $firstEffectivePointer)
: '';
for ($i = $arrayKeyValueStartPointer; $i < $arrayCloserPointer; $i++) {
$token = $tokens[$i];
if (in_array($token['code'], TokenHelper::$arrayTokenCodes, true)) {
$i = self::openClosePointers($token)[1];
continue;
}
if (array_key_exists('scope_closer', $token) && $token['scope_closer'] > $i) {
$i = $token['scope_closer'] - 1;
continue;
}
if (array_key_exists('parenthesis_closer', $token) && $token['parenthesis_closer'] > $i) {
$i = $token['parenthesis_closer'] - 1;
continue;
}
$nextEffectivePointer = TokenHelper::findNextEffective($phpcsFile, $i + 1);
if ($nextEffectivePointer === $arrayCloserPointer) {
$arrayKeyValueEndPointer = self::getValueEndPointer($phpcsFile, $i, $arrayCloserPointer, $indentation);
break;
}
if ($token['code'] !== T_COMMA || !ScopeHelper::isInSameScope($phpcsFile, $arrayOpenerPointer, $i)) {
$arrayKeyValueEndPointer = $i;
continue;
}
$arrayKeyValueEndPointer = self::getValueEndPointer($phpcsFile, $i, $arrayCloserPointer, $indentation);
$keyValues[] = new ArrayKeyValue($phpcsFile, $arrayKeyValueStartPointer, $arrayKeyValueEndPointer);
$arrayKeyValueStartPointer = $arrayKeyValueEndPointer + 1;
$i = $arrayKeyValueEndPointer;
}
$keyValues[] = new ArrayKeyValue($phpcsFile, $arrayKeyValueStartPointer, $arrayKeyValueEndPointer);
return $keyValues;
}
/**
* @param list<ArrayKeyValue> $keyValues
*/
public static function getIndentation(array $keyValues): ?string
{
$indents = [];
foreach ($keyValues as $keyValue) {
$indent = $keyValue->getIndent() ?? 'null';
$indents[$indent] = isset($indents[$indent])
? $indents[$indent] + 1
: 1;
}
arsort($indents);
$indent = key($indents);
return $indent !== 'null'
? (string) $indent
: null;
}
/**
* @param list<ArrayKeyValue> $keyValues
*/
public static function isKeyed(array $keyValues): bool
{
foreach ($keyValues as $keyValue) {
if ($keyValue->getKey() !== null) {
return true;
}
}
return false;
}
/**
* @param list<ArrayKeyValue> $keyValues
*/
public static function isKeyedAll(array $keyValues): bool
{
foreach ($keyValues as $keyValue) {
if (!$keyValue->isUnpacking() && $keyValue->getKey() === null) {
return false;
}
}
return true;
}
/**
* Test if non-empty array with opening & closing brackets on separate lines
*/
public static function isMultiLine(File $phpcsFile, int $pointer): bool
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$pointer];
[$pointerOpener, $pointerCloser] = self::openClosePointers($token);
$tokenOpener = $tokens[$pointerOpener];
$tokenCloser = $tokens[$pointerCloser];
return $tokenOpener['line'] !== $tokenCloser['line'];
}
/**
* Test if effective tokens between open & closing tokens
*/
public static function isNotEmpty(File $phpcsFile, int $pointer): bool
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$pointer];
[$pointerOpener, $pointerCloser] = self::openClosePointers($token);
/** @var int $pointerPreviousToClose */
$pointerPreviousToClose = TokenHelper::findPreviousEffective($phpcsFile, $pointerCloser - 1);
return $pointerPreviousToClose !== $pointerOpener;
}
/**
* @param list<ArrayKeyValue> $keyValues
*/
public static function isSortedByKey(array $keyValues): bool
{
$previousKey = '';
foreach ($keyValues as $keyValue) {
if ($keyValue->isUnpacking()) {
continue;
}
if (strnatcasecmp($previousKey, $keyValue->getKey()) === 1) {
return false;
}
$previousKey = $keyValue->getKey();
}
return true;
}
/**
* @param array<string, array<int, int|string>|int|string> $token
* @return array{0: int, 1: int}
*/
public static function openClosePointers(array $token): array
{
$isShortArray = $token['code'] === T_OPEN_SHORT_ARRAY;
$pointerOpener = $isShortArray
? $token['bracket_opener']
: $token['parenthesis_opener'];
$pointerCloser = $isShortArray
? $token['bracket_closer']
: $token['parenthesis_closer'];
return [(int) $pointerOpener, (int) $pointerCloser];
}
private static function getValueEndPointer(File $phpcsFile, int $endPointer, int $arrayCloserPointer, string $indentation): int
{
$tokens = $phpcsFile->getTokens();
$nextEffectivePointer = TokenHelper::findNextEffective($phpcsFile, $endPointer + 1, $arrayCloserPointer + 1);
if ($tokens[$nextEffectivePointer]['line'] === $tokens[$endPointer]['line']) {
return $nextEffectivePointer - 1;
}
for ($i = $endPointer + 1; $i < $nextEffectivePointer; $i++) {
if ($tokens[$i]['line'] === $tokens[$endPointer]['line']) {
$endPointer = $i;
continue;
}
$nextNonWhitespacePointer = TokenHelper::findNextNonWhitespace($phpcsFile, $i);
if (!in_array($tokens[$nextNonWhitespacePointer]['code'], TokenHelper::$inlineCommentTokenCodes, true)) {
break;
}
if ($indentation === IndentationHelper::getIndentation($phpcsFile, $nextNonWhitespacePointer)) {
$endPointer = $i - 1;
break;
}
$i = TokenHelper::findLastTokenOnLine($phpcsFile, $i);
$endPointer = $i;
}
return $endPointer;
}
}
@@ -0,0 +1,172 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function in_array;
use function ltrim;
use function rtrim;
use function strpos;
use function trim;
use const T_COMMA;
use const T_DOUBLE_ARROW;
use const T_ELLIPSIS;
use const T_WHITESPACE;
/**
* @internal
*/
class ArrayKeyValue
{
/** @var int */
private $pointerStart;
/** @var int */
private $pointerEnd;
/** @var ?string */
private $indent = null;
/** @var ?string */
private $key = null;
/** @var ?int */
private $pointerArrow = null;
/** @var ?int */
private $pointerComma = null;
/** @var bool */
private $unpacking = false;
public function __construct(File $phpcsFile, int $pointerStart, int $pointerEnd)
{
$this->pointerStart = $pointerStart;
$this->pointerEnd = $pointerEnd;
$this->addValues($phpcsFile);
}
public function getContent(File $phpcsFile, bool $normalize = false, ?string $indent = null): string
{
if ($normalize === false) {
return TokenHelper::getContent($phpcsFile, $this->pointerStart, $this->pointerEnd);
}
$content = '';
$addCommaPtr = $this->pointerComma === null
? TokenHelper::findPreviousEffective($phpcsFile, $this->pointerEnd)
: null;
$tokens = $phpcsFile->getTokens();
for ($pointer = $this->pointerStart; $pointer <= $this->pointerEnd; $pointer++) {
$token = $tokens[$pointer];
$content .= $token['content'];
if ($pointer === $addCommaPtr) {
$content .= ',';
}
}
// Trim, but keep leading empty lines
$content = ltrim($content, " \t");
$content = rtrim($content);
if ($indent !== null && strpos($content, $phpcsFile->eolChar) !== 0) {
$content = $indent . $content;
}
return $content;
}
public function getIndent(): ?string
{
return $this->indent;
}
public function getKey(): ?string
{
return $this->key;
}
public function getPointerArrow(): ?int
{
return $this->pointerArrow;
}
public function getPointerComma(): ?int
{
return $this->pointerComma;
}
public function getPointerEnd(): int
{
return $this->pointerEnd;
}
public function getPointerStart(): int
{
return $this->pointerStart;
}
public function isUnpacking(): bool
{
return $this->unpacking;
}
private function addValues(File $phpcsFile): void
{
$key = '';
$tokens = $phpcsFile->getTokens();
$firstNonWhitespace = null;
for ($i = $this->pointerStart; $i <= $this->pointerEnd; $i++) {
$token = $tokens[$i];
if (in_array($token['code'], TokenHelper::$arrayTokenCodes, true)) {
$i = ArrayHelper::openClosePointers($token)[1];
continue;
}
if ($token['code'] === T_DOUBLE_ARROW) {
$this->pointerArrow = $i;
continue;
}
if ($token['code'] === T_COMMA) {
$this->pointerComma = $i;
continue;
}
if ($token['code'] === T_ELLIPSIS) {
$this->unpacking = true;
continue;
}
if ($this->pointerArrow !== null) {
continue;
}
if ($firstNonWhitespace === null && $token['code'] !== T_WHITESPACE) {
$firstNonWhitespace = $i;
}
if (in_array($token['code'], TokenHelper::$inlineCommentTokenCodes, true) === false) {
$key .= $token['content'];
}
}
$haveIndent = $firstNonWhitespace !== null && TokenHelper::findFirstNonWhitespaceOnLine(
$phpcsFile,
$firstNonWhitespace
) === $firstNonWhitespace;
$this->indent = $haveIndent
? TokenHelper::getContent(
$phpcsFile,
TokenHelper::findFirstTokenOnLine($phpcsFile, $firstNonWhitespace),
$firstNonWhitespace - 1
)
: null;
$this->key = $this->pointerArrow !== null
? trim($key)
: null;
}
}
@@ -0,0 +1,60 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
/**
* @internal
*/
class Attribute
{
/** @var int */
private $attributePointer;
/** @var string */
private $name;
/** @var int */
private $startPointer;
/** @var int */
private $endPointer;
/** @var string|null */
private $content;
public function __construct(int $attributePointer, string $name, int $startPointer, int $endPointer, ?string $content = null)
{
$this->attributePointer = $attributePointer;
$this->name = $name;
$this->startPointer = $startPointer;
$this->endPointer = $endPointer;
$this->content = $content;
}
public function getAttributePointer(): int
{
return $this->attributePointer;
}
public function getName(): string
{
return $this->name;
}
public function getStartPointer(): int
{
return $this->startPointer;
}
public function getEndPointer(): int
{
return $this->endPointer;
}
public function getContent(): ?string
{
return $this->content;
}
}
@@ -0,0 +1,153 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use InvalidArgumentException;
use PHP_CodeSniffer\Files\File;
use function sprintf;
use const T_ANON_CLASS;
use const T_ATTRIBUTE;
use const T_CLASS;
use const T_CLOSURE;
use const T_COMMA;
use const T_CONST;
use const T_ENUM;
use const T_ENUM_CASE;
use const T_FN;
use const T_FUNCTION;
use const T_INTERFACE;
use const T_OPEN_PARENTHESIS;
use const T_TRAIT;
use const T_VARIABLE;
/**
* @internal
*/
class AttributeHelper
{
private const ATTRIBUTE_TARGETS = [
T_ANON_CLASS,
T_CLASS,
T_CLOSURE,
T_CONST,
T_ENUM,
T_ENUM_CASE,
T_FN,
T_FUNCTION,
T_INTERFACE,
T_TRAIT,
T_VARIABLE,
];
/**
* @return list<Attribute>
*/
public static function getAttributes(File $phpcsFile, int $attributeOpenerPointer): array
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$attributeOpenerPointer]['code'] !== T_ATTRIBUTE) {
throw new InvalidArgumentException(
sprintf('Token %d must be attribute, %s given.', $attributeOpenerPointer, $tokens[$attributeOpenerPointer]['type'])
);
}
$attributeCloserPointer = $tokens[$attributeOpenerPointer]['attribute_closer'];
$actualPointer = $attributeOpenerPointer;
$attributes = [];
do {
$attributeNameStartPointer = TokenHelper::findNextEffective($phpcsFile, $actualPointer + 1, $attributeCloserPointer);
if ($attributeNameStartPointer === null) {
break;
}
$attributeNameEndPointer = TokenHelper::findNextExcluding(
$phpcsFile,
TokenHelper::getNameTokenCodes(),
$attributeNameStartPointer + 1
) - 1;
$attributeName = TokenHelper::getContent($phpcsFile, $attributeNameStartPointer, $attributeNameEndPointer);
$pointerAfterAttributeName = TokenHelper::findNextEffective($phpcsFile, $attributeNameEndPointer + 1, $attributeCloserPointer);
if ($pointerAfterAttributeName === null) {
$attributes[] = new Attribute(
$attributeOpenerPointer,
$attributeName,
$attributeNameStartPointer,
$attributeNameEndPointer
);
break;
}
if ($tokens[$pointerAfterAttributeName]['code'] === T_COMMA) {
$attributes[] = new Attribute(
$attributeOpenerPointer,
$attributeName,
$attributeNameStartPointer,
$attributeNameEndPointer
);
$actualPointer = $pointerAfterAttributeName;
}
if ($tokens[$pointerAfterAttributeName]['code'] === T_OPEN_PARENTHESIS) {
$attributes[] = new Attribute(
$attributeOpenerPointer,
$attributeName,
$attributeNameStartPointer,
$tokens[$pointerAfterAttributeName]['parenthesis_closer'],
TokenHelper::getContent(
$phpcsFile,
$pointerAfterAttributeName,
$tokens[$pointerAfterAttributeName]['parenthesis_closer']
)
);
$actualPointer = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$pointerAfterAttributeName]['parenthesis_closer'] + 1,
$attributeCloserPointer
);
continue;
}
} while ($actualPointer !== null);
return $attributes;
}
/**
* Attributes have syntax that when defined incorrectly or in older PHP version, they are treated as comments.
* An example of incorrect declaration is variables that are not properties.
*/
public static function isValidAttribute(File $phpcsFile, int $attributeOpenerPointer): bool
{
return self::getAttributeTarget($phpcsFile, $attributeOpenerPointer) !== null;
}
public static function getAttributeTarget(File $phpcsFile, int $attributeOpenerPointer): ?int
{
$attributeTargetPointer = TokenHelper::findNext($phpcsFile, self::ATTRIBUTE_TARGETS, $attributeOpenerPointer);
if ($attributeTargetPointer === null) {
return null;
}
if (
$phpcsFile->getTokens()[$attributeTargetPointer]['code'] === T_VARIABLE
&& !PropertyHelper::isProperty($phpcsFile, $attributeTargetPointer)
&& !ParameterHelper::isParameter($phpcsFile, $attributeTargetPointer)
) {
return null;
}
return $attributeTargetPointer;
}
}
@@ -0,0 +1,83 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_merge;
use function in_array;
use const T_BITWISE_OR;
use const T_CATCH;
use const T_FINALLY;
/**
* @internal
*/
class CatchHelper
{
public static function getTryEndPointer(File $phpcsFile, int $catchPointer): int
{
$tokens = $phpcsFile->getTokens();
$endPointer = $tokens[$catchPointer]['scope_closer'];
do {
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $endPointer + 1);
if ($nextPointer === null || !in_array($tokens[$nextPointer]['code'], [T_CATCH, T_FINALLY], true)) {
break;
}
$endPointer = $tokens[$nextPointer]['scope_closer'];
} while (true);
return $endPointer;
}
/**
* @param array<string, array<int, int|string>|int|string> $catchToken
* @return list<string>
*/
public static function findCaughtTypesInCatch(File $phpcsFile, array $catchToken): array
{
/** @var int $catchParenthesisOpenerPointer */
$catchParenthesisOpenerPointer = $catchToken['parenthesis_opener'];
/** @var int $catchParenthesisCloserPointer */
$catchParenthesisCloserPointer = $catchToken['parenthesis_closer'];
$nameTokenCodes = TokenHelper::getNameTokenCodes();
$nameEndPointer = $catchParenthesisOpenerPointer;
$tokens = $phpcsFile->getTokens();
$caughtTypes = [];
do {
$nameStartPointer = TokenHelper::findNext(
$phpcsFile,
array_merge([T_BITWISE_OR], $nameTokenCodes),
$nameEndPointer + 1,
$catchParenthesisCloserPointer
);
if ($nameStartPointer === null) {
break;
}
if ($tokens[$nameStartPointer]['code'] === T_BITWISE_OR) {
/** @var int $nameStartPointer */
$nameStartPointer = TokenHelper::findNextEffective($phpcsFile, $nameStartPointer + 1, $catchParenthesisCloserPointer);
}
$pointerAfterNameEndPointer = TokenHelper::findNextExcluding($phpcsFile, $nameTokenCodes, $nameStartPointer + 1);
$nameEndPointer = $pointerAfterNameEndPointer === null ? $nameStartPointer : $pointerAfterNameEndPointer - 1;
$caughtTypes[] = NamespaceHelper::resolveClassName(
$phpcsFile,
TokenHelper::getContent($phpcsFile, $nameStartPointer, $nameEndPointer),
$catchParenthesisOpenerPointer
);
} while (true);
return $caughtTypes;
}
}
@@ -0,0 +1,120 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_reverse;
use function sprintf;
use const T_ANON_CLASS;
use const T_FINAL;
use const T_STRING;
use const T_USE;
/**
* @internal
*/
class ClassHelper
{
public static function getClassPointer(File $phpcsFile, int $pointer): ?int
{
$tokens = $phpcsFile->getTokens();
$classPointers = array_reverse(self::getAllClassPointers($phpcsFile));
foreach ($classPointers as $classPointer) {
if ($tokens[$classPointer]['scope_opener'] < $pointer && $tokens[$classPointer]['scope_closer'] > $pointer) {
return $classPointer;
}
}
return null;
}
public static function isFinal(File $phpcsFile, int $classPointer): bool
{
return $phpcsFile->getTokens()[TokenHelper::findPreviousEffective($phpcsFile, $classPointer - 1)]['code'] === T_FINAL;
}
public static function getFullyQualifiedName(File $phpcsFile, int $classPointer): string
{
$className = self::getName($phpcsFile, $classPointer);
$tokens = $phpcsFile->getTokens();
if ($tokens[$classPointer]['code'] === T_ANON_CLASS) {
return $className;
}
$name = sprintf('%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $className);
$namespace = NamespaceHelper::findCurrentNamespaceName($phpcsFile, $classPointer);
return $namespace !== null ? sprintf('%s%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $namespace, $name) : $name;
}
public static function getName(File $phpcsFile, int $classPointer): string
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$classPointer]['code'] === T_ANON_CLASS) {
return 'class@anonymous';
}
return $tokens[TokenHelper::findNext($phpcsFile, T_STRING, $classPointer + 1, $tokens[$classPointer]['scope_opener'])]['content'];
}
/**
* @return array<int, string>
*/
public static function getAllNames(File $phpcsFile): array
{
$tokens = $phpcsFile->getTokens();
$names = [];
/** @var int $classPointer */
foreach (self::getAllClassPointers($phpcsFile) as $classPointer) {
if ($tokens[$classPointer]['code'] === T_ANON_CLASS) {
continue;
}
$names[$classPointer] = self::getName($phpcsFile, $classPointer);
}
return $names;
}
/**
* @return list<int>
*/
public static function getTraitUsePointers(File $phpcsFile, int $classPointer): array
{
$useStatements = [];
$tokens = $phpcsFile->getTokens();
$scopeLevel = $tokens[$classPointer]['level'] + 1;
for ($i = $tokens[$classPointer]['scope_opener'] + 1; $i < $tokens[$classPointer]['scope_closer']; $i++) {
if ($tokens[$i]['code'] !== T_USE) {
continue;
}
if ($tokens[$i]['level'] !== $scopeLevel) {
continue;
}
$useStatements[] = $i;
}
return $useStatements;
}
/**
* @return list<int>
*/
private static function getAllClassPointers(File $phpcsFile): array
{
$lazyValue = static function () use ($phpcsFile): array {
return TokenHelper::findNextAll($phpcsFile, TokenHelper::$typeWithAnonymousClassKeywordTokenCodes, 0);
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'classPointers', $lazyValue);
}
}
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
/**
* @internal
*/
class Comment
{
/** @var int */
private $pointer;
/** @var string */
private $content;
public function __construct(int $pointer, string $content)
{
$this->pointer = $pointer;
$this->content = $content;
}
public function getPointer(): int
{
return $this->pointer;
}
public function getContent(): string
{
return $this->content;
}
}
@@ -0,0 +1,102 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use function array_key_exists;
use function in_array;
use function preg_match;
use function strpos;
use const T_COMMENT;
/**
* @internal
*/
class CommentHelper
{
public static function isLineComment(File $phpcsFile, int $commentPointer): bool
{
return (bool) preg_match('~^(?://|#)(.*)~', $phpcsFile->getTokens()[$commentPointer]['content']);
}
public static function getCommentEndPointer(File $phpcsFile, int $commentStartPointer): ?int
{
$tokens = $phpcsFile->getTokens();
if (array_key_exists('comment_closer', $tokens[$commentStartPointer])) {
return $tokens[$commentStartPointer]['comment_closer'];
}
if (self::isLineComment($phpcsFile, $commentStartPointer)) {
return $commentStartPointer;
}
if (strpos($tokens[$commentStartPointer]['content'], '/*') !== 0) {
// Part of block comment
return null;
}
$commentEndPointer = $commentStartPointer;
for ($i = $commentStartPointer + 1; $i < $phpcsFile->numTokens; $i++) {
if ($tokens[$i]['code'] === T_COMMENT) {
$commentEndPointer = $i;
continue;
}
if (in_array($tokens[$i]['code'], Tokens::$phpcsCommentTokens, true)) {
$commentEndPointer = $i;
continue;
}
break;
}
return $commentEndPointer;
}
public static function getMultilineCommentStartPointer(File $phpcsFile, int $commentEndPointer): int
{
$tokens = $phpcsFile->getTokens();
$commentStartPointer = $commentEndPointer;
do {
$commentBefore = TokenHelper::findPrevious($phpcsFile, TokenHelper::$inlineCommentTokenCodes, $commentStartPointer - 1);
if ($commentBefore === null) {
break;
}
if ($tokens[$commentBefore]['line'] + 1 !== $tokens[$commentStartPointer]['line']) {
break;
}
/** @var int $commentStartPointer */
$commentStartPointer = $commentBefore;
} while (true);
return $commentStartPointer;
}
public static function getMultilineCommentEndPointer(File $phpcsFile, int $commentStartPointer): int
{
$tokens = $phpcsFile->getTokens();
$commentEndPointer = $commentStartPointer;
do {
$commentAfter = TokenHelper::findNext($phpcsFile, TokenHelper::$inlineCommentTokenCodes, $commentEndPointer + 1);
if ($commentAfter === null) {
break;
}
if ($tokens[$commentAfter]['line'] - 1 !== $tokens[$commentEndPointer]['line']) {
break;
}
/** @var int $commentEndPointer */
$commentEndPointer = $commentAfter;
} while (true);
return $commentEndPointer;
}
}
@@ -0,0 +1,355 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use function array_key_exists;
use function array_merge;
use function count;
use function in_array;
use function preg_replace;
use function sprintf;
use function strtolower;
use function trim;
use const T_BITWISE_AND;
use const T_BOOLEAN_AND;
use const T_BOOLEAN_NOT;
use const T_BOOLEAN_OR;
use const T_CLOSE_PARENTHESIS;
use const T_COALESCE;
use const T_GREATER_THAN;
use const T_INLINE_THEN;
use const T_INSTANCEOF;
use const T_IS_EQUAL;
use const T_IS_GREATER_OR_EQUAL;
use const T_IS_IDENTICAL;
use const T_IS_NOT_EQUAL;
use const T_IS_NOT_IDENTICAL;
use const T_IS_SMALLER_OR_EQUAL;
use const T_LESS_THAN;
use const T_LOGICAL_AND;
use const T_LOGICAL_OR;
use const T_LOGICAL_XOR;
use const T_OPEN_PARENTHESIS;
use const T_PARENT;
use const T_SELF;
use const T_STATIC;
use const T_STRING;
use const T_VARIABLE;
/**
* @internal
*/
class ConditionHelper
{
public static function conditionReturnsBoolean(
File $phpcsFile,
int $conditionBoundaryStartPointer,
int $conditionBoundaryEndPointer
): bool
{
$tokens = $phpcsFile->getTokens();
$conditionContent = strtolower(
trim(TokenHelper::getContent($phpcsFile, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer))
);
if ($conditionContent === 'false' || $conditionContent === 'true') {
return true;
}
$actualPointer = $conditionBoundaryStartPointer;
do {
$actualPointer = TokenHelper::findNext(
$phpcsFile,
array_merge(
[T_OPEN_PARENTHESIS, T_LESS_THAN, T_GREATER_THAN],
Tokens::$booleanOperators,
Tokens::$equalityTokens
),
$actualPointer,
$conditionBoundaryEndPointer + 1
);
if ($actualPointer === null) {
break;
}
if ($tokens[$actualPointer]['code'] === T_OPEN_PARENTHESIS) {
$actualPointer = $tokens[$actualPointer]['parenthesis_closer'];
continue;
}
return true;
} while (true);
return false;
}
public static function getNegativeCondition(
File $phpcsFile,
int $conditionBoundaryStartPointer,
int $conditionBoundaryEndPointer,
bool $nested = false
): string
{
/** @var int $conditionStartPointer */
$conditionStartPointer = TokenHelper::findNextEffective($phpcsFile, $conditionBoundaryStartPointer);
/** @var int $conditionEndPointer */
$conditionEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $conditionBoundaryEndPointer);
$tokens = $phpcsFile->getTokens();
if (
$tokens[$conditionStartPointer]['code'] === T_OPEN_PARENTHESIS
&& $tokens[$conditionStartPointer]['parenthesis_closer'] === $conditionEndPointer
) {
/** @var int $conditionStartPointer */
$conditionStartPointer = TokenHelper::findNextEffective($phpcsFile, $conditionStartPointer + 1);
/** @var int $conditionEndPointer */
$conditionEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $conditionEndPointer - 1);
}
return sprintf(
'%s%s%s',
$conditionBoundaryStartPointer !== $conditionStartPointer
? TokenHelper::getContent(
$phpcsFile,
$conditionBoundaryStartPointer,
$conditionStartPointer - 1
)
: '',
self::getNegativeConditionPart($phpcsFile, $conditionStartPointer, $conditionEndPointer, $nested),
$conditionBoundaryEndPointer !== $conditionEndPointer
? TokenHelper::getContent(
$phpcsFile,
$conditionEndPointer + 1,
$conditionBoundaryEndPointer
)
: ''
);
}
private static function getNegativeConditionPart(
File $phpcsFile,
int $conditionBoundaryStartPointer,
int $conditionBoundaryEndPointer,
bool $nested
): string
{
$tokens = $phpcsFile->getTokens();
$condition = TokenHelper::getContent($phpcsFile, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer);
if (strtolower($condition) === 'true') {
return 'false';
}
if (strtolower($condition) === 'false') {
return 'true';
}
$pointerAfterConditionStart = TokenHelper::findNextEffective($phpcsFile, $conditionBoundaryStartPointer);
$booleanPointers = TokenHelper::findNextAll(
$phpcsFile,
Tokens::$booleanOperators,
$conditionBoundaryStartPointer,
$conditionBoundaryEndPointer + 1
);
if ($tokens[$pointerAfterConditionStart]['code'] === T_BOOLEAN_NOT) {
$pointerAfterBooleanNot = TokenHelper::findNextEffective($phpcsFile, $pointerAfterConditionStart + 1);
if ($tokens[$pointerAfterBooleanNot]['code'] === T_OPEN_PARENTHESIS) {
if ($nested && $booleanPointers !== []) {
return self::removeBooleanNot($condition);
}
$pointerAfterParenthesisCloser = TokenHelper::findNextEffective(
$phpcsFile,
$tokens[$pointerAfterBooleanNot]['parenthesis_closer'] + 1,
$conditionBoundaryEndPointer + 1
);
if (
$pointerAfterParenthesisCloser === null
|| $pointerAfterParenthesisCloser === $conditionBoundaryEndPointer
) {
return TokenHelper::getContent(
$phpcsFile,
$pointerAfterBooleanNot + 1,
$tokens[$pointerAfterBooleanNot]['parenthesis_closer'] - 1
);
}
}
}
if (count($booleanPointers) > 0) {
return self::getNegativeLogicalCondition($phpcsFile, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer);
}
if ($tokens[$pointerAfterConditionStart]['code'] === T_BOOLEAN_NOT) {
return self::removeBooleanNot($condition);
}
if (TokenHelper::findNext(
$phpcsFile,
[T_INSTANCEOF, T_BITWISE_AND, T_COALESCE, T_INLINE_THEN],
$conditionBoundaryStartPointer,
$conditionBoundaryEndPointer + 1
) !== null) {
return sprintf('!(%s)', $condition);
}
if ($tokens[$pointerAfterConditionStart]['code'] === T_STRING) {
$pointerAfterConditionStart = TokenHelper::findNextEffective($phpcsFile, $pointerAfterConditionStart + 1);
if (
$tokens[$pointerAfterConditionStart]['code'] === T_OPEN_PARENTHESIS
&& $tokens[$pointerAfterConditionStart]['parenthesis_closer'] === $conditionBoundaryEndPointer
) {
return sprintf('!%s', $condition);
}
}
if (in_array($tokens[$pointerAfterConditionStart]['code'], [T_VARIABLE, T_SELF, T_STATIC, T_PARENT], true)) {
$identificatorEndPointer = IdentificatorHelper::findEndPointer($phpcsFile, $pointerAfterConditionStart);
$pointerAfterIdentificatorEnd = TokenHelper::findNextEffective($phpcsFile, $identificatorEndPointer + 1);
if (
$tokens[$pointerAfterIdentificatorEnd]['code'] === T_OPEN_PARENTHESIS
&& $tokens[$pointerAfterIdentificatorEnd]['parenthesis_closer'] === $conditionBoundaryEndPointer
) {
return sprintf('!%s', $condition);
}
}
$comparisonPointer = TokenHelper::findNext(
$phpcsFile,
[T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_LESS_THAN, T_GREATER_THAN],
$conditionBoundaryStartPointer,
$conditionBoundaryEndPointer + 1
);
if ($comparisonPointer !== null) {
$comparisonReplacements = [
T_IS_EQUAL => '!=',
T_IS_NOT_EQUAL => '==',
T_IS_IDENTICAL => '!==',
T_IS_NOT_IDENTICAL => '===',
T_IS_GREATER_OR_EQUAL => '<',
T_IS_SMALLER_OR_EQUAL => '>',
T_GREATER_THAN => '<=',
T_LESS_THAN => '>=',
];
$negativeCondition = '';
for ($i = $conditionBoundaryStartPointer; $i <= $conditionBoundaryEndPointer; $i++) {
// Skip calls()
if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) {
$negativeCondition .= TokenHelper::getContent($phpcsFile, $i, $tokens[$i]['parenthesis_closer']);
$i = $tokens[$i]['parenthesis_closer'];
continue;
}
$negativeCondition .= array_key_exists($tokens[$i]['code'], $comparisonReplacements)
? $comparisonReplacements[$tokens[$i]['code']]
: $tokens[$i]['content'];
}
return $negativeCondition;
}
return sprintf('!%s', $condition);
}
private static function removeBooleanNot(string $condition): string
{
return preg_replace('~^!\\s*~', '', $condition);
}
private static function getNegativeLogicalCondition(
File $phpcsFile,
int $conditionBoundaryStartPointer,
int $conditionBoundaryEndPointer
): string
{
if (TokenHelper::findNext($phpcsFile, T_LOGICAL_XOR, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer) !== null) {
return sprintf('!(%s)', TokenHelper::getContent($phpcsFile, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer));
}
$tokens = $phpcsFile->getTokens();
$booleanOperatorReplacements = [
T_BOOLEAN_AND => '||',
T_BOOLEAN_OR => '&&',
T_LOGICAL_AND => 'or',
T_LOGICAL_OR => 'and',
];
$negativeCondition = '';
$nestedConditionStartPointer = $conditionBoundaryStartPointer;
$actualPointer = $conditionBoundaryStartPointer;
$parenthesesLevel = 0;
$operatorsOnLevel = [];
do {
$actualPointer = TokenHelper::findNext(
$phpcsFile,
array_merge([T_OPEN_PARENTHESIS, T_CLOSE_PARENTHESIS], Tokens::$booleanOperators),
$actualPointer,
$conditionBoundaryEndPointer + 1
);
if ($actualPointer === null) {
break;
}
if ($tokens[$actualPointer]['code'] === T_OPEN_PARENTHESIS) {
$pointerBeforeParenthesisOpener = TokenHelper::findPreviousEffective($phpcsFile, $actualPointer - 1);
if ($tokens[$pointerBeforeParenthesisOpener]['code'] === T_STRING) {
$actualPointer = $tokens[$actualPointer]['parenthesis_closer'] + 1;
continue;
}
$parenthesesLevel++;
$actualPointer++;
continue;
}
if ($tokens[$actualPointer]['code'] === T_CLOSE_PARENTHESIS) {
$parenthesesLevel--;
$actualPointer++;
continue;
}
if ($parenthesesLevel !== 0) {
$actualPointer++;
continue;
}
if (
array_key_exists($parenthesesLevel, $operatorsOnLevel)
&& $operatorsOnLevel[$parenthesesLevel] !== $tokens[$actualPointer]['code']
) {
return sprintf('!(%s)', TokenHelper::getContent($phpcsFile, $conditionBoundaryStartPointer, $conditionBoundaryEndPointer));
}
$operatorsOnLevel[$parenthesesLevel] = $tokens[$actualPointer]['code'];
$negativeCondition .= self::getNegativeCondition($phpcsFile, $nestedConditionStartPointer, $actualPointer - 1, true);
$negativeCondition .= $booleanOperatorReplacements[$tokens[$actualPointer]['code']];
$nestedConditionStartPointer = $actualPointer + 1;
$actualPointer++;
} while (true);
return $negativeCondition . self::getNegativeCondition(
$phpcsFile,
$nestedConditionStartPointer,
$conditionBoundaryEndPointer,
true
);
}
}
@@ -0,0 +1,79 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Generator;
use PHP_CodeSniffer\Files\File;
use function array_filter;
use function array_map;
use function array_reverse;
use function iterator_to_array;
use function sprintf;
use const T_CONST;
use const T_NAMESPACE;
use const T_STRING;
/**
* @internal
*/
class ConstantHelper
{
public static function getName(File $phpcsFile, int $constantPointer): string
{
$tokens = $phpcsFile->getTokens();
return $tokens[TokenHelper::findNext($phpcsFile, T_STRING, $constantPointer + 1)]['content'];
}
public static function getFullyQualifiedName(File $phpcsFile, int $constantPointer): string
{
$name = self::getName($phpcsFile, $constantPointer);
$namespace = NamespaceHelper::findCurrentNamespaceName($phpcsFile, $constantPointer);
return $namespace !== null
? sprintf('%s%s%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $namespace, NamespaceHelper::NAMESPACE_SEPARATOR, $name)
: $name;
}
/**
* @return list<string>
*/
public static function getAllNames(File $phpcsFile): array
{
$previousConstantPointer = 0;
return array_map(
static function (int $constantPointer) use ($phpcsFile): string {
return self::getName($phpcsFile, $constantPointer);
},
array_filter(
iterator_to_array(self::getAllConstantPointers($phpcsFile, $previousConstantPointer)),
static function (int $constantPointer) use ($phpcsFile): bool {
foreach (array_reverse($phpcsFile->getTokens()[$constantPointer]['conditions']) as $conditionTokenCode) {
return $conditionTokenCode === T_NAMESPACE;
}
return true;
}
)
);
}
/**
* @return Generator<int>
*/
private static function getAllConstantPointers(File $phpcsFile, int &$previousConstantPointer): Generator
{
do {
$nextConstantPointer = TokenHelper::findNext($phpcsFile, T_CONST, $previousConstantPointer + 1);
if ($nextConstantPointer === null) {
break;
}
$previousConstantPointer = $nextConstantPointer;
yield $nextConstantPointer;
} while (true);
}
}
@@ -0,0 +1,275 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
use PHPStan\PhpDocParser\Parser\ParserException;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use function array_merge;
use function count;
use function in_array;
use function preg_match;
use function sprintf;
use function stripos;
use function strtolower;
use function trim;
use const T_ABSTRACT;
use const T_ATTRIBUTE;
use const T_CLASS;
use const T_CLOSE_CURLY_BRACKET;
use const T_CONST;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_STRING;
use const T_DOC_COMMENT_TAG;
use const T_DOC_COMMENT_WHITESPACE;
use const T_ENUM;
use const T_FINAL;
use const T_FUNCTION;
use const T_INTERFACE;
use const T_OPEN_CURLY_BRACKET;
use const T_PRIVATE;
use const T_PROTECTED;
use const T_PUBLIC;
use const T_READONLY;
use const T_SEMICOLON;
use const T_STATIC;
use const T_TRAIT;
use const T_VAR;
use const T_VARIABLE;
use const T_WHITESPACE;
/**
* @internal
*/
class DocCommentHelper
{
public static function hasDocComment(File $phpcsFile, int $pointer): bool
{
return self::findDocCommentOpenPointer($phpcsFile, $pointer) !== null;
}
public static function getDocComment(File $phpcsFile, int $pointer): ?string
{
$docCommentOpenToken = self::findDocCommentOpenPointer($phpcsFile, $pointer);
if ($docCommentOpenToken === null) {
return null;
}
return trim(
TokenHelper::getContent(
$phpcsFile,
$docCommentOpenToken,
$phpcsFile->getTokens()[$docCommentOpenToken]['comment_closer']
)
);
}
/**
* @return list<Comment>|null
*/
public static function getDocCommentDescription(File $phpcsFile, int $pointer): ?array
{
$docCommentOpenPointer = self::findDocCommentOpenPointer($phpcsFile, $pointer);
if ($docCommentOpenPointer === null) {
return null;
}
$tokens = $phpcsFile->getTokens();
$descriptionStartPointer = TokenHelper::findNextExcluding(
$phpcsFile,
[T_DOC_COMMENT_WHITESPACE, T_DOC_COMMENT_STAR],
$docCommentOpenPointer + 1,
$tokens[$docCommentOpenPointer]['comment_closer']
);
if ($descriptionStartPointer === null) {
return null;
}
if ($tokens[$descriptionStartPointer]['code'] !== T_DOC_COMMENT_STRING) {
return null;
}
$tokenAfterDescriptionPointer = TokenHelper::findNext(
$phpcsFile,
[T_DOC_COMMENT_TAG, T_DOC_COMMENT_CLOSE_TAG],
$descriptionStartPointer + 1,
$tokens[$docCommentOpenPointer]['comment_closer'] + 1
);
/** @var list<Comment> $comments */
$comments = [];
for ($i = $descriptionStartPointer; $i < $tokenAfterDescriptionPointer; $i++) {
if ($tokens[$i]['code'] !== T_DOC_COMMENT_STRING) {
continue;
}
$comments[] = new Comment($i, trim($tokens[$i]['content']));
}
return count($comments) > 0 ? $comments : null;
}
public static function hasInheritdocAnnotation(File $phpcsFile, int $pointer): bool
{
$docCommentOpenPointer = self::findDocCommentOpenPointer($phpcsFile, $pointer);
if ($docCommentOpenPointer === null) {
return false;
}
$parsedDocComment = self::parseDocComment($phpcsFile, $docCommentOpenPointer);
if ($parsedDocComment === null) {
return false;
}
foreach ($parsedDocComment->getNode()->children as $child) {
if ($child instanceof PhpDocTextNode && stripos($child->text, '{@inheritdoc}') !== false) {
return true;
}
if ($child instanceof PhpDocTagNode && strtolower($child->name) === '@inheritdoc') {
return true;
}
}
return false;
}
public static function hasDocCommentDescription(File $phpcsFile, int $pointer): bool
{
return self::getDocCommentDescription($phpcsFile, $pointer) !== null;
}
public static function findDocCommentOpenPointer(File $phpcsFile, int $pointer): ?int
{
return SniffLocalCache::getAndSetIfNotCached(
$phpcsFile,
sprintf('doc-comment-open-pointer-%d', $pointer),
static function () use ($phpcsFile, $pointer): ?int {
$tokens = $phpcsFile->getTokens();
if ($tokens[$pointer]['code'] === T_DOC_COMMENT_OPEN_TAG) {
return $pointer;
}
$found = TokenHelper::findPrevious(
$phpcsFile,
[T_DOC_COMMENT_CLOSE_TAG, T_SEMICOLON, T_CLOSE_CURLY_BRACKET, T_OPEN_CURLY_BRACKET],
$pointer - 1
);
if ($found !== null && $tokens[$found]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
return $tokens[$found]['comment_opener'];
}
return null;
}
);
}
public static function findDocCommentOwnerPointer(File $phpcsFile, int $docCommentOpenPointer): ?int
{
$tokens = $phpcsFile->getTokens();
$docCommentCloserPointer = $tokens[$docCommentOpenPointer]['comment_closer'];
if (self::isInline($phpcsFile, $docCommentOpenPointer)) {
return null;
}
$docCommentOwnerPointer = null;
for ($i = $docCommentCloserPointer + 1; $i < count($tokens); $i++) {
if ($tokens[$i]['code'] === T_ATTRIBUTE) {
$i = $tokens[$i]['attribute_closer'];
continue;
}
if (in_array(
$tokens[$i]['code'],
[T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR, T_READONLY, T_FINAL, T_STATIC, T_ABSTRACT, T_WHITESPACE],
true
)) {
continue;
}
if (in_array(
$tokens[$i]['code'],
array_merge([T_FUNCTION, T_VARIABLE, T_CONST], TokenHelper::$typeKeywordTokenCodes),
true
)) {
$docCommentOwnerPointer = $i;
}
break;
}
return $docCommentOwnerPointer;
}
public static function isInline(File $phpcsFile, int $docCommentOpenPointer): bool
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextNonWhitespace($phpcsFile, $tokens[$docCommentOpenPointer]['comment_closer'] + 1);
if (
$nextPointer !== null
&& in_array(
$tokens[$nextPointer]['code'],
[T_PUBLIC, T_PROTECTED, T_PRIVATE, T_READONLY, T_FINAL, T_STATIC, T_ABSTRACT, T_CONST, T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM],
true
)
) {
return false;
}
$parsedDocComment = self::parseDocComment($phpcsFile, $docCommentOpenPointer);
if ($parsedDocComment === null) {
return false;
}
foreach ($parsedDocComment->getNode()->getTags() as $annotation) {
if (preg_match('~^@(?:(?:phpstan|psalm)-)?var~i', $annotation->name) === 1) {
return true;
}
}
return false;
}
public static function parseDocComment(File $phpcsFile, int $docCommentOpenPointer): ?ParsedDocComment
{
return SniffLocalCache::getAndSetIfNotCached(
$phpcsFile,
sprintf('parsed-doc-comment-%d', $docCommentOpenPointer),
static function () use ($phpcsFile, $docCommentOpenPointer): ?ParsedDocComment {
$docComment = self::getDocComment($phpcsFile, $docCommentOpenPointer);
$docCommentTokens = new TokenIterator(PhpDocParserHelper::getLexer()->tokenize($docComment));
try {
$parsedDocComment = PhpDocParserHelper::getParser()->parse($docCommentTokens);
return new ParsedDocComment(
$docCommentOpenPointer,
$phpcsFile->getTokens()[$docCommentOpenPointer]['comment_closer'],
$parsedDocComment,
$docCommentTokens
);
} catch (ParserException $e) {
return null;
}
}
);
}
}
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Exception;
use Throwable;
use function sprintf;
/**
* @internal
*/
class EmptyFileException extends Exception
{
/** @var string */
private $filename;
public function __construct(string $filename, ?Throwable $previous = null)
{
parent::__construct(sprintf(
'File %s is empty',
$filename
), 0, $previous);
$this->filename = $filename;
}
public function getFilename(): string
{
return $this->filename;
}
}
@@ -0,0 +1,55 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function count;
use function preg_match;
/**
* @internal
*/
class FixerHelper
{
public static function change(File $phpcsFile, int $startPointer, int $endPointer, string $content): void
{
self::removeBetweenIncluding($phpcsFile, $startPointer, $endPointer);
$phpcsFile->fixer->replaceToken($startPointer, $content);
}
public static function removeBetween(File $phpcsFile, int $startPointer, int $endPointer): void
{
self::removeBetweenIncluding($phpcsFile, $startPointer + 1, $endPointer - 1);
}
public static function removeBetweenIncluding(File $phpcsFile, int $startPointer, int $endPointer): void
{
for ($i = $startPointer; $i <= $endPointer; $i++) {
$phpcsFile->fixer->replaceToken($i, '');
}
}
public static function removeWhitespaceBefore(File $phpcsFile, int $pointer): void
{
for ($i = $pointer - 1; $i > 0; $i--) {
if (preg_match('~^\\s+$~', $phpcsFile->fixer->getTokenContent($i)) === 0) {
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
}
public static function removeWhitespaceAfter(File $phpcsFile, int $pointer): void
{
for ($i = $pointer + 1; $i < count($phpcsFile->getTokens()); $i++) {
if (preg_match('~^\\s+$~', $phpcsFile->fixer->getTokenContent($i)) === 0) {
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
}
}
@@ -0,0 +1,572 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Generator;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TypelessParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
use function array_filter;
use function array_map;
use function array_merge;
use function array_pop;
use function array_reverse;
use function in_array;
use function iterator_to_array;
use function preg_match;
use function preg_replace;
use function sprintf;
use function substr_count;
use const T_ANON_CLASS;
use const T_BITWISE_AND;
use const T_CLASS;
use const T_CLOSURE;
use const T_COLON;
use const T_ELLIPSIS;
use const T_ENUM;
use const T_FUNCTION;
use const T_INTERFACE;
use const T_NULLABLE;
use const T_RETURN;
use const T_SEMICOLON;
use const T_STRING;
use const T_TRAIT;
use const T_USE;
use const T_VARIABLE;
use const T_WHITESPACE;
use const T_YIELD;
use const T_YIELD_FROM;
/**
* @internal
*/
class FunctionHelper
{
public const LINE_INCLUDE_COMMENT = 1;
public const LINE_INCLUDE_WHITESPACE = 2;
public const SPECIAL_FUNCTIONS = [
'array_key_exists',
'array_slice',
'assert',
'boolval',
'call_user_func',
'call_user_func_array',
'chr',
'constant',
'count',
'define',
'defined',
'dirname',
'doubleval',
'extension_loaded',
'floatval',
'func_get_args',
'func_num_args',
'function_exists',
'get_called_class',
'get_class',
'gettype',
'in_array',
'ini_get',
'intval',
'is_array',
'is_bool',
'is_callable',
'is_double',
'is_float',
'is_int',
'is_integer',
'is_long',
'is_null',
'is_object',
'is_real',
'is_resource',
'is_scalar',
'is_string',
'ord',
'sizeof',
'strlen',
'strval',
];
public static function getTypeLabel(File $phpcsFile, int $functionPointer): string
{
return self::isMethod($phpcsFile, $functionPointer) ? 'Method' : 'Function';
}
public static function getName(File $phpcsFile, int $functionPointer): string
{
$tokens = $phpcsFile->getTokens();
return $tokens[TokenHelper::findNext(
$phpcsFile,
T_STRING,
$functionPointer + 1,
$tokens[$functionPointer]['parenthesis_opener']
)]['content'];
}
public static function getFullyQualifiedName(File $phpcsFile, int $functionPointer): string
{
$name = self::getName($phpcsFile, $functionPointer);
$namespace = NamespaceHelper::findCurrentNamespaceName($phpcsFile, $functionPointer);
if (self::isMethod($phpcsFile, $functionPointer)) {
foreach (array_reverse(
$phpcsFile->getTokens()[$functionPointer]['conditions'],
true
) as $conditionPointer => $conditionTokenCode) {
if ($conditionTokenCode === T_ANON_CLASS) {
return sprintf('class@anonymous::%s', $name);
}
if (in_array($conditionTokenCode, [T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], true)) {
$name = sprintf(
'%s%s::%s',
NamespaceHelper::NAMESPACE_SEPARATOR,
ClassHelper::getName($phpcsFile, $conditionPointer),
$name
);
break;
}
}
return $namespace !== null ? sprintf('%s%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $namespace, $name) : $name;
}
return $namespace !== null
? sprintf('%s%s%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $namespace, NamespaceHelper::NAMESPACE_SEPARATOR, $name)
: $name;
}
public static function isAbstract(File $phpcsFile, int $functionPointer): bool
{
return !isset($phpcsFile->getTokens()[$functionPointer]['scope_opener']);
}
public static function isMethod(File $phpcsFile, int $functionPointer): bool
{
$functionPointerConditions = $phpcsFile->getTokens()[$functionPointer]['conditions'];
if ($functionPointerConditions === []) {
return false;
}
$lastFunctionPointerCondition = array_pop($functionPointerConditions);
return in_array($lastFunctionPointerCondition, Tokens::$ooScopeTokens, true);
}
public static function findClassPointer(File $phpcsFile, int $functionPointer): ?int
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$functionPointer]['code'] === T_CLOSURE) {
return null;
}
foreach (array_reverse($tokens[$functionPointer]['conditions'], true) as $conditionPointer => $conditionTokenCode) {
if (!in_array($conditionTokenCode, Tokens::$ooScopeTokens, true)) {
continue;
}
return $conditionPointer;
}
return null;
}
/**
* @return list<string>
*/
public static function getParametersNames(File $phpcsFile, int $functionPointer): array
{
$tokens = $phpcsFile->getTokens();
$parametersNames = [];
for ($i = $tokens[$functionPointer]['parenthesis_opener'] + 1; $i < $tokens[$functionPointer]['parenthesis_closer']; $i++) {
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
$parametersNames[] = $tokens[$i]['content'];
}
return $parametersNames;
}
/**
* @return array<string, TypeHint|null>
*/
public static function getParametersTypeHints(File $phpcsFile, int $functionPointer): array
{
$tokens = $phpcsFile->getTokens();
$parametersTypeHints = [];
for ($i = $tokens[$functionPointer]['parenthesis_opener'] + 1; $i < $tokens[$functionPointer]['parenthesis_closer']; $i++) {
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
$parameterName = $tokens[$i]['content'];
$pointerBeforeVariable = TokenHelper::findPreviousExcluding(
$phpcsFile,
array_merge(TokenHelper::$ineffectiveTokenCodes, [T_BITWISE_AND, T_ELLIPSIS]),
$i - 1
);
if (!in_array($tokens[$pointerBeforeVariable]['code'], TokenHelper::getTypeHintTokenCodes(), true)) {
$parametersTypeHints[$parameterName] = null;
continue;
}
$typeHintEndPointer = $pointerBeforeVariable;
$typeHintStartPointer = TypeHintHelper::getStartPointer($phpcsFile, $typeHintEndPointer);
$pointerBeforeTypeHint = TokenHelper::findPreviousEffective($phpcsFile, $typeHintStartPointer - 1);
$isNullable = $tokens[$pointerBeforeTypeHint]['code'] === T_NULLABLE;
if ($isNullable) {
$typeHintStartPointer = $pointerBeforeTypeHint;
}
$typeHint = TokenHelper::getContent($phpcsFile, $typeHintStartPointer, $typeHintEndPointer);
/** @var string $typeHint */
$typeHint = preg_replace('~\s+~', '', $typeHint);
if (!$isNullable) {
$isNullable = preg_match('~(?:^|\|)null(?:\||$)~i', $typeHint) === 1;
}
$parametersTypeHints[$parameterName] = new TypeHint($typeHint, $isNullable, $typeHintStartPointer, $typeHintEndPointer);
}
return $parametersTypeHints;
}
public static function returnsValue(File $phpcsFile, int $functionPointer): bool
{
$tokens = $phpcsFile->getTokens();
$firstPointerInScope = $tokens[$functionPointer]['scope_opener'] + 1;
for ($i = $firstPointerInScope; $i < $tokens[$functionPointer]['scope_closer']; $i++) {
if (!in_array($tokens[$i]['code'], [T_YIELD, T_YIELD_FROM], true)) {
continue;
}
if (!ScopeHelper::isInSameScope($phpcsFile, $i, $firstPointerInScope)) {
continue;
}
return true;
}
for ($i = $firstPointerInScope; $i < $tokens[$functionPointer]['scope_closer']; $i++) {
if ($tokens[$i]['code'] !== T_RETURN) {
continue;
}
if (!ScopeHelper::isInSameScope($phpcsFile, $i, $firstPointerInScope)) {
continue;
}
$nextEffectiveTokenPointer = TokenHelper::findNextEffective($phpcsFile, $i + 1);
return $tokens[$nextEffectiveTokenPointer]['code'] !== T_SEMICOLON;
}
return false;
}
public static function findReturnTypeHint(File $phpcsFile, int $functionPointer): ?TypeHint
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $tokens[$functionPointer]['parenthesis_closer'] + 1);
if ($tokens[$nextPointer]['code'] === T_USE) {
$useParenthesisOpener = TokenHelper::findNextEffective($phpcsFile, $nextPointer + 1);
$colonPointer = TokenHelper::findNextEffective($phpcsFile, $tokens[$useParenthesisOpener]['parenthesis_closer'] + 1);
} else {
$colonPointer = $nextPointer;
}
if ($tokens[$colonPointer]['code'] !== T_COLON) {
return null;
}
$typeHintStartPointer = TokenHelper::findNextEffective($phpcsFile, $colonPointer + 1);
$nullable = $tokens[$typeHintStartPointer]['code'] === T_NULLABLE;
$pointerAfterTypeHint = self::isAbstract($phpcsFile, $functionPointer)
? TokenHelper::findNext($phpcsFile, T_SEMICOLON, $typeHintStartPointer + 1)
: $tokens[$functionPointer]['scope_opener'];
$typeHintEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $pointerAfterTypeHint - 1);
$typeHint = TokenHelper::getContent($phpcsFile, $typeHintStartPointer, $typeHintEndPointer);
/** @var string $typeHint */
$typeHint = preg_replace('~\s+~', '', $typeHint);
if (!$nullable) {
$nullable = preg_match('~(?:^|\|)null(?:\||$)~i', $typeHint) === 1;
}
return new TypeHint($typeHint, $nullable, $typeHintStartPointer, $typeHintEndPointer);
}
public static function hasReturnTypeHint(File $phpcsFile, int $functionPointer): bool
{
return self::findReturnTypeHint($phpcsFile, $functionPointer) !== null;
}
/**
* @return list<Annotation<ParamTagValueNode>|Annotation<TypelessParamTagValueNode>>
*/
public static function getParametersAnnotations(File $phpcsFile, int $functionPointer): array
{
return AnnotationHelper::getAnnotations($phpcsFile, $functionPointer, '@param');
}
/**
* @return array<string, Annotation<VarTagValueNode>|Annotation<ParamTagValueNode>|Annotation<TypelessParamTagValueNode>>
*/
public static function getValidParametersAnnotations(File $phpcsFile, int $functionPointer): array
{
$tokens = $phpcsFile->getTokens();
$parametersAnnotations = [];
if (self::getName($phpcsFile, $functionPointer) === '__construct') {
for ($i = $tokens[$functionPointer]['parenthesis_opener'] + 1; $i < $tokens[$functionPointer]['parenthesis_closer']; $i++) {
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
$varAnnotations = AnnotationHelper::getAnnotations($phpcsFile, $i, '@var');
if ($varAnnotations === []) {
continue;
}
$parametersAnnotations[$tokens[$i]['content']] = $varAnnotations[0];
}
}
foreach (self::getParametersAnnotations($phpcsFile, $functionPointer) as $parameterAnnotation) {
if ($parameterAnnotation->isInvalid()) {
continue;
}
$parametersAnnotations[$parameterAnnotation->getValue()->parameterName] = $parameterAnnotation;
}
return $parametersAnnotations;
}
/**
* @return array<string, Annotation<VarTagValueNode>|Annotation<ParamTagValueNode>>
*/
public static function getValidPrefixedParametersAnnotations(File $phpcsFile, int $functionPointer): array
{
$tokens = $phpcsFile->getTokens();
$parametersAnnotations = [];
foreach (AnnotationHelper::STATIC_ANALYSIS_PREFIXES as $prefix) {
if (self::getName($phpcsFile, $functionPointer) === '__construct') {
for ($i = $tokens[$functionPointer]['parenthesis_opener'] + 1; $i < $tokens[$functionPointer]['parenthesis_closer']; $i++) {
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
/** @var list<Annotation<VarTagValueNode>> $varAnnotations */
$varAnnotations = AnnotationHelper::getAnnotations($phpcsFile, $i, sprintf('@%s-var', $prefix));
if ($varAnnotations === []) {
continue;
}
$parametersAnnotations[$tokens[$i]['content']] = $varAnnotations[0];
}
}
/** @var list<Annotation<ParamTagValueNode>> $annotations */
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $functionPointer, sprintf('@%s-param', $prefix));
foreach ($annotations as $parameterAnnotation) {
if ($parameterAnnotation->isInvalid()) {
continue;
}
$parametersAnnotations[$parameterAnnotation->getValue()->parameterName] = $parameterAnnotation;
}
}
return $parametersAnnotations;
}
/**
* @return Annotation<ReturnTagValueNode>|null
*/
public static function findReturnAnnotation(File $phpcsFile, int $functionPointer): ?Annotation
{
/** @var list<Annotation<ReturnTagValueNode>> $returnAnnotations */
$returnAnnotations = AnnotationHelper::getAnnotations($phpcsFile, $functionPointer, '@return');
if ($returnAnnotations === []) {
return null;
}
return $returnAnnotations[0];
}
/**
* @return list<Annotation>
*/
public static function getValidPrefixedReturnAnnotations(File $phpcsFile, int $functionPointer): array
{
$returnAnnotations = [];
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $functionPointer);
foreach (AnnotationHelper::STATIC_ANALYSIS_PREFIXES as $prefix) {
$prefixedAnnotationName = sprintf('@%s-return', $prefix);
foreach ($annotations as $annotation) {
if ($annotation->isInvalid()) {
continue;
}
if ($annotation->getName() === $prefixedAnnotationName) {
$returnAnnotations[] = $annotation;
}
}
}
return $returnAnnotations;
}
/**
* @return list<string>
*/
public static function getAllFunctionNames(File $phpcsFile): array
{
$previousFunctionPointer = 0;
return array_map(
static function (int $functionPointer) use ($phpcsFile): string {
return self::getName($phpcsFile, $functionPointer);
},
array_filter(
iterator_to_array(self::getAllFunctionOrMethodPointers($phpcsFile, $previousFunctionPointer)),
static function (int $functionOrMethodPointer) use ($phpcsFile): bool {
return !self::isMethod($phpcsFile, $functionOrMethodPointer);
}
)
);
}
/**
* @param int $flags optional bitmask of self::LINE_INCLUDE_* constants
*/
public static function getFunctionLengthInLines(File $file, int $functionPosition, int $flags = 0): int
{
if (self::isAbstract($file, $functionPosition)) {
return 0;
}
return self::getLineCount($file, $functionPosition, $flags);
}
public static function getLineCount(File $file, int $tokenPosition, int $flags = 0): int
{
$includeWhitespace = ($flags & self::LINE_INCLUDE_WHITESPACE) === self::LINE_INCLUDE_WHITESPACE;
$includeComments = ($flags & self::LINE_INCLUDE_COMMENT) === self::LINE_INCLUDE_COMMENT;
$tokens = $file->getTokens();
$token = $tokens[$tokenPosition];
$tokenOpenerPosition = $token['scope_opener'] ?? $tokenPosition;
$tokenCloserPosition = $token['scope_closer'] ?? $file->numTokens - 1;
$tokenOpenerLine = $tokens[$tokenOpenerPosition]['line'];
$tokenCloserLine = $tokens[$tokenCloserPosition]['line'];
$lineCount = 0;
$lastCommentLine = null;
$previousIncludedPosition = null;
for ($position = $tokenOpenerPosition; $position <= $tokenCloserPosition - 1; $position++) {
$token = $tokens[$position];
if ($includeComments === false) {
if (in_array($token['code'], Tokens::$commentTokens, true)) {
if (
$previousIncludedPosition !== null &&
substr_count($token['content'], $file->eolChar) > 0 &&
$token['line'] === $tokens[$previousIncludedPosition]['line']
) {
// Comment with linebreak starting on same line as included Token
$lineCount++;
}
// Don't include comment
$lastCommentLine = $token['line'];
continue;
}
if (
$previousIncludedPosition !== null &&
$token['code'] === T_WHITESPACE &&
$token['line'] === $lastCommentLine &&
$token['line'] !== $tokens[$previousIncludedPosition]['line']
) {
// Whitespace after block comment... still on comment line...
// Ignore along with the comment
continue;
}
}
if ($token['code'] === T_WHITESPACE) {
$nextNonWhitespacePosition = $file->findNext(T_WHITESPACE, $position + 1, $tokenCloserPosition + 1, true);
if (
$includeWhitespace === false &&
$token['column'] === 1 &&
$nextNonWhitespacePosition !== false &&
$tokens[$nextNonWhitespacePosition]['line'] !== $token['line']
) {
// This line is nothing but whitepace
$position = $nextNonWhitespacePosition - 1;
continue;
}
if ($previousIncludedPosition === $tokenOpenerPosition && $token['line'] === $tokenOpenerLine) {
// Don't linclude line break after opening "{"
// Unless there was code or an (included) comment following the "{"
continue;
}
}
if ($token['code'] !== T_WHITESPACE) {
$previousIncludedPosition = $position;
}
$newLineFoundCount = substr_count($token['content'], $file->eolChar);
$lineCount += $newLineFoundCount;
}
if ($tokens[$previousIncludedPosition]['line'] === $tokenCloserLine) {
// There is code or comment on the closing "}" line...
$lineCount++;
}
return $lineCount;
}
/**
* @return Generator<int>
*/
private static function getAllFunctionOrMethodPointers(File $phpcsFile, int &$previousFunctionPointer): Generator
{
do {
$nextFunctionPointer = TokenHelper::findNext($phpcsFile, T_FUNCTION, $previousFunctionPointer + 1);
if ($nextFunctionPointer === null) {
break;
}
$previousFunctionPointer = $nextFunctionPointer;
yield $nextFunctionPointer;
} while (true);
}
}
@@ -0,0 +1,216 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function array_merge;
use function in_array;
use const T_CLOSE_CURLY_BRACKET;
use const T_CLOSE_PARENTHESIS;
use const T_CLOSE_SQUARE_BRACKET;
use const T_DOLLAR;
use const T_DOUBLE_COLON;
use const T_NULLSAFE_OBJECT_OPERATOR;
use const T_OBJECT_OPERATOR;
use const T_OPEN_CURLY_BRACKET;
use const T_OPEN_SQUARE_BRACKET;
use const T_PARENT;
use const T_SELF;
use const T_STATIC;
use const T_VARIABLE;
/**
* @internal
*/
class IdentificatorHelper
{
public static function getContent(File $phpcsFile, int $startPointer, int $endPointer): string
{
$tokens = $phpcsFile->getTokens();
$variableContent = '';
for ($i = $startPointer; $i <= $endPointer; $i++) {
if (in_array($tokens[$i]['code'], TokenHelper::$ineffectiveTokenCodes, true)) {
continue;
}
$variableContent .= $tokens[$i]['content'];
}
return $variableContent;
}
public static function findStartPointer(File $phpcsFile, int $endPointer): ?int
{
$tokens = $phpcsFile->getTokens();
if (in_array($tokens[$endPointer]['code'], TokenHelper::getNameTokenCodes(), true)) {
/** @var int $previousPointer */
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $endPointer - 1);
if (in_array($tokens[$previousPointer]['code'], [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_DOUBLE_COLON], true)) {
$pointerBeforeOperator = TokenHelper::findPreviousEffective($phpcsFile, $previousPointer - 1);
if ($tokens[$pointerBeforeOperator]['code'] !== T_CLOSE_PARENTHESIS) {
return self::getStartPointerBeforeOperator($phpcsFile, $previousPointer);
}
}
return $endPointer;
}
if (in_array($tokens[$endPointer]['code'], [T_CLOSE_CURLY_BRACKET, T_CLOSE_SQUARE_BRACKET], true)) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $tokens[$endPointer]['bracket_opener']);
}
if ($tokens[$endPointer]['code'] === T_VARIABLE) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $endPointer);
}
return null;
}
public static function findEndPointer(File $phpcsFile, int $startPointer): ?int
{
$tokens = $phpcsFile->getTokens();
$nameTokenCodes = TokenHelper::getNameTokenCodes();
if (in_array($tokens[$startPointer]['code'], $nameTokenCodes, true)) {
$startPointer = TokenHelper::findNextExcluding($phpcsFile, $nameTokenCodes, $startPointer + 1) - 1;
} elseif ($tokens[$startPointer]['code'] === T_DOLLAR) {
$startPointer = TokenHelper::findNextEffective($phpcsFile, $startPointer + 1);
}
/** @var int $nextPointer */
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $startPointer + 1);
if (
in_array($tokens[$startPointer]['code'], array_merge([T_SELF, T_STATIC, T_PARENT], $nameTokenCodes), true)
&& $tokens[$nextPointer]['code'] === T_DOUBLE_COLON
) {
return self::getEndPointerAfterOperator($phpcsFile, $nextPointer);
}
if ($tokens[$startPointer]['code'] === T_VARIABLE) {
if (in_array($tokens[$nextPointer]['code'], [T_DOUBLE_COLON, T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR], true)) {
return self::getEndPointerAfterOperator($phpcsFile, $nextPointer);
}
if ($tokens[$nextPointer]['code'] === T_OPEN_SQUARE_BRACKET) {
return self::getEndPointerAfterVariablePart($phpcsFile, $startPointer);
}
return $startPointer;
}
return null;
}
private static function getStartPointerBeforeOperator(File $phpcsFile, int $operatorPointer): int
{
$tokens = $phpcsFile->getTokens();
$nameTokenCodes = TokenHelper::getNameTokenCodes();
/** @var int $previousPointer */
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $operatorPointer - 1);
if (in_array($tokens[$previousPointer]['code'], $nameTokenCodes, true)) {
$previousPointer = TokenHelper::findPreviousExcluding($phpcsFile, $nameTokenCodes, $previousPointer - 1) + 1;
}
if (
$tokens[$operatorPointer]['code'] === T_DOUBLE_COLON
&& in_array($tokens[$previousPointer]['code'], array_merge([T_SELF, T_STATIC, T_PARENT], $nameTokenCodes), true)
) {
return $previousPointer;
}
if (in_array($tokens[$previousPointer]['code'], $nameTokenCodes, true)) {
/** @var int $possibleOperatorPointer */
$possibleOperatorPointer = TokenHelper::findPreviousEffective($phpcsFile, $previousPointer - 1);
if (in_array($tokens[$possibleOperatorPointer]['code'], [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR], true)) {
return self::getStartPointerBeforeOperator($phpcsFile, $possibleOperatorPointer);
}
}
if (in_array($tokens[$previousPointer]['code'], [T_CLOSE_CURLY_BRACKET, T_CLOSE_SQUARE_BRACKET], true)) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $tokens[$previousPointer]['bracket_opener']);
}
return self::getStartPointerBeforeVariablePart($phpcsFile, $previousPointer);
}
private static function getStartPointerBeforeVariablePart(File $phpcsFile, int $variablePartPointer): int
{
$tokens = $phpcsFile->getTokens();
/** @var int $previousPointer */
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $variablePartPointer - 1);
if ($tokens[$previousPointer]['code'] === T_DOLLAR) {
/** @var int $previousPointer */
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $previousPointer - 1);
}
if (in_array($tokens[$previousPointer]['code'], [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_DOUBLE_COLON], true)) {
return self::getStartPointerBeforeOperator($phpcsFile, $previousPointer);
}
if ($tokens[$previousPointer]['code'] === T_CLOSE_SQUARE_BRACKET) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $tokens[$previousPointer]['bracket_opener']);
}
if (
$tokens[$previousPointer]['code'] === T_CLOSE_CURLY_BRACKET
&& !array_key_exists('scope_condition', $tokens[$previousPointer])
) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $tokens[$previousPointer]['bracket_opener']);
}
if (in_array($tokens[$previousPointer]['code'], array_merge([T_VARIABLE], TokenHelper::getNameTokenCodes()), true)) {
return self::getStartPointerBeforeVariablePart($phpcsFile, $previousPointer);
}
return $variablePartPointer;
}
private static function getEndPointerAfterOperator(File $phpcsFile, int $operatorPointer): int
{
$tokens = $phpcsFile->getTokens();
/** @var int $nextPointer */
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $operatorPointer + 1);
if ($tokens[$nextPointer]['code'] === T_DOLLAR) {
/** @var int $nextPointer */
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $nextPointer + 1);
}
if ($tokens[$nextPointer]['code'] === T_OPEN_CURLY_BRACKET) {
return self::getEndPointerAfterVariablePart($phpcsFile, $tokens[$nextPointer]['bracket_closer']);
}
return self::getEndPointerAfterVariablePart($phpcsFile, $nextPointer);
}
private static function getEndPointerAfterVariablePart(File $phpcsFile, int $variablePartPointer): int
{
$tokens = $phpcsFile->getTokens();
/** @var int $nextPointer */
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $variablePartPointer + 1);
if (in_array($tokens[$nextPointer]['code'], [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_DOUBLE_COLON], true)) {
return self::getEndPointerAfterOperator($phpcsFile, $nextPointer);
}
if ($tokens[$nextPointer]['code'] === T_OPEN_SQUARE_BRACKET) {
return self::getEndPointerAfterVariablePart($phpcsFile, $tokens[$nextPointer]['bracket_closer']);
}
return $variablePartPointer;
}
}
@@ -0,0 +1,106 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function in_array;
use function ltrim;
use function preg_replace_callback;
use function rtrim;
use function str_repeat;
use function strlen;
use function substr;
use const T_END_HEREDOC;
use const T_END_NOWDOC;
use const T_START_HEREDOC;
use const T_START_NOWDOC;
/**
* @internal
*/
class IndentationHelper
{
public const DEFAULT_INDENTATION_WIDTH = 4;
public const TAB_INDENT = "\t";
public const SPACES_INDENT = ' ';
public static function getIndentation(File $phpcsFile, int $pointer): string
{
$firstPointerOnLine = TokenHelper::findFirstTokenOnLine($phpcsFile, $pointer);
return TokenHelper::getContent($phpcsFile, $firstPointerOnLine, $pointer - 1);
}
public static function addIndentation(string $indentation, int $level = 1): string
{
$whitespace = self::getOneIndentationLevel($indentation);
return $indentation . str_repeat($whitespace, $level);
}
public static function getOneIndentationLevel(string $indentation): string
{
return $indentation === ''
? self::TAB_INDENT
: ($indentation[0] === self::TAB_INDENT ? self::TAB_INDENT : self::SPACES_INDENT);
}
/**
* @param list<int> $codePointers
*/
public static function fixIndentation(File $phpcsFile, array $codePointers, string $defaultIndentation): string
{
$tokens = $phpcsFile->getTokens();
$eolLength = strlen($phpcsFile->eolChar);
$code = '';
$inHeredoc = false;
foreach ($codePointers as $no => $codePointer) {
$content = $tokens[$codePointer]['content'];
if (
!$inHeredoc
&& (
$no === 0
|| substr($tokens[$codePointer - 1]['content'], -$eolLength) === $phpcsFile->eolChar
)
) {
if ($content === $phpcsFile->eolChar) {
// Nothing
} elseif ($content[0] === self::TAB_INDENT) {
$content = substr($content, 1);
} elseif (substr($content, 0, self::DEFAULT_INDENTATION_WIDTH) === self::SPACES_INDENT) {
$content = substr($content, self::DEFAULT_INDENTATION_WIDTH);
} else {
$content = $defaultIndentation . ltrim($content);
}
}
if (in_array($tokens[$codePointer]['code'], [T_START_HEREDOC, T_START_NOWDOC], true)) {
$inHeredoc = true;
} elseif (in_array($tokens[$codePointer]['code'], [T_END_HEREDOC, T_END_NOWDOC], true)) {
$inHeredoc = false;
}
$code .= $content;
}
return rtrim($code);
}
public static function convertTabsToSpaces(File $phpcsFile, string $code): string
{
return preg_replace_callback('~^(\t+)~', static function (array $matches) use ($phpcsFile): string {
$indentation = str_repeat(
' ',
$phpcsFile->config->tabWidth !== 0 ? $phpcsFile->config->tabWidth : self::DEFAULT_INDENTATION_WIDTH
);
return str_repeat($indentation, strlen($matches[1]));
}, $code);
}
}
@@ -0,0 +1,201 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_filter;
use function array_reverse;
use function array_slice;
use function array_values;
use function count;
use function defined;
use function explode;
use function implode;
use function in_array;
use function ltrim;
use function sprintf;
use function strpos;
use const T_NAME_FULLY_QUALIFIED;
use const T_NAMESPACE;
use const T_NS_SEPARATOR;
/**
* Terms "unqualified", "qualified" and "fully qualified" have the same meaning as described here:
* http://php.net/manual/en/language.namespaces.rules.php
*
* "Canonical" is a fully qualified name without the leading backslash.
*
* @internal
*/
class NamespaceHelper
{
public const NAMESPACE_SEPARATOR = '\\';
/**
* @return list<int>
*/
public static function getAllNamespacesPointers(File $phpcsFile): array
{
$tokens = $phpcsFile->getTokens();
$lazyValue = static function () use ($phpcsFile, $tokens): array {
$all = TokenHelper::findNextAll($phpcsFile, T_NAMESPACE, 0);
$all = array_filter(
$all,
static function ($pointer) use ($phpcsFile, $tokens) {
$next = TokenHelper::findNextEffective($phpcsFile, $pointer + 1);
return $next === null || $tokens[$next]['code'] !== T_NS_SEPARATOR;
}
);
return array_values($all);
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'namespacePointers', $lazyValue);
}
public static function isFullyQualifiedName(string $typeName): bool
{
return StringHelper::startsWith($typeName, self::NAMESPACE_SEPARATOR);
}
public static function isFullyQualifiedPointer(File $phpcsFile, int $pointer): bool
{
return in_array($phpcsFile->getTokens()[$pointer]['code'], [T_NS_SEPARATOR, T_NAME_FULLY_QUALIFIED], true);
}
public static function getFullyQualifiedTypeName(string $typeName): string
{
if (self::isFullyQualifiedName($typeName)) {
return $typeName;
}
return sprintf('%s%s', self::NAMESPACE_SEPARATOR, $typeName);
}
public static function hasNamespace(string $typeName): bool
{
$parts = self::getNameParts($typeName);
return count($parts) > 1;
}
/**
* @return list<string>
*/
public static function getNameParts(string $name): array
{
$name = self::normalizeToCanonicalName($name);
return explode(self::NAMESPACE_SEPARATOR, $name);
}
public static function getLastNamePart(string $name): string
{
return array_slice(self::getNameParts($name), -1)[0];
}
public static function getName(File $phpcsFile, int $namespacePointer): string
{
/** @var int $namespaceNameStartPointer */
$namespaceNameStartPointer = TokenHelper::findNextEffective($phpcsFile, $namespacePointer + 1);
$namespaceNameEndPointer = TokenHelper::findNextExcluding(
$phpcsFile,
TokenHelper::getNameTokenCodes(),
$namespaceNameStartPointer + 1
) - 1;
return TokenHelper::getContent($phpcsFile, $namespaceNameStartPointer, $namespaceNameEndPointer);
}
public static function findCurrentNamespacePointer(File $phpcsFile, int $pointer): ?int
{
$allNamespacesPointers = array_reverse(self::getAllNamespacesPointers($phpcsFile));
foreach ($allNamespacesPointers as $namespacesPointer) {
if ($namespacesPointer < $pointer) {
return $namespacesPointer;
}
}
return null;
}
public static function findCurrentNamespaceName(File $phpcsFile, int $anyPointer): ?string
{
$namespacePointer = self::findCurrentNamespacePointer($phpcsFile, $anyPointer);
if ($namespacePointer === null) {
return null;
}
return self::getName($phpcsFile, $namespacePointer);
}
public static function getUnqualifiedNameFromFullyQualifiedName(string $name): string
{
$parts = self::getNameParts($name);
return $parts[count($parts) - 1];
}
public static function isQualifiedName(string $name): bool
{
return strpos($name, self::NAMESPACE_SEPARATOR) !== false;
}
public static function normalizeToCanonicalName(string $fullyQualifiedName): string
{
return ltrim($fullyQualifiedName, self::NAMESPACE_SEPARATOR);
}
public static function isTypeInNamespace(string $typeName, string $namespace): bool
{
return StringHelper::startsWith(
self::normalizeToCanonicalName($typeName) . '\\',
$namespace . '\\'
);
}
public static function resolveClassName(File $phpcsFile, string $nameAsReferencedInFile, int $currentPointer): string
{
return self::resolveName($phpcsFile, $nameAsReferencedInFile, ReferencedName::TYPE_CLASS, $currentPointer);
}
public static function resolveName(File $phpcsFile, string $nameAsReferencedInFile, string $type, int $currentPointer): string
{
if (self::isFullyQualifiedName($nameAsReferencedInFile)) {
return $nameAsReferencedInFile;
}
$useStatements = UseStatementHelper::getUseStatementsForPointer($phpcsFile, $currentPointer);
$uniqueId = UseStatement::getUniqueId($type, self::normalizeToCanonicalName($nameAsReferencedInFile));
if (isset($useStatements[$uniqueId])) {
return sprintf('%s%s', self::NAMESPACE_SEPARATOR, $useStatements[$uniqueId]->getFullyQualifiedTypeName());
}
$nameParts = self::getNameParts($nameAsReferencedInFile);
$firstPartUniqueId = UseStatement::getUniqueId($type, $nameParts[0]);
if (count($nameParts) > 1 && isset($useStatements[$firstPartUniqueId])) {
return sprintf(
'%s%s%s%s',
self::NAMESPACE_SEPARATOR,
$useStatements[$firstPartUniqueId]->getFullyQualifiedTypeName(),
self::NAMESPACE_SEPARATOR,
implode(self::NAMESPACE_SEPARATOR, array_slice($nameParts, 1))
);
}
$name = sprintf('%s%s', self::NAMESPACE_SEPARATOR, $nameAsReferencedInFile);
if ($type === ReferencedName::TYPE_CONSTANT && defined($name)) {
return $name;
}
$namespaceName = self::findCurrentNamespaceName($phpcsFile, $currentPointer);
if ($namespaceName !== null) {
$name = sprintf('%s%s%s', self::NAMESPACE_SEPARATOR, $namespaceName, $name);
}
return $name;
}
}
@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function array_keys;
use function array_reverse;
use function in_array;
/**
* @internal
*/
class ParameterHelper
{
public static function isParameter(File $phpcsFile, int $variablePointer): bool
{
$tokens = $phpcsFile->getTokens();
if (!array_key_exists('nested_parenthesis', $tokens[$variablePointer])) {
return false;
}
$parenthesisOpenerPointer = array_reverse(array_keys($tokens[$variablePointer]['nested_parenthesis']))[0];
if (!array_key_exists('parenthesis_owner', $tokens[$parenthesisOpenerPointer])) {
return false;
}
$parenthesisOwnerPointer = $tokens[$parenthesisOpenerPointer]['parenthesis_owner'];
return in_array($tokens[$parenthesisOwnerPointer]['code'], TokenHelper::$functionTokenCodes, true);
}
}
@@ -0,0 +1,108 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\Attribute;
use PHPStan\PhpDocParser\Ast\Node;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use function array_merge;
use function count;
use function strlen;
use function trim;
use const T_DOC_COMMENT_STRING;
/**
* @internal
*/
class ParsedDocComment
{
/** @var int */
private $openPointer;
/** @var int */
private $closePointer;
/** @var PhpDocNode */
private $node;
/** @var TokenIterator */
private $tokens;
public function __construct(int $openPointer, int $closePointer, PhpDocNode $node, TokenIterator $tokens)
{
$this->openPointer = $openPointer;
$this->closePointer = $closePointer;
$this->node = $node;
$this->tokens = $tokens;
}
public function getOpenPointer(): int
{
return $this->openPointer;
}
public function getClosePointer(): int
{
return $this->closePointer;
}
public function getNode(): PhpDocNode
{
return $this->node;
}
public function getTokens(): TokenIterator
{
return $this->tokens;
}
public function getNodeStartPointer(File $phpcsFile, Node $node): int
{
$tokens = $phpcsFile->getTokens();
$tagStartLine = $tokens[$this->openPointer]['line'] + $node->getAttribute('startLine') - 1;
$searchPointer = $this->openPointer + 1;
for ($i = $this->openPointer + 1; $i < $this->closePointer; $i++) {
if ($tagStartLine === $tokens[$i]['line']) {
$searchPointer = $i;
break;
}
}
return TokenHelper::findNext($phpcsFile, array_merge(TokenHelper::$annotationTokenCodes, [T_DOC_COMMENT_STRING]), $searchPointer);
}
public function getNodeEndPointer(File $phpcsFile, Node $node, int $nodeStartPointer): int
{
$tokens = $phpcsFile->getTokens();
$content = trim($this->tokens->getContentBetween(
$node->getAttribute(Attribute::START_INDEX),
$node->getAttribute(Attribute::END_INDEX) + 1
));
$length = strlen($content);
$searchPointer = $nodeStartPointer;
$content = '';
for ($i = $nodeStartPointer; $i < count($tokens); $i++) {
$content .= $tokens[$i]['content'];
if (strlen($content) >= $length) {
$searchPointer = $i;
break;
}
}
return TokenHelper::findPrevious(
$phpcsFile,
array_merge(TokenHelper::$annotationTokenCodes, [T_DOC_COMMENT_STRING]),
$searchPointer
);
}
}
@@ -0,0 +1,82 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHPStan\PhpDocParser\Ast\Node;
use PHPStan\PhpDocParser\Ast\NodeTraverser;
use PHPStan\PhpDocParser\Ast\NodeVisitor\CloningVisitor;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TypeParser;
use PHPStan\PhpDocParser\Printer\Printer;
/**
* @internal
*/
class PhpDocParserHelper
{
public static function getLexer(): Lexer
{
static $lexer;
if ($lexer === null) {
$lexer = new Lexer(true);
}
return $lexer;
}
public static function getParser(): PhpDocParser
{
static $parser;
if ($parser === null) {
$usedAttributes = ['lines' => true, 'indexes' => true];
$constantExpressionParser = new ConstExprParser(true, true, $usedAttributes);
$parser = new PhpDocParser(
new TypeParser($constantExpressionParser, true, $usedAttributes),
$constantExpressionParser,
true,
true,
$usedAttributes,
true,
true
);
}
return $parser;
}
public static function getPrinter(): Printer
{
static $printer;
if ($printer === null) {
$printer = new Printer();
}
return $printer;
}
/**
* @template T of Node
* @param T $node
* @return T
*/
public static function cloneNode(Node $node): Node
{
static $cloningTraverser;
if ($cloningTraverser === null) {
$cloningTraverser = new NodeTraverser([new CloningVisitor()]);
}
[$cloneNode] = $cloningTraverser->traverse([$node]);
return $cloneNode;
}
}
@@ -0,0 +1,140 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function array_reverse;
use function array_values;
use function count;
use function in_array;
use function preg_match;
use function preg_replace;
use function sprintf;
use const T_ANON_CLASS;
use const T_CLOSE_CURLY_BRACKET;
use const T_FUNCTION;
use const T_NULLABLE;
use const T_OPEN_CURLY_BRACKET;
use const T_PRIVATE;
use const T_PROTECTED;
use const T_PUBLIC;
use const T_READONLY;
use const T_SEMICOLON;
use const T_STATIC;
use const T_VAR;
/**
* @internal
*/
class PropertyHelper
{
public static function isProperty(File $phpcsFile, int $variablePointer, bool $promoted = false): bool
{
$tokens = $phpcsFile->getTokens();
$previousPointer = TokenHelper::findPreviousExcluding(
$phpcsFile,
array_merge(TokenHelper::$ineffectiveTokenCodes, TokenHelper::getTypeHintTokenCodes(), [T_NULLABLE]),
$variablePointer - 1
);
if ($tokens[$previousPointer]['code'] === T_STATIC) {
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $previousPointer - 1);
}
if (in_array($tokens[$previousPointer]['code'], [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_VAR, T_READONLY], true)) {
$constructorPointer = TokenHelper::findPrevious($phpcsFile, T_FUNCTION, $previousPointer - 1);
if ($constructorPointer === null) {
return true;
}
return $tokens[$constructorPointer]['parenthesis_closer'] < $previousPointer || $promoted;
}
if (
!array_key_exists('conditions', $tokens[$variablePointer])
|| count($tokens[$variablePointer]['conditions']) === 0
) {
return false;
}
$functionPointer = TokenHelper::findPrevious(
$phpcsFile,
array_merge(TokenHelper::$functionTokenCodes, [T_SEMICOLON, T_CLOSE_CURLY_BRACKET, T_OPEN_CURLY_BRACKET]),
$variablePointer - 1
);
if (
$functionPointer !== null
&& in_array($tokens[$functionPointer]['code'], TokenHelper::$functionTokenCodes, true)
) {
return false;
}
$conditionCode = array_values($tokens[$variablePointer]['conditions'])[count($tokens[$variablePointer]['conditions']) - 1];
return in_array($conditionCode, Tokens::$ooScopeTokens, true);
}
public static function findTypeHint(File $phpcsFile, int $propertyPointer): ?TypeHint
{
$tokens = $phpcsFile->getTokens();
$propertyStartPointer = TokenHelper::findPrevious(
$phpcsFile,
[T_PRIVATE, T_PROTECTED, T_PUBLIC, T_VAR, T_STATIC, T_READONLY],
$propertyPointer - 1
);
$typeHintEndPointer = TokenHelper::findPrevious(
$phpcsFile,
TokenHelper::getTypeHintTokenCodes(),
$propertyPointer - 1,
$propertyStartPointer
);
if ($typeHintEndPointer === null) {
return null;
}
$typeHintStartPointer = TypeHintHelper::getStartPointer($phpcsFile, $typeHintEndPointer);
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $typeHintStartPointer - 1, $propertyStartPointer);
$nullable = $previousPointer !== null && $tokens[$previousPointer]['code'] === T_NULLABLE;
if ($nullable) {
$typeHintStartPointer = $previousPointer;
}
$typeHint = TokenHelper::getContent($phpcsFile, $typeHintStartPointer, $typeHintEndPointer);
if (!$nullable) {
$nullable = preg_match('~(?:^|\|\s*)null(?:\s*\||$)~i', $typeHint) === 1;
}
/** @var string $typeHint */
$typeHint = preg_replace('~\s+~', '', $typeHint);
return new TypeHint($typeHint, $nullable, $typeHintStartPointer, $typeHintEndPointer);
}
public static function getFullyQualifiedName(File $phpcsFile, int $propertyPointer): string
{
$propertyToken = $phpcsFile->getTokens()[$propertyPointer];
$propertyName = $propertyToken['content'];
$classPointer = array_reverse(array_keys($propertyToken['conditions']))[0];
if ($phpcsFile->getTokens()[$classPointer]['code'] === T_ANON_CLASS) {
return sprintf('class@anonymous::%s', $propertyName);
}
$name = sprintf('%s%s::%s', NamespaceHelper::NAMESPACE_SEPARATOR, ClassHelper::getName($phpcsFile, $classPointer), $propertyName);
$namespace = NamespaceHelper::findCurrentNamespaceName($phpcsFile, $propertyPointer);
return $namespace !== null ? sprintf('%s%s%s', NamespaceHelper::NAMESPACE_SEPARATOR, $namespace, $name) : $name;
}
}
@@ -0,0 +1,75 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
/**
* @internal
*/
class ReferencedName
{
public const TYPE_CLASS = 'class';
public const TYPE_FUNCTION = 'function';
public const TYPE_CONSTANT = 'constant';
/** @var string */
private $nameAsReferencedInFile;
/** @var int */
private $startPointer;
/** @var int */
private $endPointer;
/** @var string */
private $type;
public function __construct(string $nameAsReferencedInFile, int $startPointer, int $endPointer, string $type)
{
$this->nameAsReferencedInFile = $nameAsReferencedInFile;
$this->startPointer = $startPointer;
$this->endPointer = $endPointer;
$this->type = $type;
}
public function getNameAsReferencedInFile(): string
{
return $this->nameAsReferencedInFile;
}
public function getStartPointer(): int
{
return $this->startPointer;
}
public function getType(): string
{
return $this->type;
}
public function getEndPointer(): int
{
return $this->endPointer;
}
public function isClass(): bool
{
return $this->type === self::TYPE_CLASS;
}
public function isConstant(): bool
{
return $this->type === self::TYPE_CONSTANT;
}
public function isFunction(): bool
{
return $this->type === self::TYPE_FUNCTION;
}
public function hasSameUseStatementType(UseStatement $useStatement): bool
{
return $this->getType() === $useStatement->getType();
}
}
@@ -0,0 +1,532 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use function array_merge;
use function array_reverse;
use function array_values;
use function count;
use function in_array;
use function is_array;
use function token_get_all;
use const T_ANON_CLASS;
use const T_ARRAY;
use const T_AS;
use const T_ATTRIBUTE;
use const T_BITWISE_AND;
use const T_BITWISE_OR;
use const T_CATCH;
use const T_CLASS;
use const T_CLOSE_PARENTHESIS;
use const T_COLON;
use const T_COMMA;
use const T_CONST;
use const T_DECLARE;
use const T_DOUBLE_COLON;
use const T_DOUBLE_QUOTED_STRING;
use const T_ELLIPSIS;
use const T_ENUM;
use const T_ENUM_CASE;
use const T_EXTENDS;
use const T_FUNCTION;
use const T_GOTO;
use const T_HEREDOC;
use const T_IMPLEMENTS;
use const T_INSTANCEOF;
use const T_NAME_FULLY_QUALIFIED;
use const T_NAME_QUALIFIED;
use const T_NAME_RELATIVE;
use const T_NAMESPACE;
use const T_NEW;
use const T_NS_SEPARATOR;
use const T_NULLABLE;
use const T_NULLSAFE_OBJECT_OPERATOR;
use const T_OBJECT_OPERATOR;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_OPEN_TAG;
use const T_PARAM_NAME;
use const T_STRING;
use const T_TRAIT;
use const T_TYPE_INTERSECTION;
use const T_TYPE_UNION;
use const T_USE;
use const T_VARIABLE;
use const T_WHITESPACE;
/**
* @internal
*/
class ReferencedNameHelper
{
/**
* @return list<ReferencedName>
*/
public static function getAllReferencedNames(File $phpcsFile, int $openTagPointer): array
{
$lazyValue = static function () use ($phpcsFile, $openTagPointer): array {
return self::createAllReferencedNames($phpcsFile, $openTagPointer);
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'references', $lazyValue);
}
/**
* @return list<ReferencedName>
*/
public static function getAllReferencedNamesInAttributes(File $phpcsFile, int $openTagPointer): array
{
$lazyValue = static function () use ($phpcsFile, $openTagPointer): array {
return self::createAllReferencedNamesInAttributes($phpcsFile, $openTagPointer);
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'referencesFromAttributes', $lazyValue);
}
public static function getReferenceName(File $phpcsFile, int $nameStartPointer, int $nameEndPointer): string
{
$tokens = $phpcsFile->getTokens();
$referencedName = '';
for ($i = $nameStartPointer; $i <= $nameEndPointer; $i++) {
if (in_array($tokens[$i]['code'], Tokens::$emptyTokens, true)) {
continue;
}
$referencedName .= $tokens[$i]['content'];
}
return $referencedName;
}
public static function getReferencedNameEndPointer(File $phpcsFile, int $startPointer): int
{
$tokens = $phpcsFile->getTokens();
$nameTokenCodes = TokenHelper::getNameTokenCodes();
$nameTokenCodesWithWhitespace = array_merge($nameTokenCodes, Tokens::$emptyTokens);
$lastNamePointer = $startPointer;
for ($i = $startPointer + 1; $i < count($tokens); $i++) {
if (!in_array($tokens[$i]['code'], $nameTokenCodesWithWhitespace, true)) {
break;
}
if (!in_array($tokens[$i]['code'], $nameTokenCodes, true)) {
continue;
}
$lastNamePointer = $i;
}
return $lastNamePointer;
}
/**
* @return list<ReferencedName>
*/
private static function createAllReferencedNames(File $phpcsFile, int $openTagPointer): array
{
$referencedNames = [];
$beginSearchAtPointer = $openTagPointer + 1;
$nameTokenCodes = TokenHelper::getNameTokenCodes();
$nameTokenCodes[] = T_DOUBLE_QUOTED_STRING;
$nameTokenCodes[] = T_HEREDOC;
$tokens = $phpcsFile->getTokens();
while (true) {
$nameStartPointer = TokenHelper::findNext($phpcsFile, $nameTokenCodes, $beginSearchAtPointer);
if ($nameStartPointer === null) {
break;
}
// Find referenced names inside double quotes string
if (self::isNeedParsedContent($tokens[$nameStartPointer]['code'])) {
$content = $tokens[$nameStartPointer]['content'];
$currentPointer = $nameStartPointer + 1;
while (self::isNeedParsedContent($tokens[$currentPointer]['code'])) {
$content .= $tokens[$currentPointer]['content'];
$currentPointer++;
}
$names = self::getReferencedNamesFromString($content);
foreach ($names as $name) {
$referencedNames[] = new ReferencedName($name, $nameStartPointer, $nameStartPointer, ReferencedName::TYPE_CLASS);
}
$beginSearchAtPointer = $currentPointer;
continue;
}
// Attributes are parsed in specific method
$attributeStartPointerBefore = TokenHelper::findPrevious($phpcsFile, T_ATTRIBUTE, $nameStartPointer - 1, $beginSearchAtPointer);
if ($attributeStartPointerBefore !== null) {
if ($tokens[$attributeStartPointerBefore]['attribute_closer'] > $nameStartPointer) {
$beginSearchAtPointer = $tokens[$attributeStartPointerBefore]['attribute_closer'] + 1;
continue;
}
}
if (!self::isReferencedName($phpcsFile, $nameStartPointer)) {
/** @var int $beginSearchAtPointer */
$beginSearchAtPointer = TokenHelper::findNextExcluding(
$phpcsFile,
array_merge(TokenHelper::$ineffectiveTokenCodes, $nameTokenCodes),
$nameStartPointer + 1
);
continue;
}
$nameEndPointer = self::getReferencedNameEndPointer($phpcsFile, $nameStartPointer);
$referencedNames[] = new ReferencedName(
self::getReferenceName($phpcsFile, $nameStartPointer, $nameEndPointer),
$nameStartPointer,
$nameEndPointer,
self::getReferenceType($phpcsFile, $nameStartPointer, $nameEndPointer)
);
$beginSearchAtPointer = $nameEndPointer + 1;
}
return $referencedNames;
}
private static function getReferenceType(File $phpcsFile, int $nameStartPointer, int $nameEndPointer): string
{
$tokens = $phpcsFile->getTokens();
$nextTokenAfterEndPointer = TokenHelper::findNextEffective($phpcsFile, $nameEndPointer + 1);
$previousTokenBeforeStartPointer = TokenHelper::findPreviousEffective($phpcsFile, $nameStartPointer - 1);
$nameTokenCodes = TokenHelper::getNameTokenCodes();
if ($tokens[$nextTokenAfterEndPointer]['code'] === T_OPEN_PARENTHESIS) {
return $tokens[$previousTokenBeforeStartPointer]['code'] === T_NEW
? ReferencedName::TYPE_CLASS
: ReferencedName::TYPE_FUNCTION;
}
if (
$tokens[$previousTokenBeforeStartPointer]['code'] === T_TYPE_UNION
|| $tokens[$nextTokenAfterEndPointer]['code'] === T_TYPE_UNION
) {
return ReferencedName::TYPE_CLASS;
}
if (
$tokens[$previousTokenBeforeStartPointer]['code'] === T_TYPE_INTERSECTION
|| $tokens[$nextTokenAfterEndPointer]['code'] === T_TYPE_INTERSECTION
) {
return ReferencedName::TYPE_CLASS;
}
if ($tokens[$nextTokenAfterEndPointer]['code'] === T_BITWISE_AND) {
$tokenAfterNextToken = TokenHelper::findNextEffective($phpcsFile, $nextTokenAfterEndPointer + 1);
return in_array($tokens[$tokenAfterNextToken]['code'], [T_VARIABLE, T_ELLIPSIS], true)
? ReferencedName::TYPE_CLASS
: ReferencedName::TYPE_CONSTANT;
}
if (
in_array($tokens[$nextTokenAfterEndPointer]['code'], [
T_VARIABLE,
// Variadic parameter
T_ELLIPSIS,
], true)
) {
return ReferencedName::TYPE_CLASS;
}
if ($tokens[$previousTokenBeforeStartPointer]['code'] === T_COLON) {
$previousTokenPointer = TokenHelper::findPreviousEffective($phpcsFile, $previousTokenBeforeStartPointer - 1);
if (
$tokens[$previousTokenPointer]['code'] === T_PARAM_NAME
&& $tokens[$nextTokenAfterEndPointer]['code'] !== T_DOUBLE_COLON
) {
return ReferencedName::TYPE_CONSTANT;
}
// Return type hint
return ReferencedName::TYPE_CLASS;
}
if (
in_array($tokens[$previousTokenBeforeStartPointer]['code'], [
T_EXTENDS,
T_IMPLEMENTS,
T_INSTANCEOF,
// Trait
T_USE,
T_NEW,
// Nullable type hint
T_NULLABLE,
], true)
|| $tokens[$nextTokenAfterEndPointer]['code'] === T_DOUBLE_COLON
) {
return ReferencedName::TYPE_CLASS;
}
if ($tokens[$previousTokenBeforeStartPointer]['code'] === T_COMMA) {
$previousTokenPointer = TokenHelper::findPreviousExcluding(
$phpcsFile,
array_merge([T_COMMA], $nameTokenCodes, TokenHelper::$ineffectiveTokenCodes),
$previousTokenBeforeStartPointer - 1
);
return in_array($tokens[$previousTokenPointer]['code'], [
T_IMPLEMENTS,
T_EXTENDS,
T_USE,
], true)
? ReferencedName::TYPE_CLASS
: ReferencedName::TYPE_CONSTANT;
}
if (in_array($tokens[$previousTokenBeforeStartPointer]['code'], [T_BITWISE_OR, T_OPEN_PARENTHESIS], true)) {
$catchPointer = TokenHelper::findPreviousExcluding(
$phpcsFile,
array_merge([T_BITWISE_OR, T_OPEN_PARENTHESIS], $nameTokenCodes, TokenHelper::$ineffectiveTokenCodes),
$previousTokenBeforeStartPointer - 1
);
if ($tokens[$catchPointer]['code'] === T_CATCH) {
return ReferencedName::TYPE_CLASS;
}
}
return ReferencedName::TYPE_CONSTANT;
}
private static function isReferencedName(File $phpcsFile, int $startPointer): bool
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $startPointer + 1);
$previousPointer = TokenHelper::findPreviousEffective($phpcsFile, $startPointer - 1);
if ($nextPointer !== null && $tokens[$nextPointer]['code'] === T_DOUBLE_COLON) {
return !in_array($tokens[$previousPointer]['code'], [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR], true);
}
if (
count($tokens[$startPointer]['conditions']) > 0
&& array_values(array_reverse($tokens[$startPointer]['conditions']))[0] === T_USE
) {
// Method imported from trait
return false;
}
$previousToken = $tokens[$previousPointer];
$skipTokenCodes = [
T_FUNCTION,
T_AS,
T_DOUBLE_COLON,
T_OBJECT_OPERATOR,
T_NULLSAFE_OBJECT_OPERATOR,
T_NAMESPACE,
T_CONST,
T_ENUM_CASE,
];
if ($previousToken['code'] === T_USE) {
$classPointer = TokenHelper::findPrevious($phpcsFile, [T_CLASS, T_TRAIT, T_ANON_CLASS, T_ENUM], $startPointer - 1);
if ($classPointer !== null) {
$classToken = $tokens[$classPointer];
return $startPointer > $classToken['scope_opener'] && $startPointer < $classToken['scope_closer'];
}
return false;
}
if (
$previousToken['code'] === T_OPEN_PARENTHESIS
&& isset($previousToken['parenthesis_owner'])
&& $tokens[$previousToken['parenthesis_owner']]['code'] === T_DECLARE
) {
return false;
}
if (
$previousToken['code'] === T_COMMA
&& TokenHelper::findPreviousLocal($phpcsFile, T_DECLARE, $previousPointer - 1) !== null
) {
return false;
}
if ($previousToken['code'] === T_COMMA) {
$constPointer = TokenHelper::findPreviousLocal($phpcsFile, T_CONST, $previousPointer - 1);
if (
$constPointer !== null
&& TokenHelper::findNext($phpcsFile, [T_OPEN_SHORT_ARRAY, T_ARRAY], $constPointer + 1, $startPointer) === null
) {
return false;
}
} elseif ($previousToken['code'] === T_BITWISE_AND) {
$pointerBefore = TokenHelper::findPreviousEffective($phpcsFile, $previousPointer - 1);
$isFunctionPointerBefore = TokenHelper::findPreviousLocal($phpcsFile, T_FUNCTION, $previousPointer - 1) !== null;
if ($tokens[$pointerBefore]['code'] !== T_VARIABLE && $isFunctionPointerBefore) {
return false;
}
} elseif ($previousToken['code'] === T_GOTO) {
return false;
}
$isProbablyReferencedName = !in_array(
$previousToken['code'],
array_merge($skipTokenCodes, TokenHelper::$typeKeywordTokenCodes),
true
);
if (!$isProbablyReferencedName) {
return false;
}
$endPointer = self::getReferencedNameEndPointer($phpcsFile, $startPointer);
$referencedName = self::getReferenceName($phpcsFile, $startPointer, $endPointer);
if (TypeHintHelper::isSimpleTypeHint($referencedName) || $referencedName === 'object') {
return $tokens[$nextPointer]['code'] === T_OPEN_PARENTHESIS;
}
return true;
}
/**
* @return list<ReferencedName>
*/
private static function createAllReferencedNamesInAttributes(File $phpcsFile, int $openTagPointer): array
{
$referencedNames = [];
$tokens = $phpcsFile->getTokens();
$attributePointers = TokenHelper::findNextAll($phpcsFile, T_ATTRIBUTE, $openTagPointer + 1);
foreach ($attributePointers as $attributeStartPointer) {
$searchStartPointer = $attributeStartPointer + 1;
$searchEndPointer = $tokens[$attributeStartPointer]['attribute_closer'];
$searchPointer = $searchStartPointer;
$searchTokens = array_merge(TokenHelper::getNameTokenCodes(), [T_OPEN_PARENTHESIS, T_CLOSE_PARENTHESIS]);
$level = 0;
do {
$pointer = TokenHelper::findNext($phpcsFile, $searchTokens, $searchPointer, $searchEndPointer);
if ($pointer === null) {
break;
}
if ($tokens[$pointer]['code'] === T_OPEN_PARENTHESIS) {
$level++;
$searchPointer = $pointer + 1;
continue;
}
if ($tokens[$pointer]['code'] === T_CLOSE_PARENTHESIS) {
$level--;
$searchPointer = $pointer + 1;
continue;
}
$referencedNameEndPointer = self::getReferencedNameEndPointer($phpcsFile, $pointer);
$pointerBefore = TokenHelper::findPreviousEffective($phpcsFile, $pointer - 1);
if (in_array($tokens[$pointerBefore]['code'], [T_OPEN_TAG, T_ATTRIBUTE], true)) {
$referenceType = ReferencedName::TYPE_CLASS;
} elseif ($tokens[$pointerBefore]['code'] === T_COMMA && $level === 0) {
$referenceType = ReferencedName::TYPE_CLASS;
} elseif (self::isReferencedName($phpcsFile, $pointer)) {
$referenceType = self::getReferenceType($phpcsFile, $pointer, $referencedNameEndPointer);
} else {
$searchPointer = $pointer + 1;
continue;
}
$referencedName = self::getReferenceName($phpcsFile, $pointer, $referencedNameEndPointer);
$referencedNames[] = new ReferencedName(
$referencedName,
$attributeStartPointer,
$tokens[$attributeStartPointer]['attribute_closer'],
$referenceType
);
$searchPointer = $referencedNameEndPointer + 1;
} while (true);
}
return $referencedNames;
}
/**
* @param int|string $code
*/
private static function isNeedParsedContent($code): bool
{
return in_array($code, [T_DOUBLE_QUOTED_STRING, T_HEREDOC], true);
}
/**
* @return list<string>
*/
private static function getReferencedNamesFromString(string $content): array
{
$referencedNames = [];
$subTokens = token_get_all('<?php ' . $content);
foreach ($subTokens as $position => $token) {
if (is_array($token) && $token[0] === T_DOUBLE_COLON) {
$referencedName = '';
$tmpPosition = $position - 1;
while (true) {
if (!is_array($subTokens[$tmpPosition]) || !in_array($subTokens[$tmpPosition][0], [T_NS_SEPARATOR, T_STRING], true)) {
break;
}
$referencedName = $subTokens[$tmpPosition][1] . $referencedName;
$tmpPosition--;
}
$referencedNames[] = $referencedName;
} elseif (is_array($token) && $token[0] === T_NEW) {
$referencedName = '';
$tmpPosition = $position + 1;
while (true) {
if (!is_array($subTokens[$tmpPosition])) {
break;
}
if ($subTokens[$tmpPosition][0] === T_WHITESPACE) {
$tmpPosition++;
continue;
}
if (!in_array(
$subTokens[$tmpPosition][0],
[T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED, T_NAME_RELATIVE],
true
)) {
break;
}
$referencedName .= $subTokens[$tmpPosition][1];
$tmpPosition++;
}
if ($referencedName !== '') {
$referencedNames[] = $referencedName;
}
}
}
return $referencedNames;
}
}
@@ -0,0 +1,65 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_reverse;
use function in_array;
use const T_OPEN_TAG;
/**
* @internal
*/
class ScopeHelper
{
public static function isInSameScope(File $phpcsFile, int $firstPointer, int $secondPointer): bool
{
$tokens = $phpcsFile->getTokens();
$getScope = static function (int $pointer) use ($tokens): int {
$scope = 0;
foreach (array_reverse($tokens[$pointer]['conditions'], true) as $conditionPointer => $conditionTokenCode) {
if (!in_array($conditionTokenCode, TokenHelper::$functionTokenCodes, true)) {
continue;
}
$scope = $tokens[$conditionPointer]['level'] + 1;
break;
}
return $scope;
};
return $getScope($firstPointer) === $getScope($secondPointer);
}
public static function getRootPointer(File $phpcsFile, int $pointer): int
{
$rootPointer = TokenHelper::findNext($phpcsFile, T_OPEN_TAG, 0);
$rootPointers = array_reverse(self::getAllRootPointers($phpcsFile));
foreach ($rootPointers as $currentRootPointer) {
if ($currentRootPointer < $pointer) {
$rootPointer = $currentRootPointer;
break;
}
}
return $rootPointer;
}
/**
* @return list<int>
*/
public static function getAllRootPointers(File $phpcsFile): array
{
$lazyValue = static function () use ($phpcsFile): array {
return TokenHelper::findNextAll($phpcsFile, T_OPEN_TAG, 0);
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'openTagPointers', $lazyValue);
}
}
@@ -0,0 +1,49 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Closure;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function sprintf;
/**
* @internal
*/
final class SniffLocalCache
{
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint
* @var array<int, array<string, mixed>>
*/
private static $cache = [];
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint
* @return mixed
*/
public static function getAndSetIfNotCached(File $phpcsFile, string $key, Closure $lazyValue)
{
$fixerLoops = $phpcsFile->fixer !== null ? $phpcsFile->fixer->loops : 0;
$internalKey = sprintf('%s-%s', $phpcsFile->getFilename(), $key);
self::setIfNotCached($fixerLoops, $internalKey, $lazyValue);
return self::$cache[$fixerLoops][$internalKey] ?? null;
}
private static function setIfNotCached(int $fixerLoops, string $internalKey, Closure $lazyValue): void
{
if (array_key_exists($fixerLoops, self::$cache) && array_key_exists($internalKey, self::$cache[$fixerLoops])) {
return;
}
self::$cache[$fixerLoops][$internalKey] = $lazyValue();
if ($fixerLoops > 0) {
unset(self::$cache[$fixerLoops - 1]);
}
}
}
@@ -0,0 +1,90 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Config;
use function array_filter;
use function array_map;
use function array_values;
use function is_string;
use function preg_match;
use function trim;
use const PHP_VERSION_ID;
/**
* @internal
*/
class SniffSettingsHelper
{
/**
* @param string|int $settings
*/
public static function normalizeInteger($settings): int
{
return (int) trim((string) $settings);
}
/**
* @param string|int|null $settings
*/
public static function normalizeNullableInteger($settings): ?int
{
return $settings !== null ? (int) trim((string) $settings) : null;
}
/**
* @param list<string> $settings
* @return list<string>
*/
public static function normalizeArray(array $settings): array
{
$settings = array_map(static function (string $value): string {
return trim($value);
}, $settings);
$settings = array_filter($settings, static function (string $value): bool {
return $value !== '';
});
return array_values($settings);
}
/**
* @param array<int|string, int|string> $settings
* @return array<int|string, int|string>
*/
public static function normalizeAssociativeArray(array $settings): array
{
$normalizedSettings = [];
foreach ($settings as $key => $value) {
if (is_string($key)) {
$key = trim($key);
}
if (is_string($value)) {
$value = trim($value);
}
if ($key === '' || $value === '') {
continue;
}
$normalizedSettings[$key] = $value;
}
return $normalizedSettings;
}
public static function isValidRegularExpression(string $expression): bool
{
return preg_match('~^(?:\(.*\)|\{.*\}|\[.*\])[a-z]*\z~i', $expression) !== 0
|| preg_match('~^([^a-z\s\\\\]).*\\1[a-z]*\z~i', $expression) !== 0;
}
public static function isEnabledByPhpVersion(?bool $value, int $phpVersionLimit): bool
{
if ($value !== null) {
return $value;
}
$phpVersion = Config::getConfigData('php_version') !== null ? (int) Config::getConfigData('php_version') : PHP_VERSION_ID;
return $phpVersion >= $phpVersionLimit;
}
}
@@ -0,0 +1,25 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use function strlen;
use function strpos;
use function substr;
/**
* @internal
*/
class StringHelper
{
public static function startsWith(string $haystack, string $needle): bool
{
return $needle === '' || strpos($haystack, $needle) === 0;
}
public static function endsWith(string $haystack, string $needle): bool
{
return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
}
}
@@ -0,0 +1,83 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode;
use function array_reduce;
use function assert;
use function explode;
use function sprintf;
use function strpos;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
/**
* @internal
*/
class SuppressHelper
{
public const ANNOTATION = '@phpcsSuppress';
public static function isSniffSuppressed(File $phpcsFile, int $pointer, string $suppressName): bool
{
/** @var list<Annotation<GenericTagValueNode>> $annotations */
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $pointer, self::ANNOTATION);
return array_reduce(
$annotations,
static function (bool $carry, Annotation $annotation) use ($suppressName): bool {
$annotationSuppressName = explode(' ', $annotation->getValue()->value)[0];
if (
$suppressName === $annotationSuppressName
|| strpos($suppressName, sprintf('%s.', $annotationSuppressName)) === 0
) {
$carry = true;
}
return $carry;
},
false
);
}
public static function removeSuppressAnnotation(File $phpcsFile, int $pointer, string $suppressName): void
{
$suppressAnnotation = null;
/** @var Annotation<GenericTagValueNode> $annotation */
foreach (AnnotationHelper::getAnnotations($phpcsFile, $pointer, self::ANNOTATION) as $annotation) {
if ($annotation->getValue()->value === $suppressName) {
$suppressAnnotation = $annotation;
break;
}
}
assert($suppressAnnotation !== null);
$tokens = $phpcsFile->getTokens();
/** @var int $pointerBefore */
$pointerBefore = TokenHelper::findPrevious(
$phpcsFile,
[T_DOC_COMMENT_OPEN_TAG, T_DOC_COMMENT_STAR],
$suppressAnnotation->getStartPointer() - 1
);
$changeStart = $tokens[$pointerBefore]['code'] === T_DOC_COMMENT_STAR ? $pointerBefore : $suppressAnnotation->getStartPointer();
/** @var int $changeEnd */
$changeEnd = TokenHelper::findNext(
$phpcsFile,
[T_DOC_COMMENT_CLOSE_TAG, T_DOC_COMMENT_STAR],
$suppressAnnotation->getEndPointer() + 1
) - 1;
$phpcsFile->fixer->beginChangeset();
FixerHelper::removeBetweenIncluding($phpcsFile, $changeStart, $changeEnd);
$phpcsFile->fixer->endChangeset();
}
}
@@ -0,0 +1,182 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function count;
use function in_array;
use const T_CASE;
use const T_CLOSE_PARENTHESIS;
use const T_CLOSE_SHORT_ARRAY;
use const T_CLOSE_SQUARE_BRACKET;
use const T_COALESCE;
use const T_COLON;
use const T_COMMA;
use const T_DOUBLE_ARROW;
use const T_EQUAL;
use const T_INLINE_ELSE;
use const T_INLINE_THEN;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_OPEN_SQUARE_BRACKET;
use const T_OPEN_TAG;
use const T_OPEN_TAG_WITH_ECHO;
use const T_RETURN;
use const T_SEMICOLON;
use const T_THROW;
/**
* @internal
*/
class TernaryOperatorHelper
{
public static function isConditionOfTernaryOperator(File $phpcsFile, int $pointer): bool
{
$inlineThenPointer = TokenHelper::findNext($phpcsFile, T_INLINE_THEN, $pointer + 1);
if ($inlineThenPointer === null) {
return false;
}
$startPointer = self::getStartPointer($phpcsFile, $inlineThenPointer);
return $startPointer <= $pointer;
}
public static function getElsePointer(File $phpcsFile, int $inlineThenPointer): int
{
$tokens = $phpcsFile->getTokens();
$pointer = $inlineThenPointer;
do {
$pointer = TokenHelper::findNext(
$phpcsFile,
[T_INLINE_ELSE, T_OPEN_PARENTHESIS, T_OPEN_SHORT_ARRAY, T_OPEN_SQUARE_BRACKET],
$pointer + 1
);
if ($tokens[$pointer]['code'] === T_OPEN_PARENTHESIS) {
$pointer = $tokens[$pointer]['parenthesis_closer'];
continue;
}
if (in_array($tokens[$pointer]['code'], [T_OPEN_SHORT_ARRAY, T_OPEN_SQUARE_BRACKET], true)) {
$pointer = $tokens[$pointer]['bracket_closer'];
continue;
}
if (ScopeHelper::isInSameScope($phpcsFile, $inlineThenPointer, $pointer)) {
break;
}
} while ($pointer !== null);
return $pointer;
}
public static function getStartPointer(File $phpcsFile, int $inlineThenPointer): int
{
$tokens = $phpcsFile->getTokens();
$pointerBeforeCondition = $inlineThenPointer;
do {
$pointerBeforeCondition = TokenHelper::findPrevious(
$phpcsFile,
[T_EQUAL, T_DOUBLE_ARROW, T_COMMA, T_RETURN, T_THROW, T_CASE, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_OPEN_SQUARE_BRACKET, T_OPEN_SHORT_ARRAY, T_OPEN_PARENTHESIS],
$pointerBeforeCondition - 1
);
if (
in_array($tokens[$pointerBeforeCondition]['code'], [T_OPEN_SQUARE_BRACKET, T_OPEN_SHORT_ARRAY], true)
&& $tokens[$pointerBeforeCondition]['bracket_closer'] < $inlineThenPointer
) {
continue;
}
if (
$tokens[$pointerBeforeCondition]['code'] === T_OPEN_PARENTHESIS
&& $tokens[$pointerBeforeCondition]['parenthesis_closer'] < $inlineThenPointer
) {
continue;
}
break;
} while (true);
return TokenHelper::findNextEffective($phpcsFile, $pointerBeforeCondition + 1);
}
public static function getEndPointer(File $phpcsFile, int $inlineThenPointer, int $inlineElsePointer): int
{
$tokens = $phpcsFile->getTokens();
$pointerAfterInlineElseEnd = $inlineElsePointer;
do {
$pointerAfterInlineElseEnd = TokenHelper::findNext(
$phpcsFile,
[T_SEMICOLON, T_COLON, T_COMMA, T_DOUBLE_ARROW, T_CLOSE_PARENTHESIS, T_CLOSE_SHORT_ARRAY, T_CLOSE_SQUARE_BRACKET, T_COALESCE],
$pointerAfterInlineElseEnd + 1
);
if ($pointerAfterInlineElseEnd === null) {
continue;
}
if ($tokens[$pointerAfterInlineElseEnd]['code'] === T_CLOSE_PARENTHESIS) {
if ($tokens[$pointerAfterInlineElseEnd]['parenthesis_opener'] < $inlineThenPointer) {
break;
}
} elseif (in_array($tokens[$pointerAfterInlineElseEnd]['code'], [T_CLOSE_SHORT_ARRAY, T_CLOSE_SQUARE_BRACKET], true)) {
if ($tokens[$pointerAfterInlineElseEnd]['bracket_opener'] < $inlineThenPointer) {
break;
}
} elseif ($tokens[$pointerAfterInlineElseEnd]['code'] === T_COMMA) {
$previousPointer = TokenHelper::findPrevious(
$phpcsFile,
[T_OPEN_PARENTHESIS, T_OPEN_SHORT_ARRAY],
$pointerAfterInlineElseEnd - 1,
$inlineThenPointer
);
if ($previousPointer === null) {
break;
}
if (
$tokens[$previousPointer]['code'] === T_OPEN_PARENTHESIS
&& $tokens[$previousPointer]['parenthesis_closer'] < $pointerAfterInlineElseEnd
) {
break;
}
if (
$tokens[$previousPointer]['code'] === T_OPEN_SHORT_ARRAY
&& $tokens[$previousPointer]['bracket_closer'] < $pointerAfterInlineElseEnd
) {
break;
}
} elseif ($tokens[$pointerAfterInlineElseEnd]['code'] === T_DOUBLE_ARROW) {
$previousPointer = TokenHelper::findPrevious(
$phpcsFile,
T_OPEN_SHORT_ARRAY,
$pointerAfterInlineElseEnd - 1,
$inlineThenPointer
);
if ($previousPointer === null) {
break;
}
} elseif (ScopeHelper::isInSameScope($phpcsFile, $inlineElsePointer, $pointerAfterInlineElseEnd)) {
break;
}
} while ($pointerAfterInlineElseEnd !== null);
if ($pointerAfterInlineElseEnd !== null) {
return TokenHelper::findPreviousEffective($phpcsFile, $pointerAfterInlineElseEnd - 1);
}
return TokenHelper::findPreviousEffective($phpcsFile, count($tokens) - 1);
}
}
@@ -0,0 +1,534 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function array_merge;
use function count;
use const T_ANON_CLASS;
use const T_ARRAY;
use const T_ARRAY_HINT;
use const T_BREAK;
use const T_CALLABLE;
use const T_CLASS;
use const T_CLOSURE;
use const T_COMMENT;
use const T_CONTINUE;
use const T_DOC_COMMENT;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_DOC_COMMENT_STRING;
use const T_DOC_COMMENT_TAG;
use const T_DOC_COMMENT_WHITESPACE;
use const T_ENUM;
use const T_EXIT;
use const T_FALSE;
use const T_FN;
use const T_FUNCTION;
use const T_INTERFACE;
use const T_NAME_FULLY_QUALIFIED;
use const T_NAME_QUALIFIED;
use const T_NAME_RELATIVE;
use const T_NS_SEPARATOR;
use const T_NULL;
use const T_OPEN_SHORT_ARRAY;
use const T_PARENT;
use const T_PHPCS_DISABLE;
use const T_PHPCS_ENABLE;
use const T_PHPCS_IGNORE;
use const T_PHPCS_IGNORE_FILE;
use const T_PHPCS_SET;
use const T_PRIVATE;
use const T_PROTECTED;
use const T_PUBLIC;
use const T_READONLY;
use const T_RETURN;
use const T_SELF;
use const T_STATIC;
use const T_STRING;
use const T_THROW;
use const T_TRAIT;
use const T_TRUE;
use const T_TYPE_INTERSECTION;
use const T_TYPE_UNION;
use const T_VAR;
use const T_WHITESPACE;
/**
* @internal
*/
class TokenHelper
{
/** @var array<int, (int|string)> */
public static $arrayTokenCodes = [
T_ARRAY,
T_OPEN_SHORT_ARRAY,
];
/** @var array<int, (int|string)> */
public static $typeKeywordTokenCodes = [
T_CLASS,
T_TRAIT,
T_INTERFACE,
T_ENUM,
];
/** @var array<int, (int|string)> */
public static $typeWithAnonymousClassKeywordTokenCodes = [
T_CLASS,
T_ANON_CLASS,
T_TRAIT,
T_INTERFACE,
T_ENUM,
];
/** @var array<int, (int|string)> */
public static $ineffectiveTokenCodes = [
T_WHITESPACE,
T_COMMENT,
T_DOC_COMMENT,
T_DOC_COMMENT_OPEN_TAG,
T_DOC_COMMENT_CLOSE_TAG,
T_DOC_COMMENT_STAR,
T_DOC_COMMENT_STRING,
T_DOC_COMMENT_TAG,
T_DOC_COMMENT_WHITESPACE,
T_PHPCS_DISABLE,
T_PHPCS_ENABLE,
T_PHPCS_IGNORE,
T_PHPCS_IGNORE_FILE,
T_PHPCS_SET,
];
/** @var array<int, (int|string)> */
public static $annotationTokenCodes = [
T_DOC_COMMENT_TAG,
T_PHPCS_DISABLE,
T_PHPCS_ENABLE,
T_PHPCS_IGNORE,
T_PHPCS_IGNORE_FILE,
T_PHPCS_SET,
];
/** @var array<int, (int|string)> */
public static $inlineCommentTokenCodes = [
T_COMMENT,
T_PHPCS_DISABLE,
T_PHPCS_ENABLE,
T_PHPCS_IGNORE,
T_PHPCS_IGNORE_FILE,
T_PHPCS_SET,
];
/** @var array<int, (int|string)> */
public static $earlyExitTokenCodes = [
T_RETURN,
T_CONTINUE,
T_BREAK,
T_THROW,
T_EXIT,
];
/** @var array<int, (int|string)> */
public static $functionTokenCodes = [
T_FUNCTION,
T_CLOSURE,
T_FN,
];
/** @var array<int, (int|string)> */
public static $propertyModifiersTokenCodes = [
T_VAR,
T_PUBLIC,
T_PROTECTED,
T_PRIVATE,
T_READONLY,
T_STATIC,
];
/**
* @param int|string|array<int|string, int|string> $types
*/
public static function findNext(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findNext($types, $startPointer, $endPointer, false);
return $token === false ? null : $token;
}
/**
* @param int|string|array<int|string, int|string> $types
* @return list<int>
*/
public static function findNextAll(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): array
{
$pointers = [];
$actualStartPointer = $startPointer;
while (true) {
$pointer = self::findNext($phpcsFile, $types, $actualStartPointer, $endPointer);
if ($pointer === null) {
break;
}
$pointers[] = $pointer;
$actualStartPointer = $pointer + 1;
}
return $pointers;
}
/**
* @param int|string|array<int|string, int|string> $types
*/
public static function findNextContent(File $phpcsFile, $types, string $content, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findNext($types, $startPointer, $endPointer, false, $content);
return $token === false ? null : $token;
}
/**
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findNextEffective(File $phpcsFile, int $startPointer, ?int $endPointer = null): ?int
{
return self::findNextExcluding($phpcsFile, self::$ineffectiveTokenCodes, $startPointer, $endPointer);
}
/**
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findNextNonWhitespace(File $phpcsFile, int $startPointer, ?int $endPointer = null): ?int
{
return self::findNextExcluding($phpcsFile, T_WHITESPACE, $startPointer, $endPointer);
}
/**
* @param int|string|array<int|string, int|string> $types
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findNextExcluding(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findNext($types, $startPointer, $endPointer, true);
return $token === false ? null : $token;
}
/**
* @param int|string|array<int|string, int|string> $types
*/
public static function findNextLocal(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findNext($types, $startPointer, $endPointer, false, null, true);
return $token === false ? null : $token;
}
/**
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findNextAnyToken(File $phpcsFile, int $startPointer, ?int $endPointer = null): ?int
{
return self::findNextExcluding($phpcsFile, [], $startPointer, $endPointer);
}
/**
* @param int|string|array<int|string, int|string> $types
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findPrevious(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findPrevious($types, $startPointer, $endPointer, false);
return $token === false ? null : $token;
}
/**
* @param int|string|array<int|string, int|string> $types
*/
public static function findPreviousContent(File $phpcsFile, $types, string $content, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findPrevious($types, $startPointer, $endPointer, false, $content);
return $token === false ? null : $token;
}
/**
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findPreviousEffective(File $phpcsFile, int $startPointer, ?int $endPointer = null): ?int
{
return self::findPreviousExcluding($phpcsFile, self::$ineffectiveTokenCodes, $startPointer, $endPointer);
}
/**
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findPreviousNonWhitespace(File $phpcsFile, int $startPointer, ?int $endPointer = null): ?int
{
return self::findPreviousExcluding($phpcsFile, T_WHITESPACE, $startPointer, $endPointer);
}
/**
* @param int|string|array<int|string, int|string> $types
* @param int $startPointer Search starts at this token, inclusive
* @param int|null $endPointer Search ends at this token, exclusive
*/
public static function findPreviousExcluding(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findPrevious($types, $startPointer, $endPointer, true);
return $token === false ? null : $token;
}
/**
* @param int|string|array<int|string, int|string> $types
*/
public static function findPreviousLocal(File $phpcsFile, $types, int $startPointer, ?int $endPointer = null): ?int
{
/** @var int|false $token */
$token = $phpcsFile->findPrevious($types, $startPointer, $endPointer, false, null, true);
return $token === false ? null : $token;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findFirstTokenOnLine(File $phpcsFile, int $pointer): int
{
if ($pointer === 0) {
return $pointer;
}
$tokens = $phpcsFile->getTokens();
$line = $tokens[$pointer]['line'];
do {
$pointer--;
} while ($tokens[$pointer]['line'] === $line);
return $pointer + 1;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findLastTokenOnLine(File $phpcsFile, int $pointer): int
{
$tokens = $phpcsFile->getTokens();
$line = $tokens[$pointer]['line'];
do {
$pointer++;
} while (array_key_exists($pointer, $tokens) && $tokens[$pointer]['line'] === $line);
return $pointer - 1;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findLastTokenOnPreviousLine(File $phpcsFile, int $pointer): int
{
$tokens = $phpcsFile->getTokens();
$line = $tokens[$pointer]['line'];
do {
$pointer--;
} while ($tokens[$pointer]['line'] === $line);
return $pointer;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findFirstTokenOnNextLine(File $phpcsFile, int $pointer): ?int
{
$tokens = $phpcsFile->getTokens();
if ($pointer >= count($tokens)) {
return null;
}
$line = $tokens[$pointer]['line'];
do {
$pointer++;
if (!array_key_exists($pointer, $tokens)) {
return null;
}
} while ($tokens[$pointer]['line'] === $line);
return $pointer;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findFirstNonWhitespaceOnLine(File $phpcsFile, int $pointer): int
{
if ($pointer === 0) {
return $pointer;
}
$tokens = $phpcsFile->getTokens();
$line = $tokens[$pointer]['line'];
do {
$pointer--;
} while ($pointer >= 0 && $tokens[$pointer]['line'] === $line);
return self::findNextExcluding($phpcsFile, [T_WHITESPACE, T_DOC_COMMENT_WHITESPACE], $pointer + 1);
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findFirstNonWhitespaceOnNextLine(File $phpcsFile, int $pointer): ?int
{
$newLinePointer = self::findNextContent($phpcsFile, [T_WHITESPACE, T_DOC_COMMENT_WHITESPACE], $phpcsFile->eolChar, $pointer);
if ($newLinePointer === null) {
return null;
}
$nextPointer = self::findNextExcluding($phpcsFile, [T_WHITESPACE, T_DOC_COMMENT_WHITESPACE], $newLinePointer + 1);
$tokens = $phpcsFile->getTokens();
if ($nextPointer !== null && $tokens[$pointer]['line'] === $tokens[$nextPointer]['line'] - 1) {
return $nextPointer;
}
return null;
}
/**
* @param int $pointer Search starts at this token, inclusive
*/
public static function findFirstNonWhitespaceOnPreviousLine(File $phpcsFile, int $pointer): ?int
{
$newLinePointerOnPreviousLine = self::findPreviousContent(
$phpcsFile,
[T_WHITESPACE, T_DOC_COMMENT_WHITESPACE],
$phpcsFile->eolChar,
$pointer
);
if ($newLinePointerOnPreviousLine === null) {
return null;
}
$newLinePointerBeforePreviousLine = self::findPreviousContent(
$phpcsFile,
[T_WHITESPACE, T_DOC_COMMENT_WHITESPACE],
$phpcsFile->eolChar,
$newLinePointerOnPreviousLine - 1
);
if ($newLinePointerBeforePreviousLine === null) {
return null;
}
$nextPointer = self::findNextExcluding($phpcsFile, [T_WHITESPACE, T_DOC_COMMENT_WHITESPACE], $newLinePointerBeforePreviousLine + 1);
$tokens = $phpcsFile->getTokens();
if ($nextPointer !== null && $tokens[$pointer]['line'] === $tokens[$nextPointer]['line'] + 1) {
return $nextPointer;
}
return null;
}
public static function getContent(File $phpcsFile, int $startPointer, ?int $endPointer = null): string
{
$tokens = $phpcsFile->getTokens();
$endPointer = $endPointer ?? self::getLastTokenPointer($phpcsFile);
$content = '';
for ($i = $startPointer; $i <= $endPointer; $i++) {
$content .= $tokens[$i]['content'];
}
return $content;
}
public static function getLastTokenPointer(File $phpcsFile): int
{
$tokenCount = count($phpcsFile->getTokens());
if ($tokenCount === 0) {
throw new EmptyFileException($phpcsFile->getFilename());
}
return $tokenCount - 1;
}
/**
* @return array<int, (int|string)>
*/
public static function getNameTokenCodes(): array
{
return [T_STRING, T_NS_SEPARATOR, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAME_RELATIVE];
}
/**
* @return array<int, (int|string)>
*/
public static function getOnlyNameTokenCodes(): array
{
return [T_STRING, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAME_RELATIVE];
}
/**
* @return array<int, (int|string)>
*/
public static function getOnlyTypeHintTokenCodes(): array
{
static $typeHintTokenCodes = null;
if ($typeHintTokenCodes === null) {
$typeHintTokenCodes = array_merge(
self::getNameTokenCodes(),
[
T_SELF,
T_PARENT,
T_ARRAY_HINT,
T_CALLABLE,
T_FALSE,
T_TRUE,
T_NULL,
]
);
}
return $typeHintTokenCodes;
}
/**
* @return array<int, (int|string)>
*/
public static function getTypeHintTokenCodes(): array
{
static $typeHintTokenCodes = null;
if ($typeHintTokenCodes === null) {
$typeHintTokenCodes = array_merge(
self::getOnlyTypeHintTokenCodes(),
[T_TYPE_UNION, T_TYPE_INTERSECTION]
);
}
return $typeHintTokenCodes;
}
}
@@ -0,0 +1,47 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Exception;
use Throwable;
use function sprintf;
/**
* @internal
*/
class TokenPointerOutOfBoundsException extends Exception
{
/** @var int */
private $pointer;
/** @var int */
private $lastTokenPointer;
public function __construct(int $pointer, int $lastTokenPointer, ?Throwable $previous = null)
{
parent::__construct(
sprintf(
'Attempted access to token pointer %d, last token pointer is %d',
$pointer,
$lastTokenPointer
),
0,
$previous
);
$this->pointer = $pointer;
$this->lastTokenPointer = $lastTokenPointer;
}
public function getPointer(): int
{
return $this->pointer;
}
public function getLastTokenPointer(): int
{
return $this->lastTokenPointer;
}
}
@@ -0,0 +1,35 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use Exception;
use function preg_last_error;
use function preg_match;
/**
* @internal
*/
class TypeHelper
{
/**
* Validates type name according to the allowed characters in type names + namespaces
*
* @link http://php.net/manual/en/language.oop5.basic.php
*/
public static function isTypeName(string $typeName): bool
{
$result = preg_match(
'~^\\\\?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*$~',
$typeName
);
if ($result === false) {
// @codeCoverageIgnoreStart
throw new Exception('PREG error ' . preg_last_error());
// @codeCoverageIgnoreEnd
}
return $result !== 0;
}
}
@@ -0,0 +1,59 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use function strpos;
use function substr;
/**
* @internal
*/
class TypeHint
{
/** @var string */
private $typeHint;
/** @var bool */
private $nullable;
/** @var int */
private $startPointer;
/** @var int */
private $endPointer;
public function __construct(string $typeHint, bool $nullable, int $startPointer, int $endPointer)
{
$this->typeHint = $typeHint;
$this->nullable = $nullable;
$this->startPointer = $startPointer;
$this->endPointer = $endPointer;
}
public function getTypeHint(): string
{
return $this->typeHint;
}
public function getTypeHintWithoutNullabilitySymbol(): string
{
return strpos($this->typeHint, '?') === 0 ? substr($this->typeHint, 1) : $this->typeHint;
}
public function isNullable(): bool
{
return $this->nullable;
}
public function getStartPointer(): int
{
return $this->startPointer;
}
public function getEndPointer(): int
{
return $this->endPointer;
}
}
@@ -0,0 +1,417 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode;
use function array_key_exists;
use function array_map;
use function array_merge;
use function array_unique;
use function count;
use function implode;
use function in_array;
use function preg_split;
use function sort;
use function sprintf;
use function substr;
use const PREG_SPLIT_DELIM_CAPTURE;
use const T_FUNCTION;
use const T_WHITESPACE;
/**
* @internal
*/
class TypeHintHelper
{
public static function isValidTypeHint(
string $typeHint,
bool $enableObjectTypeHint,
bool $enableStaticTypeHint,
bool $enableMixedTypeHint,
bool $enableStandaloneNullTrueFalseTypeHints
): bool
{
if (self::isSimpleTypeHint($typeHint)) {
return true;
}
if ($typeHint === 'object') {
return $enableObjectTypeHint;
}
if ($typeHint === 'static') {
return $enableStaticTypeHint;
}
if ($typeHint === 'mixed') {
return $enableMixedTypeHint;
}
if (in_array($typeHint, ['null', 'true', 'false'], true)) {
return $enableStandaloneNullTrueFalseTypeHints;
}
return !self::isSimpleUnofficialTypeHints($typeHint);
}
public static function isSimpleTypeHint(string $typeHint): bool
{
return in_array($typeHint, self::getSimpleTypeHints(), true);
}
public static function isSimpleIterableTypeHint(string $typeHint): bool
{
return in_array($typeHint, self::getSimpleIterableTypeHints(), true);
}
public static function convertLongSimpleTypeHintToShort(string $typeHint): string
{
$longToShort = [
'integer' => 'int',
'boolean' => 'bool',
];
return array_key_exists($typeHint, $longToShort) ? $longToShort[$typeHint] : $typeHint;
}
public static function isUnofficialUnionTypeHint(string $typeHint): bool
{
return in_array($typeHint, ['scalar', 'numeric'], true);
}
public static function isVoidTypeHint(string $typeHint): bool
{
return $typeHint === 'void';
}
public static function isNeverTypeHint(string $typeHint): bool
{
return in_array($typeHint, ['never', 'never-return', 'never-returns', 'no-return'], true);
}
/**
* @return list<string>
*/
public static function convertUnofficialUnionTypeHintToOfficialTypeHints(string $typeHint): array
{
$conversion = [
'scalar' => ['string', 'int', 'float', 'bool'],
'numeric' => ['int', 'float'],
];
return $conversion[$typeHint];
}
public static function isTypeDefinedInAnnotation(File $phpcsFile, int $pointer, string $typeHint): bool
{
$docCommentOpenPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $pointer);
if ($docCommentOpenPointer === null) {
return false;
}
return self::isTemplate($phpcsFile, $docCommentOpenPointer, $typeHint)
|| self::isAlias($phpcsFile, $docCommentOpenPointer, $typeHint);
}
public static function getFullyQualifiedTypeHint(File $phpcsFile, int $pointer, string $typeHint): string
{
if (self::isSimpleTypeHint($typeHint)) {
return self::convertLongSimpleTypeHintToShort($typeHint);
}
return NamespaceHelper::resolveClassName($phpcsFile, $typeHint, $pointer);
}
/**
* @return list<string>
*/
public static function getSimpleTypeHints(): array
{
static $simpleTypeHints;
if ($simpleTypeHints === null) {
$simpleTypeHints = [
'int',
'integer',
'false',
'float',
'string',
'bool',
'boolean',
'callable',
'self',
'array',
'iterable',
'void',
'never',
];
}
return $simpleTypeHints;
}
/**
* @return list<string>
*/
public static function getSimpleIterableTypeHints(): array
{
return [
'array',
'iterable',
];
}
public static function isSimpleUnofficialTypeHints(string $typeHint): bool
{
static $simpleUnofficialTypeHints;
if ($simpleUnofficialTypeHints === null) {
$simpleUnofficialTypeHints = [
'null',
'mixed',
'scalar',
'numeric',
'true',
'object',
'resource',
'static',
'$this',
'class-string',
'trait-string',
'callable-string',
'numeric-string',
'non-empty-string',
'non-falsy-string',
'literal-string',
'array-key',
'list',
'empty',
'positive-int',
'negative-int',
'min',
'max',
];
}
return in_array($typeHint, $simpleUnofficialTypeHints, true);
}
/**
* @param list<string> $traversableTypeHints
*/
public static function isTraversableType(string $type, array $traversableTypeHints): bool
{
return self::isSimpleIterableTypeHint($type) || in_array($type, $traversableTypeHints, true);
}
public static function typeHintEqualsAnnotation(
File $phpcsFile,
int $functionPointer,
string $typeHint,
string $typeHintInAnnotation
): bool
{
/** @var list<string> $typeHintParts */
$typeHintParts = preg_split('~([&|])~', self::normalize($typeHint), -1, PREG_SPLIT_DELIM_CAPTURE);
/** @var list<string> $typeHintInAnnotationParts */
$typeHintInAnnotationParts = preg_split('~([&|])~', self::normalize($typeHintInAnnotation), -1, PREG_SPLIT_DELIM_CAPTURE);
if (count($typeHintParts) !== count($typeHintInAnnotationParts)) {
return false;
}
for ($i = 0; $i < count($typeHintParts); $i++) {
if (
(
$typeHintParts[$i] === '|'
|| $typeHintParts[$i] === '&'
)
&& $typeHintParts[$i] !== $typeHintInAnnotationParts[$i]
) {
return false;
}
if (self::getFullyQualifiedTypeHint($phpcsFile, $functionPointer, $typeHintParts[$i]) !== self::getFullyQualifiedTypeHint(
$phpcsFile,
$functionPointer,
$typeHintInAnnotationParts[$i]
)) {
return false;
}
}
return true;
}
public static function getStartPointer(File $phpcsFile, int $endPointer): int
{
$previousPointer = TokenHelper::findPreviousExcluding(
$phpcsFile,
array_merge([T_WHITESPACE], TokenHelper::getTypeHintTokenCodes()),
$endPointer - 1
);
return TokenHelper::findNextNonWhitespace($phpcsFile, $previousPointer + 1);
}
private static function isTemplate(File $phpcsFile, int $docCommentOpenPointer, string $typeHint): bool
{
static $templateAnnotationNames = null;
if ($templateAnnotationNames === null) {
foreach (['template', 'template-covariant'] as $annotationName) {
$templateAnnotationNames[] = sprintf('@%s', $annotationName);
foreach (AnnotationHelper::STATIC_ANALYSIS_PREFIXES as $prefixAnnotationName) {
$templateAnnotationNames[] = sprintf('@%s-%s', $prefixAnnotationName, $annotationName);
}
}
}
$containsTypeHintInTemplateAnnotation = static function (int $docCommentOpenPointer) use ($phpcsFile, $templateAnnotationNames, $typeHint): bool {
foreach ($templateAnnotationNames as $templateAnnotationName) {
/** @var list<Annotation<TemplateTagValueNode>> $annotations */
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer, $templateAnnotationName);
foreach ($annotations as $templateAnnotation) {
if ($templateAnnotation->isInvalid()) {
continue;
}
if ($templateAnnotation->getValue()->name === $typeHint) {
return true;
}
}
}
return false;
};
$tokens = $phpcsFile->getTokens();
$docCommentOwnerPointer = DocCommentHelper::findDocCommentOwnerPointer($phpcsFile, $docCommentOpenPointer);
if ($docCommentOwnerPointer !== null) {
if (in_array($tokens[$docCommentOwnerPointer]['code'], TokenHelper::$typeKeywordTokenCodes, true)) {
return $containsTypeHintInTemplateAnnotation($docCommentOpenPointer);
}
if ($tokens[$docCommentOwnerPointer]['code'] === T_FUNCTION && $containsTypeHintInTemplateAnnotation($docCommentOpenPointer)) {
return true;
}
}
$classPointer = ClassHelper::getClassPointer($phpcsFile, $docCommentOpenPointer);
if ($classPointer === null) {
return false;
}
$classDocCommentOpenPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $classPointer);
if ($classDocCommentOpenPointer === null) {
return false;
}
return $containsTypeHintInTemplateAnnotation($classDocCommentOpenPointer);
}
private static function isAlias(File $phpcsFile, int $docCommentOpenPointer, string $typeHint): bool
{
static $aliasAnnotationNames = null;
if ($aliasAnnotationNames === null) {
foreach (['type', 'import-type'] as $annotationName) {
foreach (AnnotationHelper::STATIC_ANALYSIS_PREFIXES as $prefixAnnotationName) {
$aliasAnnotationNames[] = sprintf('@%s-%s', $prefixAnnotationName, $annotationName);
}
}
}
$classPointer = ClassHelper::getClassPointer($phpcsFile, $docCommentOpenPointer);
if ($classPointer === null) {
return false;
}
$classDocCommentOpenPointer = DocCommentHelper::findDocCommentOpenPointer($phpcsFile, $classPointer);
if ($classDocCommentOpenPointer === null) {
return false;
}
foreach ($aliasAnnotationNames as $aliasAnnotationName) {
$annotations = AnnotationHelper::getAnnotations($phpcsFile, $classDocCommentOpenPointer, $aliasAnnotationName);
foreach ($annotations as $aliasAnnotation) {
$aliasAnnotationValue = $aliasAnnotation->getValue();
if ($aliasAnnotationValue instanceof TypeAliasTagValueNode && $aliasAnnotationValue->alias === $typeHint) {
return true;
}
if (!($aliasAnnotationValue instanceof TypeAliasImportTagValueNode)) {
continue;
}
if ($aliasAnnotationValue->importedAs === $typeHint) {
return true;
}
if ($aliasAnnotationValue->importedAlias === $typeHint) {
return true;
}
}
}
return false;
}
private static function normalize(string $typeHint): string
{
if (StringHelper::startsWith($typeHint, '?')) {
$typeHint = substr($typeHint, 1) . '|null';
}
if (self::isNeverTypeHint($typeHint)) {
return 'never';
}
/** @var list<string> $parts */
$parts = preg_split('~([&|])~', $typeHint, -1, PREG_SPLIT_DELIM_CAPTURE);
$hints = [];
$delimiter = '|';
foreach ($parts as $part) {
if ($part === '|' || $part === '&') {
$delimiter = $part;
continue;
}
$hints[] = $part;
}
if (in_array('mixed', $hints, true)) {
return 'mixed';
}
$convertedHints = [];
foreach ($hints as $hint) {
if (self::isUnofficialUnionTypeHint($hint) && $delimiter !== '&') {
$convertedHints = array_merge($convertedHints, self::convertUnofficialUnionTypeHintToOfficialTypeHints($hint));
} else {
$convertedHints[] = $hint;
}
}
$convertedHints = array_unique($convertedHints);
if (count($convertedHints) > 1) {
$convertedHints = array_map(static function (string $part): string {
return self::isVoidTypeHint($part) ? 'null' : $part;
}, $convertedHints);
}
sort($convertedHints);
return implode($delimiter, $convertedHints);
}
}
@@ -0,0 +1,135 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use function sprintf;
use function strtolower;
/**
* @internal
*/
class UseStatement
{
public const TYPE_CLASS = ReferencedName::TYPE_CLASS;
public const TYPE_FUNCTION = ReferencedName::TYPE_FUNCTION;
public const TYPE_CONSTANT = ReferencedName::TYPE_CONSTANT;
/** @var string */
private $nameAsReferencedInFile;
/** @var string */
private $normalizedNameAsReferencedInFile;
/** @var string */
private $fullyQualifiedTypeName;
/** @var int */
private $usePointer;
/** @var string */
private $type;
/** @var string|null */
private $alias;
public function __construct(
string $nameAsReferencedInFile,
string $fullyQualifiedClassName,
int $usePointer,
string $type,
?string $alias
)
{
$this->nameAsReferencedInFile = $nameAsReferencedInFile;
$this->normalizedNameAsReferencedInFile = self::normalizedNameAsReferencedInFile($type, $nameAsReferencedInFile);
$this->fullyQualifiedTypeName = $fullyQualifiedClassName;
$this->usePointer = $usePointer;
$this->type = $type;
$this->alias = $alias;
}
public function getNameAsReferencedInFile(): string
{
return $this->nameAsReferencedInFile;
}
public function getCanonicalNameAsReferencedInFile(): string
{
return $this->normalizedNameAsReferencedInFile;
}
public function getFullyQualifiedTypeName(): string
{
return $this->fullyQualifiedTypeName;
}
public function getPointer(): int
{
return $this->usePointer;
}
public function getType(): string
{
return $this->type;
}
public function getAlias(): ?string
{
return $this->alias;
}
public function isClass(): bool
{
return $this->type === self::TYPE_CLASS;
}
public function isConstant(): bool
{
return $this->type === self::TYPE_CONSTANT;
}
public function isFunction(): bool
{
return $this->type === self::TYPE_FUNCTION;
}
public function hasSameType(self $that): bool
{
return $this->type === $that->type;
}
public static function getUniqueId(string $type, string $name): string
{
$normalizedName = self::normalizedNameAsReferencedInFile($type, $name);
if ($type === self::TYPE_CLASS) {
return $normalizedName;
}
return sprintf('%s %s', $type, $normalizedName);
}
public static function normalizedNameAsReferencedInFile(string $type, string $name): string
{
if ($type === self::TYPE_CONSTANT) {
return $name;
}
return strtolower($name);
}
public static function getTypeName(string $type): ?string
{
if ($type === self::TYPE_CONSTANT) {
return 'const';
}
if ($type === self::TYPE_FUNCTION) {
return 'function';
}
return null;
}
}
@@ -0,0 +1,270 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function array_key_exists;
use function array_merge;
use function array_reverse;
use function count;
use function current;
use function in_array;
use function strtolower;
use const T_AS;
use const T_CLOSE_CURLY_BRACKET;
use const T_COMMA;
use const T_DECLARE;
use const T_FUNCTION;
use const T_NAMESPACE;
use const T_OPEN_CURLY_BRACKET;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_TAG;
use const T_OPEN_USE_GROUP;
use const T_SEMICOLON;
use const T_STRING;
use const T_USE;
/**
* @internal
*/
class UseStatementHelper
{
public static function isImportUse(File $phpcsFile, int $usePointer): bool
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $usePointer + 1);
// Anonymous function use
if ($tokens[$nextPointer]['code'] === T_OPEN_PARENTHESIS) {
return false;
}
if (
$tokens[$nextPointer]['code'] === T_STRING
&& in_array(strtolower($tokens[$nextPointer]['content']), ['function', 'const'], true)
) {
return true;
}
$previousPointer = TokenHelper::findPrevious(
$phpcsFile,
[T_OPEN_TAG, T_DECLARE, T_NAMESPACE, T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET],
$usePointer
);
if (in_array($tokens[$previousPointer]['code'], [T_OPEN_TAG, T_DECLARE, T_NAMESPACE], true)) {
return true;
}
if (array_key_exists('scope_condition', $tokens[$previousPointer])) {
$scopeConditionPointer = $tokens[$previousPointer]['scope_condition'];
if (
$tokens[$previousPointer]['code'] === T_OPEN_CURLY_BRACKET
&& in_array($tokens[$scopeConditionPointer]['code'], TokenHelper::$typeWithAnonymousClassKeywordTokenCodes, true)
) {
return false;
}
// Trait use after another trait use
if ($tokens[$scopeConditionPointer]['code'] === T_USE) {
return false;
}
// Trait use after method or import use after function
if ($tokens[$scopeConditionPointer]['code'] === T_FUNCTION) {
return ClassHelper::getClassPointer($phpcsFile, $usePointer) === null;
}
}
return true;
}
public static function isTraitUse(File $phpcsFile, int $usePointer): bool
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $usePointer + 1);
// Anonymous function use
if ($tokens[$nextPointer]['code'] === T_OPEN_PARENTHESIS) {
return false;
}
return !self::isImportUse($phpcsFile, $usePointer);
}
public static function getAlias(File $phpcsFile, int $usePointer): ?string
{
$endPointer = TokenHelper::findNext($phpcsFile, [T_SEMICOLON, T_COMMA], $usePointer + 1);
$asPointer = TokenHelper::findNext($phpcsFile, T_AS, $usePointer + 1, $endPointer);
if ($asPointer === null) {
return null;
}
$tokens = $phpcsFile->getTokens();
return $tokens[TokenHelper::findNext($phpcsFile, T_STRING, $asPointer + 1)]['content'];
}
public static function getNameAsReferencedInClassFromUse(File $phpcsFile, int $usePointer): string
{
$alias = self::getAlias($phpcsFile, $usePointer);
if ($alias !== null) {
return $alias;
}
$name = self::getFullyQualifiedTypeNameFromUse($phpcsFile, $usePointer);
return NamespaceHelper::getUnqualifiedNameFromFullyQualifiedName($name);
}
public static function getFullyQualifiedTypeNameFromUse(File $phpcsFile, int $usePointer): string
{
$tokens = $phpcsFile->getTokens();
$nameEndPointer = TokenHelper::findNext($phpcsFile, [T_SEMICOLON, T_AS, T_COMMA], $usePointer + 1) - 1;
if (in_array($tokens[$nameEndPointer]['code'], TokenHelper::$ineffectiveTokenCodes, true)) {
$nameEndPointer = TokenHelper::findPreviousEffective($phpcsFile, $nameEndPointer);
}
$nameStartPointer = TokenHelper::findPreviousExcluding($phpcsFile, TokenHelper::getNameTokenCodes(), $nameEndPointer - 1) + 1;
$name = TokenHelper::getContent($phpcsFile, $nameStartPointer, $nameEndPointer);
return NamespaceHelper::normalizeToCanonicalName($name);
}
/**
* @return array<string, UseStatement>
*/
public static function getUseStatementsForPointer(File $phpcsFile, int $pointer): array
{
$allUseStatements = self::getFileUseStatements($phpcsFile);
if (count($allUseStatements) === 1) {
return current($allUseStatements);
}
foreach (array_reverse($allUseStatements, true) as $pointerBeforeUseStatements => $useStatements) {
if ($pointerBeforeUseStatements < $pointer) {
return $useStatements;
}
}
return [];
}
/**
* @return array<int, array<string, UseStatement>>
*/
public static function getFileUseStatements(File $phpcsFile): array
{
$lazyValue = static function () use ($phpcsFile): array {
$useStatements = [];
$tokens = $phpcsFile->getTokens();
$namespaceAndOpenTagPointers = TokenHelper::findNextAll($phpcsFile, [T_OPEN_TAG, T_NAMESPACE], 0);
$openTagPointer = $namespaceAndOpenTagPointers[0];
foreach (self::getUseStatementPointers($phpcsFile, $openTagPointer) as $usePointer) {
$pointerBeforeUseStatements = $openTagPointer;
if (count($namespaceAndOpenTagPointers) > 1) {
foreach (array_reverse($namespaceAndOpenTagPointers) as $namespaceAndOpenTagPointer) {
if ($namespaceAndOpenTagPointer < $usePointer) {
$pointerBeforeUseStatements = $namespaceAndOpenTagPointer;
break;
}
}
}
$nextTokenFromUsePointer = TokenHelper::findNextEffective($phpcsFile, $usePointer + 1);
$type = UseStatement::TYPE_CLASS;
if ($tokens[$nextTokenFromUsePointer]['code'] === T_STRING) {
if ($tokens[$nextTokenFromUsePointer]['content'] === 'const') {
$type = UseStatement::TYPE_CONSTANT;
} elseif ($tokens[$nextTokenFromUsePointer]['content'] === 'function') {
$type = UseStatement::TYPE_FUNCTION;
}
}
$name = self::getNameAsReferencedInClassFromUse($phpcsFile, $usePointer);
$useStatement = new UseStatement(
$name,
self::getFullyQualifiedTypeNameFromUse($phpcsFile, $usePointer),
$usePointer,
$type,
self::getAlias($phpcsFile, $usePointer)
);
$useStatements[$pointerBeforeUseStatements][UseStatement::getUniqueId($type, $name)] = $useStatement;
}
return $useStatements;
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'useStatements', $lazyValue);
}
public static function getUseStatementPointer(File $phpcsFile, int $pointer): ?int
{
$pointers = self::getUseStatementPointers($phpcsFile, 0);
foreach (array_reverse($pointers) as $pointerBeforeUseStatements) {
if ($pointerBeforeUseStatements < $pointer) {
return $pointerBeforeUseStatements;
}
}
return null;
}
/**
* Searches for all use statements in a file, skips bodies of classes and traits.
*
* @return list<int>
*/
private static function getUseStatementPointers(File $phpcsFile, int $openTagPointer): array
{
$lazy = static function () use ($phpcsFile, $openTagPointer): array {
$tokens = $phpcsFile->getTokens();
$pointer = $openTagPointer + 1;
$pointers = [];
while (true) {
$typesToFind = array_merge([T_USE], TokenHelper::$typeKeywordTokenCodes);
$pointer = TokenHelper::findNext($phpcsFile, $typesToFind, $pointer);
if ($pointer === null) {
break;
}
$token = $tokens[$pointer];
if (in_array($token['code'], TokenHelper::$typeKeywordTokenCodes, true)) {
$pointer = $token['scope_closer'] + 1;
continue;
}
if (self::isGroupUse($phpcsFile, $pointer)) {
$pointer++;
continue;
}
if (!self::isImportUse($phpcsFile, $pointer)) {
$pointer++;
continue;
}
$pointers[] = $pointer;
$pointer++;
}
return $pointers;
};
return SniffLocalCache::getAndSetIfNotCached($phpcsFile, 'useStatementPointers', $lazy);
}
private static function isGroupUse(File $phpcsFile, int $usePointer): bool
{
$tokens = $phpcsFile->getTokens();
$semicolonOrGroupUsePointer = TokenHelper::findNext($phpcsFile, [T_SEMICOLON, T_OPEN_USE_GROUP], $usePointer + 1);
return $tokens[$semicolonOrGroupUsePointer]['code'] === T_OPEN_USE_GROUP;
}
}
@@ -0,0 +1,178 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use function count;
use function in_array;
use function preg_match;
use function preg_quote;
use function strlen;
use function strtolower;
use function substr;
use const T_DOUBLE_COLON;
use const T_DOUBLE_QUOTED_STRING;
use const T_FN;
use const T_HEREDOC;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_TAG;
use const T_STRING;
use const T_VARIABLE;
/**
* @internal
*/
class VariableHelper
{
public static function isUsedInScope(File $phpcsFile, int $scopeOwnerPointer, int $variablePointer): bool
{
return self::isUsedInScopeInternal($phpcsFile, $scopeOwnerPointer, $variablePointer, null);
}
public static function isUsedInScopeAfterPointer(
File $phpcsFile,
int $scopeOwnerPointer,
int $variablePointer,
int $startCheckPointer
): bool
{
return self::isUsedInScopeInternal($phpcsFile, $scopeOwnerPointer, $variablePointer, $startCheckPointer);
}
public static function isUsedAsVariable(File $phpcsFile, int $variablePointer, int $variableToCheckPointer): bool
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$variablePointer]['content'] !== $tokens[$variableToCheckPointer]['content']) {
return false;
}
if ($tokens[$variableToCheckPointer - 1]['code'] === T_DOUBLE_COLON) {
$pointerAfterVariable = TokenHelper::findNextEffective($phpcsFile, $variableToCheckPointer + 1);
return $tokens[$pointerAfterVariable]['code'] === T_OPEN_PARENTHESIS;
}
return !ParameterHelper::isParameter($phpcsFile, $variableToCheckPointer);
}
public static function isUsedInCompactFunction(File $phpcsFile, int $variablePointer, int $stringPointer): bool
{
$tokens = $phpcsFile->getTokens();
$stringContent = $tokens[$stringPointer]['content'];
if (strtolower($stringContent) !== 'compact') {
return false;
}
$parenthesisOpenerPointer = TokenHelper::findNextEffective($phpcsFile, $stringPointer + 1);
if ($tokens[$parenthesisOpenerPointer]['code'] !== T_OPEN_PARENTHESIS) {
return false;
}
$variableNameWithoutDollar = substr($tokens[$variablePointer]['content'], 1);
for ($i = $parenthesisOpenerPointer + 1; $i < $tokens[$parenthesisOpenerPointer]['parenthesis_closer']; $i++) {
if (preg_match('~^([\'"])' . $variableNameWithoutDollar . '\\1$~', $tokens[$i]['content']) !== 0) {
return true;
}
}
return false;
}
public static function isUsedInScopeInString(File $phpcsFile, string $variableName, int $stringPointer): bool
{
$tokens = $phpcsFile->getTokens();
$stringContent = $tokens[$stringPointer]['content'];
if (preg_match('~(\\\\)?(' . preg_quote($variableName, '~') . ')\b~', $stringContent, $matches) !== 0) {
if ($matches[1] === '') {
return true;
}
if (strlen($matches[1]) % 2 === 1) {
return true;
}
}
$variableNameWithoutDollar = substr($variableName, 1);
return preg_match('~\$\{' . preg_quote($variableNameWithoutDollar, '~') . '(<=\}|\b)~', $stringContent) !== 0;
}
private static function isUsedInScopeInternal(
File $phpcsFile,
int $scopeOwnerPointer,
int $variablePointer,
?int $startCheckPointer
): bool
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$scopeOwnerPointer]['code'] === T_OPEN_TAG) {
$scopeCloserPointer = count($tokens) - 1;
} elseif ($tokens[$scopeOwnerPointer]['code'] === T_FN) {
$scopeCloserPointer = $tokens[$scopeOwnerPointer]['scope_closer'];
} else {
$scopeCloserPointer = $tokens[$scopeOwnerPointer]['scope_closer'] - 1;
}
if ($tokens[$scopeOwnerPointer]['code'] === T_OPEN_TAG) {
$firstPointerInScope = $scopeOwnerPointer + 1;
} elseif ($tokens[$scopeOwnerPointer]['code'] === T_FN) {
$firstPointerInScope = $tokens[$scopeOwnerPointer]['scope_opener'];
} else {
$firstPointerInScope = $tokens[$scopeOwnerPointer]['scope_opener'] + 1;
}
if ($startCheckPointer === null) {
$startCheckPointer = $firstPointerInScope;
}
for ($i = $startCheckPointer; $i <= $scopeCloserPointer; $i++) {
if (!ScopeHelper::isInSameScope($phpcsFile, $i, $firstPointerInScope)) {
continue;
}
if (
$tokens[$i]['code'] === T_VARIABLE
&& self::isUsedAsVariable($phpcsFile, $variablePointer, $i)
) {
return true;
}
if ($tokens[$i]['code'] === T_STRING) {
if (self::isGetDefinedVarsCall($phpcsFile, $i)) {
return true;
}
if (self::isUsedInCompactFunction($phpcsFile, $variablePointer, $i)) {
return true;
}
}
if (
in_array($tokens[$i]['code'], [T_DOUBLE_QUOTED_STRING, T_HEREDOC], true)
&& self::isUsedInScopeInString($phpcsFile, $tokens[$variablePointer]['content'], $i)
) {
return true;
}
}
return false;
}
private static function isGetDefinedVarsCall(File $phpcsFile, int $stringPointer): bool
{
$tokens = $phpcsFile->getTokens();
$stringContent = $tokens[$stringPointer]['content'];
if (strtolower($stringContent) !== 'get_defined_vars') {
return false;
}
$parenthesisOpenerPointer = TokenHelper::findNextEffective($phpcsFile, $stringPointer + 1);
return $tokens[$parenthesisOpenerPointer]['code'] === T_OPEN_PARENTHESIS;
}
}
@@ -0,0 +1,358 @@
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Helpers;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;
use function array_fill_keys;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_reverse;
use function array_values;
use function count;
use function end;
use function implode;
use function in_array;
use function key;
use function reset;
use const T_ARRAY;
use const T_ARRAY_CAST;
use const T_BOOL_CAST;
use const T_BOOLEAN_AND;
use const T_BOOLEAN_OR;
use const T_CASE;
use const T_CLOSE_CURLY_BRACKET;
use const T_CLOSE_PARENTHESIS;
use const T_CLOSE_SHORT_ARRAY;
use const T_COALESCE;
use const T_COLON;
use const T_COMMA;
use const T_COMMENT;
use const T_CONSTANT_ENCAPSED_STRING;
use const T_DNUMBER;
use const T_DOC_COMMENT;
use const T_DOUBLE_CAST;
use const T_DOUBLE_COLON;
use const T_FALSE;
use const T_FN_ARROW;
use const T_INLINE_ELSE;
use const T_INLINE_THEN;
use const T_INT_CAST;
use const T_LNUMBER;
use const T_LOGICAL_AND;
use const T_LOGICAL_OR;
use const T_LOGICAL_XOR;
use const T_MATCH_ARROW;
use const T_MINUS;
use const T_NS_SEPARATOR;
use const T_NULL;
use const T_OBJECT_CAST;
use const T_OPEN_PARENTHESIS;
use const T_OPEN_SHORT_ARRAY;
use const T_OPEN_TAG;
use const T_PLUS;
use const T_RETURN;
use const T_SEMICOLON;
use const T_STRING;
use const T_STRING_CAST;
use const T_TRUE;
use const T_UNSET_CAST;
use const T_VARIABLE;
use const T_WHITESPACE;
/**
* @internal
*/
class YodaHelper
{
private const DYNAMISM_VARIABLE = 999;
private const DYNAMISM_CONSTANT = 1;
private const DYNAMISM_FUNCTION_CALL = 998;
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $leftSideTokens
* @param array<int, array<string, array<int, int|string>|int|string>> $rightSideTokens
*/
public static function fix(File $phpcsFile, array $leftSideTokens, array $rightSideTokens): void
{
$phpcsFile->fixer->beginChangeset();
self::replace($phpcsFile, $leftSideTokens, $rightSideTokens);
self::replace($phpcsFile, $rightSideTokens, $leftSideTokens);
$phpcsFile->fixer->endChangeset();
}
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $tokens
* @return array<int, array<string, array<int, int|string>|int|string>>
*/
public static function getLeftSideTokens(array $tokens, int $comparisonTokenPointer): array
{
$parenthesisDepth = 0;
$shortArrayDepth = 0;
$examinedTokenPointer = $comparisonTokenPointer;
$sideTokens = [];
$stopTokenCodes = self::getStopTokenCodes();
while (true) {
$examinedTokenPointer--;
$examinedToken = $tokens[$examinedTokenPointer];
/** @var string|int $examinedTokenCode */
$examinedTokenCode = $examinedToken['code'];
if ($parenthesisDepth === 0 && $shortArrayDepth === 0 && isset($stopTokenCodes[$examinedTokenCode])) {
break;
}
if ($examinedTokenCode === T_CLOSE_SHORT_ARRAY) {
$shortArrayDepth++;
} elseif ($examinedTokenCode === T_OPEN_SHORT_ARRAY) {
if ($shortArrayDepth === 0) {
break;
}
$shortArrayDepth--;
}
if ($examinedTokenCode === T_CLOSE_PARENTHESIS) {
$parenthesisDepth++;
} elseif ($examinedTokenCode === T_OPEN_PARENTHESIS) {
if ($parenthesisDepth === 0) {
break;
}
$parenthesisDepth--;
}
$sideTokens[$examinedTokenPointer] = $examinedToken;
}
return self::trimWhitespaceTokens(array_reverse($sideTokens, true));
}
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $tokens
* @return array<int, array<string, array<int, int|string>|int|string>>
*/
public static function getRightSideTokens(array $tokens, int $comparisonTokenPointer): array
{
$parenthesisDepth = 0;
$shortArrayDepth = 0;
$examinedTokenPointer = $comparisonTokenPointer;
$sideTokens = [];
$stopTokenCodes = self::getStopTokenCodes();
while (true) {
$examinedTokenPointer++;
$examinedToken = $tokens[$examinedTokenPointer];
/** @var string|int $examinedTokenCode */
$examinedTokenCode = $examinedToken['code'];
if ($parenthesisDepth === 0 && $shortArrayDepth === 0 && isset($stopTokenCodes[$examinedTokenCode])) {
break;
}
if ($examinedTokenCode === T_OPEN_SHORT_ARRAY) {
$shortArrayDepth++;
} elseif ($examinedTokenCode === T_CLOSE_SHORT_ARRAY) {
if ($shortArrayDepth === 0) {
break;
}
$shortArrayDepth--;
}
if ($examinedTokenCode === T_OPEN_PARENTHESIS) {
$parenthesisDepth++;
} elseif ($examinedTokenCode === T_CLOSE_PARENTHESIS) {
if ($parenthesisDepth === 0) {
break;
}
$parenthesisDepth--;
}
$sideTokens[$examinedTokenPointer] = $examinedToken;
}
return self::trimWhitespaceTokens($sideTokens);
}
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $tokens
* @param array<int, array<string, array<int, int|string>|int|string>> $sideTokens
*/
public static function getDynamismForTokens(array $tokens, array $sideTokens): ?int
{
$sideTokens = array_values(array_filter($sideTokens, static function (array $token): bool {
return !in_array(
$token['code'],
[T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_NS_SEPARATOR, T_PLUS, T_MINUS, T_INT_CAST, T_DOUBLE_CAST, T_STRING_CAST, T_ARRAY_CAST, T_OBJECT_CAST, T_BOOL_CAST, T_UNSET_CAST],
true
);
}));
$sideTokensCount = count($sideTokens);
$dynamism = self::getTokenDynamism();
if ($sideTokensCount > 0) {
if ($sideTokens[0]['code'] === T_VARIABLE) {
// Expression starts with a variable - wins over everything else
return self::DYNAMISM_VARIABLE;
}
if ($sideTokens[$sideTokensCount - 1]['code'] === T_CLOSE_PARENTHESIS) {
if (array_key_exists('parenthesis_owner', $sideTokens[$sideTokensCount - 1])) {
/** @var int $parenthesisOwner */
$parenthesisOwner = $sideTokens[$sideTokensCount - 1]['parenthesis_owner'];
if ($tokens[$parenthesisOwner]['code'] === T_ARRAY) {
// Array
return $dynamism[T_ARRAY];
}
}
// Function or method call
return self::DYNAMISM_FUNCTION_CALL;
}
if ($sideTokensCount === 1 && $sideTokens[0]['code'] === T_STRING) {
// Constant
return self::DYNAMISM_CONSTANT;
}
}
if ($sideTokensCount > 2 && $sideTokens[$sideTokensCount - 2]['code'] === T_DOUBLE_COLON) {
if ($sideTokens[$sideTokensCount - 1]['code'] === T_VARIABLE) {
// Static property access
return self::DYNAMISM_VARIABLE;
}
if ($sideTokens[$sideTokensCount - 1]['code'] === T_STRING) {
// Class constant
return self::DYNAMISM_CONSTANT;
}
}
if (array_key_exists(0, $sideTokens)) {
/** @var int $sideTokenCode */
$sideTokenCode = $sideTokens[0]['code'];
if (array_key_exists($sideTokenCode, $dynamism)) {
return $dynamism[$sideTokenCode];
}
}
return null;
}
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $tokens
* @return array<int, array<string, array<int, int|string>|int|string>>
*/
public static function trimWhitespaceTokens(array $tokens): array
{
foreach ($tokens as $pointer => $token) {
if ($token['code'] !== T_WHITESPACE) {
break;
}
unset($tokens[$pointer]);
}
foreach (array_reverse($tokens, true) as $pointer => $token) {
if ($token['code'] !== T_WHITESPACE) {
break;
}
unset($tokens[$pointer]);
}
return $tokens;
}
/**
* @param array<int, array<string, array<int, int|string>|int|string>> $oldTokens
* @param array<int, array<string, array<int, int|string>|int|string>> $newTokens
*/
private static function replace(File $phpcsFile, array $oldTokens, array $newTokens): void
{
reset($oldTokens);
/** @var int $firstOldPointer */
$firstOldPointer = key($oldTokens);
end($oldTokens);
/** @var int $lastOldPointer */
$lastOldPointer = key($oldTokens);
$content = implode('', array_map(static function (array $token): string {
/** @var string $content */
$content = $token['content'];
return $content;
}, $newTokens));
FixerHelper::change($phpcsFile, $firstOldPointer, $lastOldPointer, $content);
}
/**
* @return array<int|string, int>
*/
private static function getTokenDynamism(): array
{
static $tokenDynamism;
if ($tokenDynamism === null) {
$tokenDynamism = [
T_TRUE => 0,
T_FALSE => 0,
T_NULL => 0,
T_DNUMBER => 0,
T_LNUMBER => 0,
T_OPEN_SHORT_ARRAY => 0,
// Do not stack error messages when the old-style array syntax is used
T_ARRAY => 0,
T_CONSTANT_ENCAPSED_STRING => 0,
T_VARIABLE => self::DYNAMISM_VARIABLE,
T_STRING => self::DYNAMISM_FUNCTION_CALL,
];
$tokenDynamism += array_fill_keys(array_keys(Tokens::$castTokens), 3);
}
return $tokenDynamism;
}
/**
* @return array<int|string, bool>
*/
private static function getStopTokenCodes(): array
{
static $stopTokenCodes;
if ($stopTokenCodes === null) {
$stopTokenCodes = [
T_BOOLEAN_AND => true,
T_BOOLEAN_OR => true,
T_SEMICOLON => true,
T_OPEN_TAG => true,
T_INLINE_THEN => true,
T_INLINE_ELSE => true,
T_LOGICAL_AND => true,
T_LOGICAL_OR => true,
T_LOGICAL_XOR => true,
T_COALESCE => true,
T_CASE => true,
T_COLON => true,
T_RETURN => true,
T_COMMA => true,
T_CLOSE_CURLY_BRACKET => true,
T_MATCH_ARROW => true,
T_FN_ARROW => true,
];
$stopTokenCodes += array_fill_keys(array_keys(Tokens::$assignmentTokens), true);
$stopTokenCodes += array_fill_keys(array_keys(Tokens::$commentTokens), true);
}
return $stopTokenCodes;
}
}