diff --git a/src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php b/src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php index b5521f7..66e74fb 100644 --- a/src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php +++ b/src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php @@ -50,6 +50,7 @@ public function processNode(Node $node, Scope $scope): array $reflectionMethod->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhp'), $reflectionMethod->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhpunit'), ), + $node->getOriginalNode()->attrGroups, $scope, ); } diff --git a/src/Rules/PHPUnit/AttributeVersionRequirementHelper.php b/src/Rules/PHPUnit/AttributeVersionRequirementHelper.php index 203b3fe..6f3b59c 100644 --- a/src/Rules/PHPUnit/AttributeVersionRequirementHelper.php +++ b/src/Rules/PHPUnit/AttributeVersionRequirementHelper.php @@ -5,6 +5,8 @@ use PharIo\Version\UnsupportedVersionConstraintException; use PharIo\Version\Version; use PharIo\Version\VersionConstraintParser; +use PhpParser\Node; +use PhpParser\Node\Scalar\String_; use PHPStan\Analyser\Scope; use PHPStan\BetterReflection\Reflection\ReflectionAttribute; use PHPStan\Php\ConfiguredPhpVersionRangeHelper; @@ -13,6 +15,8 @@ use PHPStan\Rules\RuleErrorBuilder; use PHPStan\ShouldNotHappenException; use function count; +use function explode; +use function implode; use function is_numeric; use function is_string; use function preg_match; @@ -24,6 +28,13 @@ final class AttributeVersionRequirementHelper { + /** + * Matches requirements whose version can be completed to major.minor.patch + * without changing their meaning, e.g. `>=8`, `>=8.1` or `^8.1`. + * Versions without an operator are deliberately not matched. + */ + private const FIXABLE_VERSION_REQUIREMENT = '/^(?P>=|\^)(?P\s*)(?P\d+(?:\.\d+){0,2})$/'; + private const VERSION_COMPARISON = "/(?P!=|<|<=|<>|=|==|>|>=)?\s*(?P[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?)[ \t]*\r?$/m"; private PHPUnitVersion $PHPUnitVersion; @@ -59,34 +70,45 @@ public function __construct( /** * @param array $attributes + * @param array $attrGroups AST attribute groups of the node $attributes were read from * * @return list */ - public function checkVersionRequirement(array $attributes, Scope $scope): array + public function checkVersionRequirement(array $attributes, array $attrGroups, Scope $scope): array { $errors = []; $parser = new VersionConstraintParser(); + $attributeNodes = $this->groupAttributeNodesByName($attrGroups); + $attributeIndexes = []; foreach ($attributes as $attr) { + $attributeIndex = $attributeIndexes[$attr->getName()] ?? 0; + $attributeIndexes[$attr->getName()] = $attributeIndex + 1; + $args = $attr->getArguments(); if (count($args) !== 1) { continue; } - // the following block is mimicing PHPUnit version parsing - // see https://github.com/sebastianbergmann/phpunit/blob/43c2cd7b96ee1e800b35e4df23b419a88b53111d/src/Metadata/Version/Requirement.php - - // named arguments are handled just to make sure we don't crash on them. + // phpunit does not support named arguments. + // we handle them here just to make sure we don't crash on them. $versionRequirement = $args[0] ?? $args['versionRequirement'] ?? null; if (!is_string($versionRequirement)) { continue; } + // the following block is mimicing PHPUnit version parsing + // see https://github.com/sebastianbergmann/phpunit/blob/43c2cd7b96ee1e800b35e4df23b419a88b53111d/src/Metadata/Version/Requirement.php + if ($this->warnAboutIncompleteVersion($versionRequirement)) { - $errors[] = RuleErrorBuilder::message( + $errorBuilder = RuleErrorBuilder::message( sprintf('Version requirement %s is incomplete. Expect a version composed of major, minor and patch.', $versionRequirement), ) - ->identifier('phpunit.attributeRequiresPhpVersion') - ->build(); + ->identifier('phpunit.attributeRequiresPhpVersion'); + $versionNode = $this->getFixableVersionNode( + $attributeNodes[$attr->getName()][$attributeIndex] ?? null, + $versionRequirement, + ); + $errors[] = $this->buildError($errorBuilder, $versionNode); } if ( @@ -180,6 +202,84 @@ public function checkVersionRequirement(array $attributes, Scope $scope): array return $errors; } + /** + * @param array $attrGroups + * + * @return array> + */ + private function groupAttributeNodesByName(array $attrGroups): array + { + $attributeNodes = []; + foreach ($attrGroups as $attrGroup) { + foreach ($attrGroup->attrs as $attributeNode) { + $attributeNodes[$attributeNode->name->toString()][] = $attributeNode; + } + } + + return $attributeNodes; + } + + /** + * Returns the string literal holding the version requirement, when it is a plain literal in the analysed file. + */ + private function getFixableVersionNode(?Node\Attribute $attributeNode, string $versionRequirement): ?String_ + { + if ($attributeNode === null || count($attributeNode->args) !== 1) { + return null; + } + + $versionNode = $attributeNode->args[0]->value; + if (!$versionNode instanceof String_) { + return null; + } + + // make sure the AST node is the one the reflection attribute was read from + if ($versionNode->value !== $versionRequirement) { + return null; + } + + return $versionNode; + } + + /** + * @param RuleErrorBuilder $errorBuilder + */ + private function buildError(RuleErrorBuilder $errorBuilder, ?String_ $versionNode): IdentifierRuleError + { + if ($versionNode === null) { + return $errorBuilder->build(); + } + + $fixedVersionRequirement = $this->fixVersionRequirement($versionNode->value); + if ($fixedVersionRequirement === null) { + return $errorBuilder->build(); + } + + return $errorBuilder->fixNode( + $versionNode, + static fn (String_ $versionNode): String_ => new String_($fixedVersionRequirement, ['kind' => $versionNode->getAttribute('kind')]), + )->build(); + } + + /** + * Completes the version to major.minor.patch. + * Only applied where the meaning of the requirement stays the same. + * Versions without an operator are not fixed. + */ + private function fixVersionRequirement(string $versionRequirement): ?string + { + if (preg_match(self::FIXABLE_VERSION_REQUIREMENT, $versionRequirement, $matches) !== 1) { + return null; + } + + $versionParts = explode('.', $matches['version']); + while (count($versionParts) < 3) { + $versionParts[] = '0'; + } + + return $matches['operator'] . $matches['space'] . implode('.', $versionParts); + } + /** * @return list */ diff --git a/src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php b/src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php index a9e68ff..1e2a831 100644 --- a/src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php +++ b/src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php @@ -41,6 +41,7 @@ public function processNode(Node $node, Scope $scope): array $classReflection->getNativeReflection()->getBetterReflection()->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhp'), $classReflection->getNativeReflection()->getBetterReflection()->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhpunit'), ), + $node->getOriginalNode()->attrGroups, $scope, ); } diff --git a/tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php b/tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php index 370d0a9..84e886c 100644 --- a/tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php +++ b/tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php @@ -207,6 +207,54 @@ public function testNonStringArguments(): void ]); } + public function testFixIncompleteVersion(): void + { + $this->phpunitMajorVersion = 13; + $this->phpunitMinorVersion = 0; + $this->deprecationRulesInstalled = false; + $this->warnAboutIncompleteVersion = true; + + $this->fix(__DIR__ . '/data/requires-php-version-fixable.php', __DIR__ . '/data/requires-php-version-fixable.php.fixed'); + } + + public function testDoNotFixVersionWithoutOperator(): void + { + $this->phpunitMajorVersion = 12; + $this->phpunitMinorVersion = 4; + $this->deprecationRulesInstalled = true; + + $this->fix(__DIR__ . '/data/requires-php-version.php', __DIR__ . '/data/requires-php-version.php'); + } + + public function testNamedArgument(): void + { + $this->phpunitMajorVersion = 13; + $this->phpunitMinorVersion = 0; + $this->deprecationRulesInstalled = false; + $this->warnAboutIncompleteVersion = true; + + $this->analyse([__DIR__ . '/data/requires-php-version-named-argument.php'], [ + [ + 'Version requirement 8.0 is incomplete. Expect a version composed of major, minor and patch.', + 12, + ], + [ + 'Version requirement 8.0 is missing operator.', + 12, + ], + ]); + } + + public function testFixNamedArgument(): void + { + $this->phpunitMajorVersion = 13; + $this->phpunitMinorVersion = 0; + $this->deprecationRulesInstalled = false; + $this->warnAboutIncompleteVersion = true; + + $this->fix(__DIR__ . '/data/requires-php-version-named-argument.php', __DIR__ . '/data/requires-php-version-named-argument.php'); + } + protected function getRule(): Rule { $phpunitVersion = new PHPUnitVersion($this->phpunitMajorVersion, $this->phpunitMinorVersion); diff --git a/tests/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRuleTest.php b/tests/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRuleTest.php index 47e92de..e082ddd 100644 --- a/tests/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRuleTest.php +++ b/tests/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRuleTest.php @@ -67,6 +67,15 @@ public function testNonStringArguments(): void ]); } + public function testFixIncompleteVersion(): void + { + $this->phpunitMajorVersion = 12; + $this->phpunitMinorVersion = 5; + $this->warnAboutIncompleteVersion = true; + + $this->fix(__DIR__ . '/data/requires-php-version-on-class-fixable.php', __DIR__ . '/data/requires-php-version-on-class-fixable.php.fixed'); + } + protected function getRule(): Rule { $phpunitVersion = new PHPUnitVersion($this->phpunitMajorVersion, $this->phpunitMinorVersion); diff --git a/tests/Rules/PHPUnit/data/requires-php-version-fixable.php b/tests/Rules/PHPUnit/data/requires-php-version-fixable.php new file mode 100644 index 0000000..361065a --- /dev/null +++ b/tests/Rules/PHPUnit/data/requires-php-version-fixable.php @@ -0,0 +1,79 @@ +=8.0')] + public function testGreaterOrEqual(): void { + + } + + #[RequiresPhp('>= 8')] + public function testGreaterOrEqualWithSpace(): void { + + } + + #[RequiresPhp('^8.0')] + public function testCaret(): void { + + } + + #[RequiresPhp("8.0")] + public function testDoubleQuoted(): void { + + } + + #[RequiresPhp('8.0')] + #[RequiresPhpunit('>=11')] + public function testMultipleAttributes(): void { + + } + + #[RequiresPhp('>= 8.0.0')] + #[RequiresPhp('8.1')] + public function testRepeatedAttribute(): void { + + } + + // changing these would change their meaning + #[RequiresPhp('<8.0')] + public function testLessThan(): void { + + } + + #[RequiresPhp('>8.0')] + public function testGreaterThan(): void { + + } + + #[RequiresPhp('~8.0')] + public function testTilde(): void { + + } + + #[RequiresPhp('<=8.5')] + public function testLessOrEqual(): void { + + } +} diff --git a/tests/Rules/PHPUnit/data/requires-php-version-fixable.php.fixed b/tests/Rules/PHPUnit/data/requires-php-version-fixable.php.fixed new file mode 100644 index 0000000..ab3f631 --- /dev/null +++ b/tests/Rules/PHPUnit/data/requires-php-version-fixable.php.fixed @@ -0,0 +1,79 @@ +=8.0.0')] + public function testGreaterOrEqual(): void { + + } + + #[RequiresPhp('>= 8.0.0')] + public function testGreaterOrEqualWithSpace(): void { + + } + + #[RequiresPhp('^8.0.0')] + public function testCaret(): void { + + } + + #[RequiresPhp("8.0")] + public function testDoubleQuoted(): void { + + } + + #[RequiresPhp('8.0')] + #[RequiresPhpunit('>=11.0.0')] + public function testMultipleAttributes(): void { + + } + + #[RequiresPhp('>= 8.0.0')] + #[RequiresPhp('8.1')] + public function testRepeatedAttribute(): void { + + } + + // changing these would change their meaning + #[RequiresPhp('<8.0')] + public function testLessThan(): void { + + } + + #[RequiresPhp('>8.0')] + public function testGreaterThan(): void { + + } + + #[RequiresPhp('~8.0')] + public function testTilde(): void { + + } + + #[RequiresPhp('<=8.5')] + public function testLessOrEqual(): void { + + } +} diff --git a/tests/Rules/PHPUnit/data/requires-php-version-named-argument.php b/tests/Rules/PHPUnit/data/requires-php-version-named-argument.php new file mode 100644 index 0000000..ecda29d --- /dev/null +++ b/tests/Rules/PHPUnit/data/requires-php-version-named-argument.php @@ -0,0 +1,16 @@ +=8.0')] +#[RequiresPhpunit('^11.0')] +class FixableOnClassTest extends TestCase +{ + public function testBar(): void { + + } +} + +#[RequiresPhp('< 7.0')] +class NotFixableOnClassTest extends TestCase +{ + public function testBar(): void { + + } +} diff --git a/tests/Rules/PHPUnit/data/requires-php-version-on-class-fixable.php.fixed b/tests/Rules/PHPUnit/data/requires-php-version-on-class-fixable.php.fixed new file mode 100644 index 0000000..106b9e4 --- /dev/null +++ b/tests/Rules/PHPUnit/data/requires-php-version-on-class-fixable.php.fixed @@ -0,0 +1,24 @@ +=8.0.0')] +#[RequiresPhpunit('^11.0.0')] +class FixableOnClassTest extends TestCase +{ + public function testBar(): void { + + } +} + +#[RequiresPhp('< 7.0')] +class NotFixableOnClassTest extends TestCase +{ + public function testBar(): void { + + } +}