Api Platform - DTO validation in DataTransformer

2.7k Views Asked by At

I have a DTO input that needs to be transformed into Entity object. DTO needs to be validated first and may be in invalid state.

There is section in manual that talks about validation of DTO https://api-platform.com/docs/core/dto/#validating-data-transfer-objects but it does not say what to to with validation result, whether it should be passed somewhere or thrown directly.

final class MyDataDransformer implements DataTransformerInterface
{
    private ValidatorInterface $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    public function transform($dto, string $to, array $context = []): MyEntityObject
    {
        /** @var \Symfony\Component\Validator\ConstraintViolationList */
        $validationResult = $this->validator->validate($dto);

        if ($validationResult->count() > 0) {
            // how to throw exception with validation result here?
            // is this right place to throw this exception?
        }

        // if no validation errors, construct entity object and return as normal
    }

    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        return true; // for simplicity
    }
}

Api Platform has mechanism for handling validation exceptions for entity object, it will format ConstraintViolationList object and output all errors as error type response. I need same for DTO.

1

There are 1 best solutions below

0
On BEST ANSWER

There's a service in api platform that throws an exception if there's violations.

It is not the ValidatorInterface from symfony , but the api platform one

use ApiPlatform\Core\Validator\ValidatorInterface;