Skip to content

Unable to infer type when using a getter #1157

@Jean85

Description

@Jean85

Summary of a problem or a feature request

I encountered this problem when checking this little piece of code inside a Symfony controller:

        if ($this->tokenStorage->getToken()) {
            return $this->tokenStorage->getToken()->getUser();
        }

PHPStan should infer that, since we checked the getter inside the if, we can safely exclude that the getter returns null here.

Code snippet that reproduces the problem

The code to reproduce the issue is here: https://phpstan.org/r/10c11895e307276cd46b1501d63e1cba

<?php declare(strict_types = 1);

class HelloWorld
{
	private $a;

	/**
	 * @return \DateTimeInterface|null
	 */
	public function getA() 
	{
		return $this->a;
	}
}

$class = new HelloWorld();
if ($class->getA()) {
	echo $class->getA()->format('Y-m-d');
}

Expected output

The expected output should be no errors, instead we get Cannot call method format() on DateTimeInterface|null.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions