Psalm: [False Positive] Issues when subtracting null from class-string|null type

Created on 26 Jul 2020  路  2Comments  路  Source: vimeo/psalm

Consider a code example like the following (A real-world example is laravel's container named aliases )

https://psalm.dev/r/a711ca9aa9

Remove lines 27-29 and behavior is as expected.

-if (!$instance) {
-           return null;
-       }
bug

Most helpful comment

the result of get_class($some_object) is always a class-string, so that check is invalid

All 2 comments

I found these snippets:


https://psalm.dev/r/a711ca9aa9

<?php

class Resolver
{
    /**
    * @psalm-var array<string, class-string>
    */
    private $cache = [];

    /**
    * @psalm-return class-string|null
    */
    public function cachedResolve(string $abstract)
    {
        if (array_key_exists($abstract, self::$cache)) {
            return self::$cache[$abstract];
        }

        $resolved = $this->resolve($abstract);

        if (!$resolved) {
            return null;
        }

        $instance = get_class($resolved);

        if (!$instance) {
            return null;
        }

        self::$cache[$abstract] = $instance;

        return $instance;
    }

    /**
    * @return object|null
    */
    public function resolve(string $abstract) {
        return strlen($abstract) > 10 ? new stdClass() : null;
    }
}
Psalm output (using commit 3f06d4f):

ERROR: PropertyTypeCoercion - 31:9 - Resolver::$cache expects 'array<string, class-string>',  parent type 'non-empty-array<string, non-empty-string>' provided

INFO: LessSpecificReturnStatement - 33:16 - The type 'non-empty-string' is more general than the declared return type 'class-string|null' for Resolver::cachedResolve

INFO: MoreSpecificReturnType - 11:21 - The declared return type 'class-string|null' for Resolver::cachedResolve is more specific than the inferred return type 'non-empty-string|null'

the result of get_class($some_object) is always a class-string, so that check is invalid

Was this page helpful?
0 / 5 - 0 ratings