Skip to content

Commit

Permalink
TraitAttributeClassRule
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Nov 18, 2020
1 parent d6c5e44 commit 9656bc5
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions conf/config.level0.neon
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ rules:
- PHPStan\Rules\Classes\InvalidPromotedPropertiesRule
- PHPStan\Rules\Classes\NewStaticRule
- PHPStan\Rules\Classes\NonClassAttributeClassRule
- PHPStan\Rules\Classes\TraitAttributeClassRule
- PHPStan\Rules\Exceptions\ThrowExpressionRule
- PHPStan\Rules\Functions\ArrowFunctionReturnNullsafeByRefRule
- PHPStan\Rules\Functions\CallToFunctionParametersRule
Expand Down
37 changes: 37 additions & 0 deletions src/Rules/Classes/TraitAttributeClassRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Classes;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

/**
* @implements Rule<Node\Stmt\Trait_>
*/
class TraitAttributeClassRule implements Rule
{

public function getNodeType(): string
{
return Node\Stmt\Trait_::class;
}

public function processNode(Node $node, Scope $scope): array
{
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$name = $attr->name->toLowerString();
if ($name === 'attribute') {
return [
RuleErrorBuilder::message('Trait cannot be an Attribute class.')->build(),
];
}
}
}

return [];
}

}
32 changes: 32 additions & 0 deletions tests/PHPStan/Rules/Classes/TraitAttributeClassRuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Classes;

use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;

/**
* @extends RuleTestCase<TraitAttributeClassRule>
*/
class TraitAttributeClassRuleTest extends RuleTestCase
{

protected function getRule(): Rule
{
return new TraitAttributeClassRule();
}

public function testRule(): void
{
if (!self::$useStaticReflectionProvider && PHP_VERSION_ID < 80000) {
$this->markTestSkipped('Test requires PHP 8.0.');
}
$this->analyse([__DIR__ . '/data/non-class-attribute-class.php'], [
[
'Trait cannot be an Attribute class.',
11,
],
]);
}

}

0 comments on commit 9656bc5

Please sign in to comment.