【问题标题】:Get user instead of Userinterface获取用户而不是用户界面
【发布时间】:2020-06-18 08:48:32
【问题描述】:

当我这样做时如何获取用户类而不是用户界面:

$this->security->getUser() (安全是 Symfony\Component\Security\Core\Security;)

通过示例(它只是一个示例:),我有这个自定义功能:

public function getUser(User $user){
}

当我这样做时:

public function __construct(
        Security $security,
    ) {
        $this->security = $security;
    }

getUser($this->security->getUser());

我有一个警告:

getUser 期望 App\Entity\User, Symfony\Component\Security\Core\User\UserInterface|null。

【问题讨论】:

  • 你的用户没有实现UserInterface吗?
  • 是的:class User implements UserInterface
  • 你从哪里得到这个警告?这是来自 psalm 或 phpstan 等静态分析工具吗?
  • 是的,phpstan(还有 phpstorm)
  • 如果这是你的编辑器告诉你的,而不是 Symfony 调试器告诉你的,那么忽略它。 PhpStorm 无法正确解决。

标签: symfony


【解决方案1】:

如果$this->security->getUser() 调用 Symfony 的核心安全类来返回一个用户,它将总是返回一个实现 UserInterface 的对象——这就是该类的返回类型定义的(或者通过正确的返回类型,或通过 PHPDoc)。这不能由您自己的应用程序更改。

为了克服你的问题,你自己的方法getUser 应该使用这个接口作为它的参数的参数类型。在该方法中,您可以检查更具体的类(例如:if($argument instanceof User)),但不能检查方法的函数签名。

【讨论】:

  • 我试过了,但是现在我不能写$user->getId(),因为getId不在接口中
  • 好吧,那么您应该检查$user 是否是您的User 的一个实例。此类检查之后的任何代码(抛出异常或中断该方法)都将属于该类型,您的 IDE 应该检测到这一点
【解决方案2】:

当 phpstan 或 psalm 等代码分析工具警告您类型不匹配时,有多种方法可以处理它。

您很可能想更改方法签名,然后处理消息抱怨的情况,例如像这样:

public function getUser(UserInterface $user = null)
{
    if (null === $user || ! $user instanceof User) {
        // do something about the wrong types, that you might get from getSecurity()->getUser(), e.g. return or throw an exception
        throw Exception(sprintf('Expected App\\Entity\\User, got %s', $user === null ? 'null' : get_class($user)));
    }

    ... your logic
}

现在您的方法同时接受可能进入的接口和 null。您还可以在调用 getUser 方法之前进行错误处理并保持原样,因此不仅仅是getUser($this->security->getUser());

$temporaryUser = $this->security->getUser();

if (!$temporaryUser instanceof User) {
    throw Exception(sprintf('Expected App\\Entity\\User, got %s', $user === null ? 'null' : get_class($user))); 
}

getUser($temporaryUser);

如果您确定代码不会遇到问题,您还可以通过在项目根目录中创建phpstan.neon 来忽略某些错误消息。见:https://github.com/phpstan/phpstan#ignore-error-messages-with-regular-expressions

【讨论】:

  • 好的,但是在我的 User 类中我有一个 getId 函数(UserInterface 中不存在)然后我不能这样做:``` $user->getId() ``
  • 我会忽略这个 phpstan 消息(我知道的简单解决方案...:D)
  • 是的,你可以,因为经过特殊情况的处理你肯定知道是App\Entity\User,所以你可以放心地使用这些方法。
猜你喜欢
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多