Skip to content

Commit f9b30da

Browse files
committed
fixup! AssertEqualsIsDiscouragedRule
1 parent bef077d commit f9b30da

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

src/Rules/PHPUnit/AssertEqualsIsDiscouragedRule.php

+17-3
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,24 @@ public function processNode(Node $node, Scope $scope): array
6363
];
6464
}
6565

66-
$fileContents = explode("\n", file_get_contents($scope->getFile()));
67-
$previousLine = $fileContents[$node->getLine() - 2];
66+
/** @var \PhpParser\Comment[] $comments */
67+
$comments = $node->getAttribute('comments');
6868

69-
if (!preg_match('~^\s+//\s+assertEquals because(.*)~', $previousLine)) {
69+
if (count($comments) === 0) {
70+
return [
71+
'You should use assertSame instead of assertEquals. Or it should have a comment above with explanation: // assertEquals because ...',
72+
];
73+
}
74+
75+
$comment = $comments[0];
76+
// the comment should be on the line above the assertEquals()
77+
if ($comment->getLine() !== ($node->getLine() - 1)) {
78+
return [
79+
'You should use assertSame instead of assertEquals. Or it should have a comment above with explanation: // assertEquals because ...',
80+
];
81+
}
82+
83+
if (!preg_match('~^//\s+assertEquals because(.*)~', $comment->getReformattedText())) {
7084
return [
7185
'You should use assertSame instead of assertEquals. Or it should have a comment above with explanation: // assertEquals because ...',
7286
];

tests/Rules/PHPUnit/AssertEqualsIsDiscouragedRuleTest.php

+4
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ public function testRule(): void
4343
'You should use assertSame instead of assertEquals. Or it should have a comment above with explanation: // assertEquals because ...',
4444
24,
4545
],
46+
[
47+
'You should use assertSame instead of assertEquals. Or it should have a comment above with explanation: // assertEquals because ...',
48+
28,
49+
],
4650
]);
4751
}
4852

tests/Rules/PHPUnit/data/assert-equals-is-discouraged.php

+4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ public function testAssertEqualsIsDiscouraged()
2323
// with incorrect comment
2424
$this->assertEquals(1, '1');
2525

26+
// assertEquals because I want it! But sadly, the comment is not just above the assert.
27+
28+
$this->assertEquals(1, '1');
29+
2630
// assertEquals because I want it!
2731
$this->assertEquals(1, '1');
2832
}

0 commit comments

Comments
 (0)