Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#[Before] attribute should not be private in final classes #863

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
16 changes: 16 additions & 0 deletions src/Methods/PrivateInFinalClassRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@

final class PrivateInFinalClassRule implements Rules\Rule
{
/**
* @var array<int, class-string>
*/
private static array $attributesThatIndicateProtectedIsOk = [
\PHPUnit\Framework\Attributes\Before::class,
];

public function getNodeType(): string
{
return Node\Stmt\ClassMethod::class;
Expand Down Expand Up @@ -53,6 +60,15 @@ public function processNode(
return [];
}

// Check attributes
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if (\in_array($attr->name->toString(), self::$attributesThatIndicateProtectedIsOk, true)) {
return [];
}
}
}

$methodName = $node->name->toString();

$parentClass = $containingClass->getNativeReflection()->getParentClass();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Ergebnis\PHPStan\Rules\Test\Fixture\Methods\PrivateInFinalClassRule\Success;

use PHPUnit\Framework\Attributes\Before;

final class FinalClassWithProtectedMethodUsingPhpUnitAttribute
{
#[Before()]
protected function aMethod(): void
{
}
}
1 change: 1 addition & 0 deletions test/Integration/Methods/PrivateInFinalClassRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public static function provideCasesWhereAnalysisShouldSucceed(): iterable
'final-class-with-protected-method-extending-class-with-same-protected-method' => __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Success/FinalClassWithProtectedMethodExtendingClassWithSameProtectedMethod.php',
'final-class-with-protected-method-from-trait' => __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Success/FinalClassWithProtectedMethodFromTrait.php',
'final-class-with-public-method' => __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Success/FinalClassWithPublicMethod.php',
'final-class-with-protected-method-using-php-unit-attribute' => __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Success/FinalClassWithProtectedMethodUsingPhpUnitAttribute.php',
];

foreach ($paths as $description => $path) {
Expand Down