phpsymfonyenumspsalm-php

UnitEnum cannot be cast to string


I have a variable declared in config/services.yaml

parameters:
    login_url: '%env(string:APP_FRONTEND_DOMAIN)%'

I am accessing it in my controller like this:

$loginUrl = (string) ($this->getParameter('login_url') ?? "");

Everything works fine, but psalm is giving following error:

ERROR: PossiblyInvalidCast - src/Controller/MyController.php:57:31 - UnitEnum cannot be cast to string (see https://psalm.dev/190)
$loginUrl = (string) ($this->getParameter('login_url') ?? "");

Any suggestions, how to fix it, please?

Duplicated the question in the official github issue of the pslam-plugin-symfony: https://github.com/psalm/psalm-plugin-symfony/issues/272


Solution

  • As I mentioned, I duplicated the issue in github pages of the psalm and psalm-plugin and actually received the answer from one of them which solves my problem.

    The answer is copied from: https://github.com/psalm/psalm-plugin-symfony/issues/272#issuecomment-1211802478

    Here is the related part on Symfony side:

    /**
     * Gets a service container parameter.
     *
     * @return array|bool|string|int|float|\UnitEnum|null
     *
     * @throws ParameterNotFoundException if the parameter is not defined
     */
    public function get(string $name);
    

    According to the code, it means $login_url can be array, bool, etc. including \UnitEnum which cannot be casted to string. Thus the error is correct actually.

    On the other hand, I know that you specified the type on parameters with environment variable which should be string. To be able to infer the type of parameter, the plugin needs to analyze compiled container XML (assuming that you already configured it) which is currently missing.

    For now, you can rewrite it to tackle the error:

    $loginUrl = $this->getParameter('login_url');
    $loginUrl = is_string($loginUrl) ? $loginUrl : '';