0

我最近开始在Symfony 3.4项目上使用PHPStan(版本 0.12.19),但我遇到了一个错误,看起来应该很容易解决,但我很难弄清楚。

目前在第 7 级运行。这是我运行时遇到的错误:

vendor/bin/phpstan analyse

------ --------------------------------------------------------------------------------------------------------------
  Line   src/AppBundle/Controller/MapController.php
 ------ --------------------------------------------------------------------------------------------------------------
  94     Parameter #1 $user of static method AppBundle\Entity\MapMarker::createMapMarker() expects
         Symfony\Component\Security\Core\User\UserInterface, object given.

这是MapController.php的重要部分:

    $user = $this->getUser();

     $mapMarker = MapMarker::createMapMarker(
            $user,
            $latitude,
            $longitude
        );

getUser 方法是 Symfony 方法,所以我无法更改这部分:https ://github.com/symfony/symfony/blob/3.4/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php#L444 :

/**
     * Get a user from the Security Token Storage.
     *
     * @return UserInterface|object|null
     *
     * @throws \LogicException If SecurityBundle is not available
     *
     * @see TokenInterface::getUser()
     *
     * @final since version 3.4
     */
    protected function getUser()
    {
        if (!$this->container->has('security.token_storage')) {
            throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
        }

        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
            return null;
        }

        if (!\is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return null;
        }

        return $user;
    }

MapMarker.php的重要部分:

/**
     * @param UserInterface $user
     * @param double $latitude
     * @param double $longitude
     */
    private function __construct(UserInterface $user, $latitude, $longitude) {
        $this->createdBy = $user;
        $this->latitude = $latitude;
        $this->longitude = $longitude;
    }

    /**
     * @param UserInterface $user
     * @param double $latitude
     * @param double $longitude
     * @return MapMarker
     */
    public static function createMapMarker(UserInterface $user, $latitude, $longitude): MapMarker
    {
        return new self($user, $latitude, $longitude);
    }

当我转储它时,$user instanceof UserInterface它返回 true - 据我所知,它正在传递一个 UserInterface 对象,而不仅仅是 PHPStan 所指示的“对象”。

最后,这是我的 phpstan.neon 配置文件:

parameters:
    level: 7
    paths:
        - src
        - tests
    checkGenericClassInNonGenericObjectType: false
    checkMissingIterableValueType: false

我错过了什么?

4

1 回答 1

2

我想你至少知道了问题所在:方法的返回类型getUser@return UserInterface|object|nullwhilecreateMapMarker需要一个UserInterface.

在调用之前,createMapMarker您应该检查返回值getUser是否实际上是一个实例,并且可能是变量声明将修复UserInterface的简单/** @var UserInterface $user */权利。$user

于 2020-04-28T23:55:34.317 回答