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

Model::create() issue with generics #1149

Open
pxlrbt opened this issue Mar 4, 2022 · 3 comments
Open

Model::create() issue with generics #1149

pxlrbt opened this issue Mar 4, 2022 · 3 comments

Comments

@pxlrbt
Copy link

pxlrbt commented Mar 4, 2022

  • Larastan Version: 2.0.1
  • --level used: 5
  • Pull request with failing test:

Description

Not sure whether this is an issue with Larastan, Laravels type definitions or even PhpStan itself:
When running the Model::create() function on a class-string with a template definition, that's causing an issue. Seems like PhpStan cannot figure out the correct type.

Method Domain\Document\Actions\Action::run() should return T of  
    Domain\Document\Models\Document but returns Domain\Document\Models\Document.

Laravel code where the issue was found

Simplified setup for the models:

abstract class Document extends Model {}

class Tour extends Document {}

class Analysis extends Document {}

Actual code which throws error

class Action
{
    /**
     * @template T of \Domain\Document\Models\Document
     * @param  class-string<T>  $documentType
     * @return T
     */
    public function run(string $documentType): Document
    {
        return $documentType::create();
    }
}

But this works:

class Action
{
    /**
     * @template T of \Domain\Document\Models\Document
     * @param  class-string<T>  $documentType
     * @return T
     */
    public function run(string $documentType): Document
    {
        $document = new $documentType();
        $document->save();
        return $document;
    }
}
@canvural
Copy link
Collaborator

canvural commented Mar 4, 2022

Hi,

I tried to replicate this. And I think this can be an issue with PHPStan. I'll try to prepare an example and open an issue there.

Thanks.

@pxlrbt
Copy link
Author

pxlrbt commented Mar 4, 2022

Thank you!

@mwnciau
Copy link

mwnciau commented Feb 14, 2023

Getting the same issue with Model::find()

/**
 * @template T of Model
 * @param class-string<T> $modelClassName
 * @return T|null
 */
function findModel(string $modelClassName, int $id): ?Model
{
    return $modelClassName::find($id);
}

Gives the PHPStan error:

Function findModel() should return (T of Illuminate\Database\Eloquent\Model)|null but returns Illuminate\Database\Eloquent\Model|null.

@canvural Did you ever make that issue in PHPStan?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants