Skip to content

Commit 8c16263

Browse files
authored
Some #[RequiresPhp] errors are autofixable (#362)
* Some `#[RequiresPhp]` errors are autofixable * Attach requirement version fix to first error per attribute only Several errors fixing the same string node caused a MergeConflictException. * Attach requirement version fix to first error per attribute only Several errors fixing the same string node caused a MergeConflictException. * Revert "Attach requirement version fix to first error per attribute only" This reverts commit ec258ff. * Don't crash on named arguments * Don't auto-fix versions without operator, as this can change meaning when tests will run * remove unnecessary work
1 parent f4a0b7b commit 8c16263

10 files changed

Lines changed: 389 additions & 8 deletions

‎src/Rules/PHPUnit/AttributeRequiresPhpVersionRule.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ public function processNode(Node $node, Scope $scope): array
5050
$reflectionMethod->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhp'),
5151
$reflectionMethod->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhpunit'),
5252
),
53+
$node->getOriginalNode()->attrGroups,
5354
$scope,
5455
);
5556
}

‎src/Rules/PHPUnit/AttributeVersionRequirementHelper.php‎

Lines changed: 108 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use PharIo\Version\UnsupportedVersionConstraintException;
66
use PharIo\Version\Version;
77
use PharIo\Version\VersionConstraintParser;
8+
use PhpParser\Node;
9+
use PhpParser\Node\Scalar\String_;
810
use PHPStan\Analyser\Scope;
911
use PHPStan\BetterReflection\Reflection\ReflectionAttribute;
1012
use PHPStan\Php\ConfiguredPhpVersionRangeHelper;
@@ -13,6 +15,8 @@
1315
use PHPStan\Rules\RuleErrorBuilder;
1416
use PHPStan\ShouldNotHappenException;
1517
use function count;
18+
use function explode;
19+
use function implode;
1620
use function is_numeric;
1721
use function is_string;
1822
use function preg_match;
@@ -24,6 +28,13 @@
2428
final class AttributeVersionRequirementHelper
2529
{
2630

31+
/**
32+
* Matches requirements whose version can be completed to major.minor.patch
33+
* without changing their meaning, e.g. `>=8`, `>=8.1` or `^8.1`.
34+
* Versions without an operator are deliberately not matched.
35+
*/
36+
private const FIXABLE_VERSION_REQUIREMENT = '/^(?P<operator>>=|\^)(?P<space>\s*)(?P<version>\d+(?:\.\d+){0,2})$/';
37+
2738
private const VERSION_COMPARISON = "/(?P<operator>!=|<|<=|<>|=|==|>|>=)?\s*(?P<version>[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?)[ \t]*\r?$/m";
2839

2940
private PHPUnitVersion $PHPUnitVersion;
@@ -59,34 +70,45 @@ public function __construct(
5970

6071
/**
6172
* @param array<ReflectionAttribute> $attributes
73+
* @param array<Node\AttributeGroup> $attrGroups AST attribute groups of the node $attributes were read from
6274
*
6375
* @return list<IdentifierRuleError>
6476
*/
65-
public function checkVersionRequirement(array $attributes, Scope $scope): array
77+
public function checkVersionRequirement(array $attributes, array $attrGroups, Scope $scope): array
6678
{
6779
$errors = [];
6880
$parser = new VersionConstraintParser();
81+
$attributeNodes = $this->groupAttributeNodesByName($attrGroups);
82+
$attributeIndexes = [];
6983
foreach ($attributes as $attr) {
84+
$attributeIndex = $attributeIndexes[$attr->getName()] ?? 0;
85+
$attributeIndexes[$attr->getName()] = $attributeIndex + 1;
86+
7087
$args = $attr->getArguments();
7188
if (count($args) !== 1) {
7289
continue;
7390
}
7491

75-
// the following block is mimicing PHPUnit version parsing
76-
// see https://github.com/sebastianbergmann/phpunit/blob/43c2cd7b96ee1e800b35e4df23b419a88b53111d/src/Metadata/Version/Requirement.php
77-
78-
// named arguments are handled just to make sure we don't crash on them.
92+
// phpunit does not support named arguments.
93+
// we handle them here just to make sure we don't crash on them.
7994
$versionRequirement = $args[0] ?? $args['versionRequirement'] ?? null;
8095
if (!is_string($versionRequirement)) {
8196
continue;
8297
}
8398

99+
// the following block is mimicing PHPUnit version parsing
100+
// see https://github.com/sebastianbergmann/phpunit/blob/43c2cd7b96ee1e800b35e4df23b419a88b53111d/src/Metadata/Version/Requirement.php
101+
84102
if ($this->warnAboutIncompleteVersion($versionRequirement)) {
85-
$errors[] = RuleErrorBuilder::message(
103+
$errorBuilder = RuleErrorBuilder::message(
86104
sprintf('Version requirement %s is incomplete. Expect a version composed of major, minor and patch.', $versionRequirement),
87105
)
88-
->identifier('phpunit.attributeRequiresPhpVersion')
89-
->build();
106+
->identifier('phpunit.attributeRequiresPhpVersion');
107+
$versionNode = $this->getFixableVersionNode(
108+
$attributeNodes[$attr->getName()][$attributeIndex] ?? null,
109+
$versionRequirement,
110+
);
111+
$errors[] = $this->buildError($errorBuilder, $versionNode);
90112
}
91113

92114
if (
@@ -180,6 +202,84 @@ public function checkVersionRequirement(array $attributes, Scope $scope): array
180202
return $errors;
181203
}
182204

205+
/**
206+
* @param array<Node\AttributeGroup> $attrGroups
207+
*
208+
* @return array<string, list<Node\Attribute>>
209+
*/
210+
private function groupAttributeNodesByName(array $attrGroups): array
211+
{
212+
$attributeNodes = [];
213+
foreach ($attrGroups as $attrGroup) {
214+
foreach ($attrGroup->attrs as $attributeNode) {
215+
$attributeNodes[$attributeNode->name->toString()][] = $attributeNode;
216+
}
217+
}
218+
219+
return $attributeNodes;
220+
}
221+
222+
/**
223+
* Returns the string literal holding the version requirement, when it is a plain literal in the analysed file.
224+
*/
225+
private function getFixableVersionNode(?Node\Attribute $attributeNode, string $versionRequirement): ?String_
226+
{
227+
if ($attributeNode === null || count($attributeNode->args) !== 1) {
228+
return null;
229+
}
230+
231+
$versionNode = $attributeNode->args[0]->value;
232+
if (!$versionNode instanceof String_) {
233+
return null;
234+
}
235+
236+
// make sure the AST node is the one the reflection attribute was read from
237+
if ($versionNode->value !== $versionRequirement) {
238+
return null;
239+
}
240+
241+
return $versionNode;
242+
}
243+
244+
/**
245+
* @param RuleErrorBuilder<IdentifierRuleError> $errorBuilder
246+
*/
247+
private function buildError(RuleErrorBuilder $errorBuilder, ?String_ $versionNode): IdentifierRuleError
248+
{
249+
if ($versionNode === null) {
250+
return $errorBuilder->build();
251+
}
252+
253+
$fixedVersionRequirement = $this->fixVersionRequirement($versionNode->value);
254+
if ($fixedVersionRequirement === null) {
255+
return $errorBuilder->build();
256+
}
257+
258+
return $errorBuilder->fixNode(
259+
$versionNode,
260+
static fn (String_ $versionNode): String_ => new String_($fixedVersionRequirement, ['kind' => $versionNode->getAttribute('kind')]),
261+
)->build();
262+
}
263+
264+
/**
265+
* Completes the version to major.minor.patch.
266+
* Only applied where the meaning of the requirement stays the same.
267+
* Versions without an operator are not fixed.
268+
*/
269+
private function fixVersionRequirement(string $versionRequirement): ?string
270+
{
271+
if (preg_match(self::FIXABLE_VERSION_REQUIREMENT, $versionRequirement, $matches) !== 1) {
272+
return null;
273+
}
274+
275+
$versionParts = explode('.', $matches['version']);
276+
while (count($versionParts) < 3) {
277+
$versionParts[] = '0';
278+
}
279+
280+
return $matches['operator'] . $matches['space'] . implode('.', $versionParts);
281+
}
282+
183283
/**
184284
* @return list<Version>
185285
*/

‎src/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRule.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public function processNode(Node $node, Scope $scope): array
4141
$classReflection->getNativeReflection()->getBetterReflection()->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhp'),
4242
$classReflection->getNativeReflection()->getBetterReflection()->getAttributesByName('PHPUnit\Framework\Attributes\RequiresPhpunit'),
4343
),
44+
$node->getOriginalNode()->attrGroups,
4445
$scope,
4546
);
4647
}

‎tests/Rules/PHPUnit/AttributeRequiresPhpVersionRuleTest.php‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,54 @@ public function testNonStringArguments(): void
207207
]);
208208
}
209209

