-1

I'm working with Symfony 4.4,

For security reason, when submitting OrderProduct entity that embedd Product entity, I have to control some values of OrderProduct taken from Product.

So, it's an Symfony API, I receive an orderProduct in a JSON format:

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

I have to get the product from the database, to test if the price is correct.

OrderProduct Entity:

Community
  • 1
  • 1
Med Karim Garali
  • 923
  • 1
  • 14
  • 37

2 Answers2

0
  1. Create your ProductPriceConstraint and ProductPriceConstraintValidator, make sure you use validator as a service
  2. Inject the EntityManager service
  3. Query for the product using the id from the value
  4. Compare the values

Detailed info on how to create custom constraint validators: https://symfony.com/doc/current/validation/custom_constraint.html

Note: Your validator has to be class constraint validator so that you can access every value, not just the price or product property. https://symfony.com/doc/current/validation/custom_constraint.html#class-constraint-validator

domagoj
  • 906
  • 1
  • 8
  • 20
0

I think custom validation constraint will be good option. In your custom constraint validator inject ProductRepository, find your entity and compare needed values. Maybe create OrderProduct validation constraint for your entity and validate a few fields.

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;
}
Ihor Kostrov
  • 2,361
  • 14
  • 23