在没有 FormType 的情况下动态更改实体断言约束

Change Entity assert constrains dynamically without FormType

所以问题是这样的:

我正在尝试从 API 中保存一些数据,我需要使用 Symfony 验证来验证它们,例如:

private $id;

    /**
     * @var
     * @Assert\Length(max="255")
     * @CustomAssert\OrderExternalCode()
     * @CustomAssert\OrderShipNoExternalCode()
     */
    private $code;

    private $someId;

    /**
     * @var
     * @Assert\NotBlank()
     * @Assert\Length(max="255")
     */
    private $number;

这很好用,但现在我需要从控制器动态添加一些 Assert Constrains,这就是我卡住的地方!

有谁知道该怎么做或有任何可能有用的建议吗?

目前我做了一个额外的约束,它在数据库中进行额外的查询,我不想这样做,我也没有使用 FormType。

我认为使用 CallbackConstraint 应该对您有所帮助:

use My\Custom\MyConstraint;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

// This is not tested !
class MyEntity
{
    /**
     * @Assert\Callback()
     */
    public function validateSomeId(ExecutionContextInterface $context)
    {
        $constraint = new MyConstraint(['code' => $this->code]);
        $violations = $context->getValidator()->validate($this->number, $constraint);

        foreach ($violations as $violation) {
            $context->getViolations()->add($violation);
        }
    }
}

https://symfony.com/doc/current/reference/constraints/Callback.html

EDIT : I don't know what you're trying to validate so I just put some random params of your entity in there

您可以使用 groups 并使用(或省略)您正在谈论的额外组。

所以我想根据控制器中的条件动态验证请求数据。

我在实体中为此指定了一个额外的组,如下所示:

    /**
      * @var
      * @Assert\NotBlank(groups={"extra_check"})
      * @Assert\Length(max="255")
      */
     private $externalId;

然后在控制器中我只是做了条件来验证是否有额外的组。

$groups = $order->getExternalCode() != null ? ['Default'] : ['Default', 'extra_check'];
$this->validateRequest($request, null, $groups);

默认组是没有指定组的组,另一个是我在字段中指定的组