gpt4 book ai didi

php - 如何使异常消息在 Symfony 4 用户检查器中可翻译?

转载 作者:行者123 更新时间:2023-12-05 03:02:53 25 4
gpt4 key购买 nike

我正在检查用户是否可以让他们登录,如果没有,则以他们的语言环境向他们显示错误消息。这是一个 Symfony 4.2 应用程序。所以这是我的用户检查器(有效):

<?php
namespace App\Security;

use App\Entity\User as AppUser;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker implements UserCheckerInterface {
public function checkPreAuth(UserInterface $user)
{
if (!$user instanceof AppUser) {
return;
}
}

public function checkPostAuth(UserInterface $user)
{
/* Make the message translatable */
if (!$user->isEnabled()) {
throw new CustomUserMessageAuthenticationException(
'This account has not been activated.'
);
}
}
}

在 Symfony 4 中翻译字符串的常用方法需要更改签名:

public function checkPostAuth(UserInterface $user, TranslatorInterface $translator)

这将适用于我在 Controller 中定义的功能,但此用户检查器已注册为防火墙中使用的服务,因此我们收到错误:

FatalErrorException
Compile Error: Declaration of App\Security\UserChecker::checkPostAuth(Symfony\Component\Security\Core\User\UserInterface $user, App\Security\TranslatorInterface $translator) must be compatible with Symfony\Component\Security\Core\User\UserCheckerInterface::checkPostAuth(Symfony\Component\Security\Core\User\UserInterface $user)

我找不到任何其他适用于 Symfony 4 的方法的文档。

最佳答案

Symfony 这样做的方式是,仅在模板渲染期间显示消息时才翻译消息,例如在login form你有这个:

{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}

另一种方法可能是挂接到 Symfony 的事件系统,并在 EventListener 中转换异常,该 EventListener 通过监听 AuthenticationEvents::AUTHENTICATION_FAILURE 捕获 AuthenticationFailureEvent

关于php - 如何使异常消息在 Symfony 4 用户检查器中可翻译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com