generated from spawnia/php-package-template
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(phpstan): add OneThingPerLineRule #73
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
Open
simbig
wants to merge
6
commits into
master
Choose a base branch
from
one-thing-per-line-phpstan-rule
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9bd1a83
feat(phpstan): add OneThingPerLineRule
abb3c82
Apply php-cs-fixer changes
simbig 73a5a42
fix(phpstan): support PHP 7.4/8.0 in OneThingPerLineRule CI
94480f8
feat(phpstan): handle string interpolation in OneThingPerLineRule
9175bf9
feat(phpstan): treat no-arg method calls as accessors in OneThingPerL…
1b18fe9
fix(phpstan): restore PHP 7.4/8.0 compatibility config
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| parameters: | ||
| excludePaths: | ||
| - ../tests/PHPStan/data/method-chain-nullsafe-violations.php | ||
| - ../tests/PHPStan/data/method-chain-nullsafe-correct.php |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils\PHPStan\Rules; | ||
|
|
||
| use PhpParser\Node; | ||
| use PhpParser\Node\Expr; | ||
| use PhpParser\Node\Expr\CallLike; | ||
| use PhpParser\Node\Expr\MethodCall; | ||
| use PhpParser\Node\Expr\NullsafeMethodCall; | ||
| use PhpParser\Node\Expr\NullsafePropertyFetch; | ||
| use PhpParser\Node\Expr\PropertyFetch; | ||
| use PHPStan\Analyser\Scope; | ||
| use PHPStan\Rules\IdentifierRuleError; | ||
| use PHPStan\Rules\Rule; | ||
| use PHPStan\Rules\RuleErrorBuilder; | ||
|
|
||
| use function Safe\file_get_contents; | ||
|
|
||
| /** | ||
| * @implements Rule<CallLike> | ||
| */ | ||
| final class OneThingPerLineRule implements Rule | ||
| { | ||
| /** @var array<string, string> */ | ||
| private array $fileContentsCache = []; | ||
|
|
||
| public function getNodeType(): string | ||
| { | ||
| return CallLike::class; | ||
| } | ||
|
|
||
| /** @return list<IdentifierRuleError> */ | ||
| public function processNode(Node $node, Scope $scope): array | ||
| { | ||
| if (! $node instanceof MethodCall | ||
| && ! $node instanceof NullsafeMethodCall) { | ||
| return []; | ||
| } | ||
|
|
||
| $var = $node->var; | ||
| if (! $var instanceof MethodCall | ||
| && ! $var instanceof NullsafeMethodCall) { | ||
| return []; | ||
| } | ||
|
|
||
| if ($node->name->getStartLine() !== $var->name->getStartLine()) { | ||
| return []; | ||
| } | ||
|
|
||
| if ($var->getArgs() === []) { | ||
| return []; | ||
| } | ||
|
|
||
| if ($this->isInsideStringInterpolation($scope->getFile(), $node)) { | ||
| return []; | ||
| } | ||
|
|
||
| return [ | ||
| RuleErrorBuilder::message('Method chain calls must each be on their own line.') | ||
| ->identifier('mll.oneThingPerLine') | ||
| ->line($node->name->getStartLine()) | ||
| ->build(), | ||
| ]; | ||
| } | ||
|
|
||
| private function isInsideStringInterpolation(string $file, Expr $node): bool | ||
| { | ||
| $root = $node; | ||
| while ($root instanceof MethodCall | ||
| || $root instanceof NullsafeMethodCall | ||
| || $root instanceof PropertyFetch | ||
| || $root instanceof NullsafePropertyFetch) { | ||
| $root = $root->var; | ||
| } | ||
|
|
||
| $startPos = $root->getStartFilePos(); | ||
| if ($startPos <= 0) { | ||
| return false; | ||
| } | ||
|
|
||
| $this->fileContentsCache[$file] ??= file_get_contents($file); | ||
|
|
||
| return $this->fileContentsCache[$file][$startPos - 1] === '{'; | ||
|
Comment on lines
+76
to
+83
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Können wir nochmal evaluieren ob das anders geht, auf AST Ebene? Mir fallen einige Edge-Cases ein in denen das so implementiert nicht passt: if ($cond) {$bar = 123;} // false-positive
return "bar is $bar"; // false-negative |
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils\Tests\PHPStan; | ||
|
|
||
| use PHPStan\Analyser\Analyser; | ||
| use PHPStan\Analyser\Error; | ||
| use PHPStan\Testing\PHPStanTestCase; | ||
| use PHPUnit\Framework\Attributes\DataProvider; | ||
|
|
||
| final class OneThingPerLineRuleTest extends PHPStanTestCase | ||
| { | ||
| private const ERROR_MESSAGE = 'Method chain calls must each be on their own line.'; | ||
|
|
||
| /** @return iterable<array{0: string, 1: array<int, array<int, string>>}> */ | ||
| public static function dataIntegrationTests(): iterable | ||
| { | ||
| self::getContainer(); | ||
|
|
||
| yield [__DIR__ . '/data/method-chain-violations.php', [ | ||
| 26 => [self::ERROR_MESSAGE], | ||
| 31 => [self::ERROR_MESSAGE], | ||
| 38 => [self::ERROR_MESSAGE], | ||
| 45 => [self::ERROR_MESSAGE], | ||
| ]]; | ||
|
|
||
| yield [__DIR__ . '/data/method-chain-correct.php', []]; | ||
|
|
||
| if (PHP_VERSION_ID >= 80000) { | ||
| yield [__DIR__ . '/data/method-chain-nullsafe-violations.php', [ | ||
| 19 => [self::ERROR_MESSAGE], | ||
| 24 => [self::ERROR_MESSAGE], | ||
| ]]; | ||
|
|
||
| yield [__DIR__ . '/data/method-chain-nullsafe-correct.php', []]; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param array<int, array<int, string>> $expectedErrors | ||
| * | ||
| * @dataProvider dataIntegrationTests | ||
| */ | ||
| #[DataProvider('dataIntegrationTests')] | ||
| public function testIntegration(string $file, array $expectedErrors): void | ||
| { | ||
| $errors = $this->runAnalyse($file); | ||
|
|
||
| $ourErrors = array_filter( | ||
| $errors, | ||
| static fn (Error $error): bool => str_contains($error->getMessage(), self::ERROR_MESSAGE), | ||
| ); | ||
|
|
||
| if ($expectedErrors === []) { | ||
| self::assertEmpty($ourErrors, 'Should not report errors for correct code'); | ||
| } else { | ||
| self::assertNotEmpty($ourErrors, 'Should detect method chain violations'); | ||
| $this->assertSameErrorMessages($expectedErrors, $ourErrors); | ||
| } | ||
| } | ||
|
|
||
| /** @return array<Error> */ | ||
| private function runAnalyse(string $file): array | ||
| { | ||
| $file = self::getFileHelper()->normalizePath($file); | ||
|
|
||
| /** @var Analyser $analyser */ | ||
| $analyser = self::getContainer()->getByType(Analyser::class); | ||
|
|
||
| return $analyser->analyse([$file])->getErrors(); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<int, array<int, string>> $expectedErrors | ||
| * @param array<Error> $errors | ||
| */ | ||
| private function assertSameErrorMessages(array $expectedErrors, array $errors): void | ||
| { | ||
| foreach ($errors as $error) { | ||
| $errorLine = $error->getLine() ?? 0; | ||
| $errorMessage = $error->getMessage(); | ||
|
|
||
| self::assertArrayHasKey($errorLine, $expectedErrors, "Unexpected error at line {$errorLine}: {$errorMessage}"); | ||
| self::assertContains($errorMessage, $expectedErrors[$errorLine]); | ||
| } | ||
| } | ||
|
|
||
| /** @return array<string> */ | ||
| public static function getAdditionalConfigFiles(): array | ||
| { | ||
| return [ | ||
| __DIR__ . '/phpstan-one-thing-per-line-test.neon', | ||
| ]; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils\Tests\PHPStan\data; | ||
|
|
||
| class MethodChainCorrect | ||
| { | ||
| public function foo(int $arg = 0): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function bar(): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function baz(): void {} | ||
|
|
||
| public function name(): string | ||
| { | ||
| return 'test'; | ||
| } | ||
|
|
||
| public static function create(): self | ||
| { | ||
| return new self(); | ||
| } | ||
|
|
||
| /** @var self */ | ||
| public object $relation; | ||
|
|
||
| public function singleMethodCall(): void | ||
| { | ||
| $this->foo(); | ||
| } | ||
|
|
||
| public function staticPlusSingleMethod(): void | ||
| { | ||
| self::create()->foo(); | ||
| } | ||
|
|
||
| public function propertyAccessPlusMethod(): void | ||
| { | ||
| $this->relation->foo(); | ||
| } | ||
|
|
||
| public function properlySplitChain(): void | ||
| { | ||
| $this->foo() | ||
| ->bar(); | ||
| } | ||
|
|
||
| public function properlySplitThreeChain(): void | ||
| { | ||
| $this->foo() | ||
| ->bar() | ||
| ->baz(); | ||
| } | ||
|
|
||
| public function newExpressionPlusSingleMethod(): void | ||
| { | ||
| (new self())->baz(); | ||
| } | ||
|
|
||
| public function multilineArgsWithSplitContinuation(): void | ||
| { | ||
| $this->foo( | ||
| 1 | ||
| )->bar(); | ||
| } | ||
|
|
||
| public function noArgAccessorThenAction(): void | ||
| { | ||
| $this->foo()->baz(); | ||
| } | ||
|
|
||
| public function noArgAccessorThenActionWithArgs(): void | ||
| { | ||
| $this->foo()->foo(1); | ||
| } | ||
|
|
||
| public function noArgChainAllAccessors(): void | ||
| { | ||
| $this->foo()->bar()->baz(); | ||
| } | ||
|
|
||
| public function staticPlusNoArgChain(): void | ||
| { | ||
| self::create()->foo()->bar(); | ||
| } | ||
|
|
||
| public function propertyThenNoArgAccessorThenAction(): void | ||
| { | ||
| $this->relation->foo()->baz(); | ||
| } | ||
|
|
||
| public function noArgAccessorChainInArrowFunction(): void | ||
| { | ||
| /** @var list<self> $items */ | ||
| $items = []; | ||
| array_map(fn (self $x): self => $x->foo()->bar(), $items); | ||
| } | ||
|
|
||
| public function noArgAccessorChainInClosure(): void | ||
| { | ||
| /** @var list<self> $items */ | ||
| $items = []; | ||
| array_map(fn (self $x): int => spl_object_id($x->foo()->bar()), $items); | ||
| } | ||
|
|
||
| public function chainInsideStringInterpolation(): string | ||
| { | ||
| return "value: {$this->foo()->name()}"; | ||
| } | ||
|
|
||
| public function properlySplitChainInClosure(): void | ||
| { | ||
| /** @var list<self> $items */ | ||
| $items = []; | ||
| array_map(fn (self $x): self => $x->foo() | ||
| ->bar(), $items); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils\Tests\PHPStan\data; | ||
|
|
||
| class MethodChainNullsafeCorrect | ||
| { | ||
| public function foo(): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function bar(): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function properlySplitNullSafeChain(?self $nullable): void | ||
| { | ||
| $nullable?->foo() | ||
| ?->bar(); | ||
| } | ||
|
|
||
| public function noArgNullSafeChain(?self $nullable): void | ||
| { | ||
| $nullable?->foo()?->bar(); | ||
| } | ||
|
|
||
| public function mixedNoArgNullSafeChain(?self $nullable): void | ||
| { | ||
| $nullable?->foo()->bar(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils\Tests\PHPStan\data; | ||
|
|
||
| class MethodChainNullsafeViolations | ||
| { | ||
| public function foo(int $arg = 0): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function bar(int $arg = 0): self | ||
| { | ||
| return $this; | ||
| } | ||
|
|
||
| public function nullSafeChainWithArgs(?self $nullable): void | ||
| { | ||
| $nullable?->foo(1)?->bar(2); | ||
| } | ||
|
|
||
| public function mixedNullSafeChainWithArgs(?self $nullable): void | ||
| { | ||
| $nullable?->foo(1)->bar(2); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Eine lange Kette von Property-Zugriffen würde für mich auch unter
OneThingPerLinefallen, ist aber nichtCallLike. PHPStan Regeln gehen aber immer nur auf einen NodeType, oder? Daher würde ich den Klassennamen spezifischer wählen. Den Identifiermll.oneThingPerLinefinde ich in Ordnung, den könnten wir in mehreren Klassen mit verschiedener Message verwenden.