210+
public function testFixIncompleteVersion(): void
211+
{
212+
$this->phpunitMajorVersion = 13;
213+
$this->phpunitMinorVersion = 0;
214+
$this->deprecationRulesInstalled = false;
215+
$this->warnAboutIncompleteVersion = true;
216+
217+
$this->fix(__DIR__ . '/data/requires-php-version-fixable.php', __DIR__ . '/data/requires-php-version-fixable.php.fixed');
218+
}
219+
220+
public function testDoNotFixVersionWithoutOperator(): void
221+
{
222+
$this->phpunitMajorVersion = 12;
223+
$this->phpunitMinorVersion = 4;
224+
$this->deprecationRulesInstalled = true;
225+
226+
$this->fix(__DIR__ . '/data/requires-php-version.php', __DIR__ . '/data/requires-php-version.php');
227+
}
228+
229+
public function testNamedArgument(): void
230+
{
231+
$this->phpunitMajorVersion = 13;
232+
$this->phpunitMinorVersion = 0;
233+
$this->deprecationRulesInstalled = false;
234+
$this->warnAboutIncompleteVersion = true;
235+
236+
$this->analyse([__DIR__ . '/data/requires-php-version-named-argument.php'], [
237+
[
238+
'Version requirement 8.0 is incomplete. Expect a version composed of major, minor and patch.',
239+
12,
240+
],
241+
[
242+
'Version requirement 8.0 is missing operator.',
243+
12,
244+
],
245+
]);
246+
}
247+
248+
public function testFixNamedArgument(): void
249+
{
250+
$this->phpunitMajorVersion = 13;
251+
$this->phpunitMinorVersion = 0;
252+
$this->deprecationRulesInstalled = false;
253+
$this->warnAboutIncompleteVersion = true;
254+
255+
$this->fix(__DIR__ . '/data/requires-php-version-named-argument.php', __DIR__ . '/data/requires-php-version-named-argument.php');
256+
}
257+
210258
protected function getRule(): Rule
211259
{
212260
$phpunitVersion = new PHPUnitVersion($this->phpunitMajorVersion, $this->phpunitMinorVersion);

‎tests/Rules/PHPUnit/ClassAttributeRequiresPhpVersionRuleTest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ public function testNonStringArguments(): void
6767
]);
6868
}
6969

