【问题标题】:Psalm: Handle method that returns multiple types诗篇:返回多种类型的句柄方法
【发布时间】:2020-05-16 23:56:34
【问题描述】:

编辑这是 Psalm 的事,不是 PHP MD 的事。

我正在编写一个 Symfony 控制台命令。在其execute 方法中,我使用$input->getArgument('argument_name') 方法检索参数。我将这个值传递给一个服务,它期望这个值是字符串类型的。

整体代码:

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (is_string($input->getArgument('identifier'))) {
            $identifier = $input->getArgument('identifier');
        } else {
            return 2;
        }
        if ($input->getArgument('mode') === "vehicle") {
            $this->vehicleService->getVehicleInfo($identifier);
            return null;
        }
        if ($input->getArgument('mode') === "company") {
            $this->vehicleService->getCompanyVehiclesInfo($identifier);
            return null;
        }
        return 1;
    }

PHP MD Psalm 没有看到我已经确认 $identifier 是一个字符串,然后将其作为参数传递给 vehicleService 方法之一,并向我抛出 PossiblyInvalidArgument 错误,因为Argument 1 ... expects string, possibly different type array<array-key, string>|null|string provided

我如何确保 PHP MD 这是一个字符串?

【问题讨论】:

  • 您是否尝试过将$identifier 显式转换为字符串,将其作为(string)$identifier 传递,或者将其分配为$identifier = (string)$input->getArgument('identifier');
  • PHP MD 会说不可能将可能的数组变量转换为字符串:(

标签: php symfony-console psalm-php


【解决方案1】:

经过几次尝试,我想通了。我需要把所有东西都放在if (is_string(...)) 检查:

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $identifier = $input->getArgument('identifier');
        if (is_string($identifier)) {
            if ($input->getArgument('mode') === "vehicle") {
                $this->vehicleService->getVehicleInfo($identifier);
                return null;
            }
            if ($input->getArgument('mode') === "company") {
                $this->vehicleService->getCompanyVehiclesInfo($identifier);
                return null;
            }
        } else {
            return 2;
        }
        return 1;
    }

【讨论】:

    【解决方案2】:

    截至 3 月,Symfony Psalm Plugin 可以正确处理参数和选项。不再需要解决方法了:)

    【讨论】:

      猜你喜欢
      • 2021-04-11
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多