symfony - 获取用户而不是用户界面
问题描述
当我这样做时如何获取用户类而不是用户界面:
$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 给定。
解决方案
当 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