Skip to content

Narrowing type using @phpstan-assert-if-true doesn't work with $this on abstract class #13358

@ruudk

Description

@ruudk

Bug report

<?php declare(strict_types=1);

/**
 * @phpstan-sealed SystemActor|AnonymousVisitorActor
 */
abstract class Actor
{
    /**
     * @phpstan-assert-if-true SystemActor $this
     */
    public function isSystem() : bool
    {
        return $this instanceof SystemActor;
    }

    /**
     * @phpstan-assert-if-true AnonymousVisitorActor $this
     */
    public function isAnonymousVisitor() : bool
    {
        return $this instanceof AnonymousVisitorActor;
    }
}

class SystemActor extends Actor
{
}

class AnonymousVisitorActor extends Actor
{
}

$actor = mt_rand(0, 1) === 1 ? new SystemActor() : new AnonymousVisitorActor();
\PHPStan\dumpType($actor);

if ($actor->isSystem()) {
    \PHPStan\dumpType($actor);
} else {
    \PHPStan\dumpType($actor);
}

It will always be AnonymousVisitorActor|SystemActor

Code snippet that reproduces the problem

https://phpstan.org/r/f8b4723c-7774-49d6-beee-2e4fb0c3c312

Expected output

I expected SystemActor in the if condition and AnonymousVisitorActor in the else condition.

Did PHPStan help you today? Did it make you happy in any way?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions