Lars Nyström
Lars Nyström

Reputation: 6373

How can I configure return type of third party method with phpstan?

I'm working on a Laravel application. In Laravel you can get the currently authenticated user with Auth::user(). The return type of Auth::user() is Authenticatable (which is an interface provided by Laravel), but I know this function will always return an implementation of a more specific interface.

How can I configure phpstan so that it knows the return type of Auth::user() is this more specific interface?

Upvotes: 1

Views: 1224

Answers (2)

TroyeKizzz
TroyeKizzz

Reputation: 1

Write a stub for the Auth facade. For example, if you want to overwrite the return type from \Illuminate\Contracts\Auth\Authenticatable to \App\User, create the following stub:

<?php

namespace Illuminate\Support\Facades;

/**
 * @method static \App\User|null user()
 */
class Auth extends Facade {}

More on how to create stubs here.

Upvotes: 0

Can Vural
Can Vural

Reputation: 2067

There are couple of ways you can do this.

  • You can use the Laravel extension for PHPStan called Larastan. This extension should help to understand the correct return type of Auth::user()

  • You can write a DynamicMethodReturnTypeExtension More details about it are here.

  • You can write a stub file that will overwrite the return type of user method. You can read more about stub files here.

Upvotes: 2

Related Questions