Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
Expand Down
116 changes: 108 additions & 8 deletions src/Rules/PHPUnit/AttributeVersionRequirementHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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<operator>>=|\^)(?P<space>\s*)(?P<version>\d+(?:\.\d+){0,2})$/';

private const VERSION_COMPARISON = "/(?P<operator>!=|<|<=|<>|=|==|>|>=)?\s*(?P<version>[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?)[ \t]*\r?$/m";

private PHPUnitVersion $PHPUnitVersion;
Expand Down Expand Up @@ -59,34 +70,45 @@ public function __construct(

/**
* @param array<ReflectionAttribute> $attributes
* @param array<Node\AttributeGroup> $attrGroups AST attribute groups of the node $attributes were read from
*
* @return list<IdentifierRuleError>
*/
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 (
Expand Down Expand Up @@ -180,6 +202,84 @@ public function checkVersionRequirement(array $attributes, Scope $scope): array
return $errors;
}

/**
* @param array<Node\AttributeGroup> $attrGroups
*
* @return array<string, list<Node\Attribute>>
*/
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<IdentifierRuleError> $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<Version>
*/
Expand Down
1 change: 1 addition & 0 deletions src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
Expand Down
48 changes: 48 additions & 0 deletions tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
79 changes: 79 additions & 0 deletions tests/Rules/PHPUnit/data/requires-php-version-fixable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace RequiresPhpVersionFixable;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\RequiresPhp;
use PHPUnit\Framework\Attributes\RequiresPhpunit;

class FixableTest extends TestCase
{
#[RequiresPhp('8')]
public function testMajorOnly(): void {

}

#[RequiresPhp('8.0')]
public function testMissingOperator(): void {

}

// not reported, as it is not numeric
#[RequiresPhp('8.0.1')]
public function testCompleteMissingOperator(): void {

}

#[RequiresPhp('>=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 {

}
}
Loading