-1

我正在使用 Symfony 4.4,

出于安全原因,在提交嵌入 Product 实体的 OrderProduct 实体时,我必须控制取自 Product 的 OrderProduct 的一些值。

所以,这是一个 Symfony API,我收到一个 JSON 格式的 orderProduct:

{
   "product" : { "id" : 82 },
   "price" : 9.7,
   "quantity": 3,
   //...
}

我必须从数据库中获取产品,以测试价格是否正确。

订购产品实体:

4

2 回答 2

0

我认为自定义验证约束将是一个不错的选择。在您的自定义约束验证器注入ProductRepository中,找到您的实体并比较所需的值。也许OrderProduct为您的实体创建验证约束并验证一些字段。

public function validate($orderProduct, Constraint $constraint)
{
    // a few checks 

    $product = $this->productRepository->find($orderProduct->getProduct()->getId());

    if (!$this->isPriceValid($product->getPrice(), $orderProduct->getPrice()) { 
        $this->context->buildViolation($constraint->message)
            ->atPath('price')
            ->addViolation();
    }

    // ...
}

public function isPriceValid(float $oldPrice, float $newPrice): bool
{
    return $oldPrice === $newPrice;
}
于 2020-01-22T07:32:33.173 回答
0
  1. 创建您的 ProductPriceConstraint 和 ProductPriceConstraintValidator,确保您使用验证器作为服务
  2. 注入 EntityManager 服务
  3. 使用值中的 id 查询产品
  4. 比较值

有关如何创建自定义约束验证器的详细信息: https ://symfony.com/doc/current/validation/custom_constraint.html

注意:您的验证器必须是类约束验证器,以便您可以访问每个值,而不仅仅是价格或产品属性。 https://symfony.com/doc/current/validation/custom_constraint.html#class-constraint-validator

于 2020-01-22T07:29:36.770 回答