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

Prevent false positive for NoUnnecessaryCollectionCallRule when using arrow functions #1483

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- feat: conditional return types for `Eloquent\Collection::find()` by @sebdesign
- feat: add support for generic paginators by @erikgaal
- feat: add support for encrypted and parameterized eloquent casts by @jdjfisher
- fix: prevent false positive for NoUnnecessaryCollectionCallRule when using arrow functions by @JeppeKnockaert

## [2.2.0] - 2022-08-31

Expand Down
2 changes: 1 addition & 1 deletion src/Rules/NoUnnecessaryCollectionCallRule.php
Expand Up @@ -204,7 +204,7 @@ public function processNode(Node $node, Scope $scope): array
// 'contains' can also be called with Model instances or keys as its first argument
/** @var \PhpParser\Node\Arg[] $args */
$args = $node->args;
if (count($args) === 1 && ! ($args[0]->value instanceof Node\Expr\Closure)) {
if (count($args) === 1 && ! ($args[0]->value instanceof Node\FunctionLike)) {
return [$this->formatError($name->toString())];
}

Expand Down
20 changes: 20 additions & 0 deletions tests/Rules/Data/CorrectCollectionCalls.php
Expand Up @@ -72,6 +72,16 @@ public function testContainsClosure(): bool
});
}

/**
* Can't analyze the arrow function as a parameter to contains, so should not throw any error.
*
* @return bool
*/
public function testContainsArrowFunction(): bool
{
return User::where('id', '>', 1)->get()->contains(fn (User $user): bool => $user->id === 2);
}

/**
* Can't analyze the closure as a parameter to first, so should not throw any error.
*
Expand All @@ -84,6 +94,16 @@ public function testFirstClosure(): ?User
});
}

/**
* Can't analyze the arrow function as a parameter to first, so should not throw any error.
*
* @return User|null
*/
public function testFirstArrowFunction(): ?User
{
return User::where('id', '>', 1)->get()->first(fn (User $user): bool => $user->id === 2);
}

/** @phpstan-return mixed */
public function testAggregateNoArgs()
{
Expand Down