Symfony "fos_rest.request_body" converter: do not deserialize nested DTO classes

Viewed 804

I have a OrderDto class with a nested PointDto class (array of points):

class OrderDto
{
    /**
     * @var PointDto[]
     * @Assert\All({
     *     @Assert\Type("App\Dto\PointDto")
     * })
     * @Assert\Valid()
     */
    private array $points;

    // getters, setters
}

The PointDto class also uses validator constraints:

class PointDto
{
    /**
     * @Assert\NotBlank()
     */
    private string $address;

    // getters, setters
}

My controller:

/**
  * @Rest\Post("/order/calc")
  * @ParamConverter("orderDto", converter="fos_rest.request_body")
  */
public function calcOrder(OrderDto $orderDto, ConstraintViolationListInterface $validationErrors)
{
    if (count($validationErrors) > 0)
        return $this->json($validationErrors, Response::HTTP_BAD_REQUEST);
    return ApiResponseUtil::okData(['sum' => 0]);
}

But when is send request with nested dto object, like this:

{
    "points": [
        {
            "address": "",
            "person": {
                "name": "",
                "phone": ""
            }
        }
    ]
}

The validator cannot determine the type, error:

{
  "error": "points[0]: This value should be of type App\\Dto\\PointDto.",
  "violations": [
    {
      "property": "points[0]",
      "message": "This value should be of type App\\Dto\\PointDto."
    }
  ]
}

Is there any way to deserialize nested object?

1 Answers

I faced with the similar problem.

I had to use @var annotation for a field, iterable as it's type and ArrayCollection as initialized value.

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

class OrderDto
{
    /**
     * @var PointDto[] - this annotation is super important
     *
     * @ODM\Field
     * @Assert\All({
     *     @Assert\Type("App\Dto\PointDto")
     * })
     * @Assert\Valid()
     */
    private iterable $points;

    public function __construct()
    {
        $this->points = new ArrayCollection();
    }

    public function setPoints(iterable $points) // Don't use Collection type here, it will lead to a type error
    {
        $this->points = $points;
    }
}
Related