-1

我已经在我的 Symfony 项目中集成了 FOSUserBundle 和 HWIOAUTHBundle。我在 FOSUserBundle 的简单登录表单旁边有一个 facebook 和一个 google 登录/注册。但是,Facebook 不一定会给我回电子邮件,因为 Facebook 帐户不需要它(即当用户通过电话在 Facebook 上注册时)。在这种情况下,当用户注册时,我将她/他的电子邮件地址设置为与 facebook/google ID 相同(因为我不能将电子邮件字段留空)。

当有人在我的网站上订购商品时,我需要向他发送一封电子邮件,其中包含她/他将用来验证自己的二维码,因此我需要一种从用户那里获取真实电子邮件地址的方法。

我认为当用户通过 Facebook 注册并尝试购买产品时,我会将她/他重定向到个人资料编辑页面,显示他/她应该提供正确的电子邮件地址的通知,然后她/他可以继续随着购买。

但是,我需要验证他们当前的电子邮件是否是处理购买的控制器中的真实(或至少看起来真实的)电子邮件地址。

如何在控制器中使用 Symfony 的验证器来检查用户的电子邮件是否$user = $this->get('security.token_storage')->getToken()->getUser(); $user->getEmail();真的看起来像电子邮件?

现在这就是我所拥有的:

if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
    throw $this->createAccessDeniedException('some message');
}

$user = $this->get('security.token_storage')->getToken()->getUser();

if ($user->isEnabled() == false) {
    throw $this->createAccessDeniedException('some message');
}

if (null == $user->getEmail() || $user->getFacebookId() == $user->getEmail() || $user->getGoogleId() === $user->getEmail()) {
    $session = new Session();
    $session->getFlashBag()->add('warning', 'Please provide a real email address, yata yata, etc.');
    return $this->redirectToRoute('fos_user_profile_edit');
}

提前致谢!

4

2 回答 2

3

在你的控制器中试试这个

    ...
use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...
public function addEmailAction($email, ValidatorInterface $validator)
{
    $emailConstraint = new Assert\Email();
    // all constraint "options" can be set this way
    $emailConstraint->message = 'Invalid email address';

    // use the validator to validate the value
    $errorList = $validator->validate(
        $email,
        $emailConstraint
    );

请参阅此处的文档https://symfony.com/doc/current/validation/raw_values.html

于 2017-11-09T10:09:10.327 回答
0

您应该能够只使用该validator服务并为其提供值和约束(或组合约束列表)

这个简单的例子应该可以工作(对于 sf 3.3+,取决于您的服务定义策略,您可能必须通过构造函数注入它)

public function testAction()
{
    $constraint = new \Symfony\Component\Validator\Constraints\Email();
    $stringToTest = 'lorem@ipsum.com';

    $errors = $this->get('validator')->validate($stringToTest, $constraint);

    if(count($errors) > 0) {
        //no valid email
    }
}
于 2017-11-09T10:06:30.053 回答