1

我正在尝试通过静态回调验证我的实体。

我能够按照Symfony 指南使其工作,但我不清楚。

public static function validate($object, ExecutionContextInterface $context, $payload)
{
    // somehow you have an array of "fake names"
    $fakeNames = array(/* ... */);

    // check if the name is actually a fake name
    if (in_array($object->getFirstName(), $fakeNames)) {
        $context->buildViolation('This name sounds totally fake!')
            ->atPath('firstName')
            ->addViolation()
        ;
    }
}

当我填充我的$fakeNames数组时它工作正常但是如果我想让它“动态”呢?假设我想从参数或数据库或任何地方选择该数组。从构造函数不起作用并且它必须是静态的那一刻起,我应该如何将东西(例如容器或 entityManager)传递给这个类?

当然,我的方法可能完全错误,但我只是使用 symfony 示例以及在互联网上发现的一些其他类似问题,我试图适应我的情况。

4

2 回答 2

3

您可以创建一个约束和验证器并将其注册为服务,以便您可以注入 entityManager 或您需要的任何东西,您可以在此处阅读更多信息:

https://symfony.com/doc/2.8/validation/custom_constraint.html

或者如果您使用的是 symfony 3.3,它已经是一项服务,您可以在构造函数中输入提示: https ://symfony.com/doc/current/validation/custom_constraint.html

于 2017-09-13T18:20:20.193 回答
1

这是我最终能够找到的解决方案。它运行顺利,我希望它对其他人有用。

我已经设置了我的约束validation.yml

User\UserBundle\Entity\Group:
    constraints:
        - User\UserBundle\Validator\Constraints\Roles\RolesConstraint: ~

这是我的 RolesConstraint 类

namespace User\UserBundle\Validator\Constraints\Roles;

use Symfony\Component\Validator\Constraint;

class RolesConstraint extends Constraint
{
    /** @var string $message */
    public $message = 'The role "{{ role }}" is not recognised.';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}

这是我的 RolesConstraintValidator 类

<?php

namespace User\UserBundle\Validator\Constraints\Roles;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class RolesConstraintValidator extends ConstraintValidator
{
    /** @var ContainerInterface */
    private $containerInterface;

    /**
     * @param ContainerInterface $containerInterface
    */
    public function __construct(ContainerInterface $containerInterface)
    {
        $this->containerInterface = $containerInterface;
    }

    /**
     * @param \User\UserBundle\Entity\Group $object
     * @param Constraint $constraint
    */
    public function validate($object, Constraint $constraint)
    {
        if (!in_array($object->getRole(), $this->containerInterface->getParameter('roles'))) {
            $this->context
                ->buildViolation($constraint->message)
                ->setParameter('{{ role }}', $object->getRole())
                ->addViolation();
        }
    }
}

本质上,我设置了一个约束,每次新用户用户与角色一起注册时,该角色必须在参数中设置的角色中。如果不是,则构成违规。

于 2017-09-15T10:37:55.517 回答