psalm icon indicating copy to clipboard operation
psalm copied to clipboard

false positive PossiblyNullPropertyFetch?

Open wickedOne opened this issue 1 year ago • 3 comments

see code example: https://psalm.dev/r/960a481894

shouldn't the fact that $compared is true not infer that $visitorUser is not null?

wickedOne avatar Feb 13 '24 06:02 wickedOne

I found these snippets:

https://psalm.dev/r/960a481894
<?php
class User {
    public function __construct(
        public ?int $id = null,
    ) {
    }
}
class Visitor {
	public function __construct(
        public ?User $user = null,
    ) {
    }
}
class Employee {
	public function __construct(
        public ?User $user = null,
    ) {
    }
}

class Foo
{
	public function __construct(
        public Visitor $visitor,
        public Employee $employee,
    ) {
    }
    
    public function compare(): mixed
    {
        $visitorUser = $this->visitor->user;
        $employeeUser = $this->employee->user;
    	$compared = $visitorUser !== null && $employeeUser === $visitorUser;
        
        if ($compared === false) {
            return 0;
        }
        
        return $visitorUser->id;
    }
}
Psalm output (using commit cb0e6a1):

ERROR: PossiblyNullPropertyFetch - 39:16 - Cannot get property on possibly null variable $visitorUser of type User|null

psalm-github-bot[bot] avatar Feb 13 '24 06:02 psalm-github-bot[bot]

This works: https://psalm.dev/r/235b00ed02

weirdan avatar Feb 13 '24 17:02 weirdan

I found these snippets:

https://psalm.dev/r/235b00ed02
<?php
class User {
    public function __construct(
        public ?int $id = null,
    ) {
    }
}
class Visitor {
	public function __construct(
        public ?User $user = null,
    ) {
    }
}
class Employee {
	public function __construct(
        public ?User $user = null,
    ) {
    }
}

class Foo
{
	public function __construct(
        public Visitor $visitor,
        public Employee $employee,
    ) {
    }
    
    public function compare(): mixed
    {
        $visitorUser = $this->visitor->user;
        $employeeUser = $this->employee->user;
    	$compared = $visitorUser !== null && $employeeUser === $visitorUser;
        
        if ($compared) {
            return $visitorUser->id;
        }
        
        return 0;
    }
}
Psalm output (using commit cb0e6a1):

No issues!

psalm-github-bot[bot] avatar Feb 13 '24 17:02 psalm-github-bot[bot]