1

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

Bakhtiyor
  • 7,198
  • 15
  • 55
  • 77

2 Answers2

2

Symfony started documenting that getParameter can return UnitEnum in specific cases. This throws up Psalm analysis because in most cases, this is not what happens and you just get a scalar in return.

Unfortunately, this is not something that can be easily handled on the user side (you'd have to make a proxy method to make sure you exclude the UnitEnum case). So ideally, it should be handled by the Psalm's Symfony plugin (even if I'm not sure how). I suggest creating an issue on the tracker on github as I don't see it yet.

Source: I'm a Psalm maintainer

orklah
  • 81
  • 2
  • thank you for your answer. I duplicated the question here https://github.com/vimeo/psalm/issues/8380 as you suggested. – Bakhtiyor Aug 08 '22 at 06:25
0

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 : '';
Bakhtiyor
  • 7,198
  • 15
  • 55
  • 77