70+
public function testFixIncompleteVersion(): void
71+
{
72+
$this->phpunitMajorVersion = 12;
73+
$this->phpunitMinorVersion = 5;
74+
$this->warnAboutIncompleteVersion = true;
75+
76+
$this->fix(__DIR__ . '/data/requires-php-version-on-class-fixable.php', __DIR__ . '/data/requires-php-version-on-class-fixable.php.fixed');
77+
}
78+
7079
protected function getRule(): Rule
7180
{
7281
$phpunitVersion = new PHPUnitVersion($this->phpunitMajorVersion, $this->phpunitMinorVersion);
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
namespace RequiresPhpVersionFixable;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use PHPUnit\Framework\Attributes\RequiresPhp;
7+
use PHPUnit\Framework\Attributes\RequiresPhpunit;
8+
9+
class FixableTest extends TestCase
10+
{
11+
#[RequiresPhp('8')]
12+
public function testMajorOnly(): void {
13+
14+
}
15+
16+
#[RequiresPhp('8.0')]
17+
public function testMissingOperator(): void {
18+
19+
}
20+
21+
// not reported, as it is not numeric
22+
#[RequiresPhp('8.0.1')]
23+
public function testCompleteMissingOperator(): void {
24+
25+
}
26+
27+
#[RequiresPhp('>=8.0')]
28+
public function testGreaterOrEqual(): void {
29+
30+
}
31+
32+
#[RequiresPhp('>= 8')]
33+
public function testGreaterOrEqualWithSpace(): void {
34+
35+
}
36+
37+
#[RequiresPhp('^8.0')]
38+
public function testCaret(): void {
39+
40+
}
41+
42+
#[RequiresPhp("8.0")]
43+
public function testDoubleQuoted(): void {
44+
45+
}
46+
47+
#[RequiresPhp('8.0')]
48+
#[RequiresPhpunit('>=11')]
49+
public function testMultipleAttributes(): void {
50+
51+
}
52+
53+
#[RequiresPhp('>= 8.0.0')]
54+
#[RequiresPhp('8.1')]
55+
public function testRepeatedAttribute(): void {
56+
57+
}
58+
59+
// changing these would change their meaning
60+
#[RequiresPhp('<8.0')]
61+
public function testLessThan(): void {
62+
63+
}
64+
65+
#[RequiresPhp('>8.0')]
66+
public function testGreaterThan(): void {
67+
68+
}
69+
70+
#[RequiresPhp('~8.0')]
71+
public function testTilde(): void {
72+
73+
}
74+
75+
#[RequiresPhp('<=8.5')]
76+
public function testLessOrEqual(): void {
77+
78+
}
79+
}

0 commit comments

Comments
 (0)