Skip to content

Commit

Permalink
Fix not respecting return type of overridden Request::user() method.
Browse files Browse the repository at this point in the history
  • Loading branch information
mad-briller committed Feb 19, 2024
1 parent b1f5610 commit 6a00d74
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/ReturnTypes/RequestUserExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
use Illuminate\Http\Request;
use Larastan\Larastan\Concerns\HasContainer;
use Larastan\Larastan\Concerns\LoadsAuthModel;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PhpParser\Node\Expr\MethodCall;

/**
* @internal
Expand Down Expand Up @@ -48,6 +48,10 @@ public function getTypeFromMethodCall(
MethodCall $methodCall,
Scope $scope
): Type {
if ($methodReflection->getDeclaringClass()->getName() !== Request::class) {
return ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType();
}

$config = $this->getContainer()->get('config');
$authModel = null;

Expand Down
1 change: 1 addition & 0 deletions tests/Type/GeneralTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public static function dataFileAsserts(): iterable
yield from self::gatherAssertTypes(__DIR__.'/data/view-exists.php');
yield from self::gatherAssertTypes(__DIR__.'/data/view.php');
yield from self::gatherAssertTypes(__DIR__.'/data/where-relation.php');
yield from self::gatherAssertTypes(__DIR__.'/data/bug-1718.php');

if (version_compare(LARAVEL_VERSION, '10.15.0', '>=')) {
yield from self::gatherAssertTypes(__DIR__.'/data/model-l10-15.php');
Expand Down
31 changes: 31 additions & 0 deletions tests/Type/data/bug-1718.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Bug1718;

use Illuminate\Foundation\Http\FormRequest;
use App\User;
use function PHPStan\Testing\assertType;

class AuthedRequest extends FormRequest
{
public function authorize(): bool
{
return parent::user() instanceof User;
}

public function user($guard = null): User
{
$user = parent::user($guard);
if (!$user instanceof User) {
abort(403);
}

return $user;
}
}

function test(AuthedRequest $request, FormRequest $formRequest): void
{
assertType('App\User', $request->user());
assertType('App\User|null', $formRequest->user());
}

0 comments on commit 6a00d74

Please sign in to comment.