在实体之外使用UniqueEntity而不使用表单

时间:2017-05-26 10:51:43

标签: symfony validation symfony-validator

我需要验证用户传递的电子邮件:

private function validate($value): bool
{
    $violations = $this->validator->validate($value, [
        new Assert\NotBlank(),
        new Assert\Email(),
        new UniqueEntity([
            'entityClass' => User::class,
            'fields' => 'email',
        ])
    ]);

    return count($violations) === 0;
}

UniqueEntity约束会引发异常:

  

警告:get_class()期望参数1为对象,字符串为

似乎ValidatorInterface::validate()方法的第一个参数等待具有getEmail()方法的Entity对象,但它看起来很难看。

是否有任何优雅的方法来验证仅将标量值传递给ValidatorInterface::validate()方法的字段的唯一性?

2 个答案:

答案 0 :(得分:5)

似乎没有内置的Symfony解决方案来做我想要的,所以我创建了自定义约束{/ 3}}。

UPD:当您发送表单以编辑实体时,此解决方案会引发验证错误。要避免此行为,您需要手动改进此约束。

约束:

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class UniqueValueInEntity extends Constraint
{
    public $message = 'This value is already used.';
    public $entityClass;
    public $field;

    public function getRequiredOptions()
    {
        return ['entityClass', 'field'];
    }

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

    public function validatedBy()
    {
        return get_class($this).'Validator';
    }
} 

验证

namespace AppBundle\Validator\Constraints;

use Doctrine\ORM\EntityManager;
use InvalidArgumentException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueValueInEntityValidator extends ConstraintValidator
{
    /**
     * @var EntityManager
     */
    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function validate($value, Constraint $constraint)
    {
        $entityRepository = $this->em->getRepository($constraint->entityClass);

        if (!is_scalar($constraint->field)) {
            throw new InvalidArgumentException('"field" parameter should be any scalar type');
        }

        $searchResults = $entityRepository->findBy([
            $constraint->field => $value
        ]);

        if (count($searchResults) > 0) {
            $this->context->buildViolation($constraint->message)
                ->addViolation();
        }
    }
}

服务:

services:
    app.validator.unique_value_in_entity:
        class: AppBundle\Validator\Constraints\UniqueValueInEntityValidator
        arguments: ['@doctrine.orm.entity_manager']
        tags:
            - { name: validator.constraint_validator }

用法示例:

private function validate($value): bool
{
    $violations = $this->validator->validate($value, [
        new Assert\NotBlank(),
        new Assert\Email(),
        new UniqueValueInEntity([
            'entityClass' => User::class,
            'field' => 'email',
        ])
    ]);

    return count($violations) === 0;
}

答案 1 :(得分:-1)

对于这个porpose,我会在用户类注释中使用@UniqueEntity(fields = {“email”})。有点像这样:

/**
 * @ORM\Entity()
 * @ORM\Table(name="user")
 * @UniqueEntity(fields={"email"})
 */