Merge pull request #78 from psalm/fix-query-builder-calls

fix: relations should also be able to call query builder methods
This commit is contained in:
feek 2020-06-06 23:54:11 -07:00 committed by GitHub
commit af5e562210
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 1 deletions

View File

@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use PhpParser\Node\Expr\MethodCall;
use Psalm\CodeLocation;
use Psalm\Context;
@ -51,7 +52,10 @@ final class RelationReturnTypeProvider implements MethodReturnTypeProviderInterf
// returns an instance of ITSELF, rather than the instance of the builder. That explains this nonsense
// If this method name is on the builder object, proxy it over there
if ($source->getCodebase()->methods->methodExists(new MethodIdentifier(Builder::class, $method_name_lowercase))) {
if ($source->getCodebase()->methods->methodExists(new MethodIdentifier(Builder::class, $method_name_lowercase)) ||
$source->getCodebase()->methods->methodExists(new MethodIdentifier(QueryBuilder::class, $method_name_lowercase))
) {
if (!$template_type_parameters) {
return null;
}

View File

@ -145,3 +145,22 @@ Feature: Eloquent Builder Types
Then I see these errors
| MixedInferredReturnType | Could not verify return type 'Illuminate\Database\Eloquent\Builder<User>' for UserRepository::test_failure |
| MixedReturnStatement | Could not infer a return type |
Scenario: can call methods on underlying query builder
Given I have the following code
"""
<?php declare(strict_types=1);
use Tests\Psalm\LaravelPlugin\Models\User;
use \Illuminate\Database\Eloquent\Builder;
/**
* @psalm-param Builder<User> $builder
* @psalm-return Builder<User>
*/
function test(Builder $builder): Builder {
return $builder->orderBy('id', 'ASC');
}
"""
When I run Psalm
Then I see no errors

View File

@ -214,3 +214,17 @@ Feature: Eloquent Relation Types
"""
When I run Psalm
Then I see no errors
Scenario: Relationships return themselves when the proxied method is a query builder method
Given I have the following code
"""
/**
* @param HasOne<Phone> $relationship
* @psalm-return HasOne<Phone>
*/
function test(HasOne $relationship): HasOne {
return $relationship->orderBy('id', 'ASC');
}
"""
When I run Psalm
Then I see no errors