doctrine-json-odm
doctrine-json-odm copied to clipboard
How to use the serializer with api platform?
I have an Enity with property "offers": @ORM\Column(type="json_document", options={"jsonb": true}) Offers is a POPO with an id property that is of type rmsey uuid.
When API-Platform tries to persist the entity, is seems that the uuid cannot be serialized. What would be the right definition in services.yaml to make the serialization work?
I tried something like this, but it is not working:
dunglas_doctrine_json_odm.serializer: class: 'Dunglas\DoctrineJsonOdm\Serializer' arguments: - ['@api_platform.serializer.normalizer.item', '@dunglas_doctrine_json_odm.normalizer.array', '@dunglas_doctrine_json_odm.normalizer.object'] - ['@serializer.encoder.json'] public: true autowire: false
I know this is an old question, but just in case anyone comes looking for the same thing my way of making this work with ApiPlatform was by using a prePersist event listener. My actual code looks like this:
class DocumentListener
{
private SerializerInterface $serializer;
private ValidatorInterface $validator;
/**
* DocumentListener constructor.
* @param SerializerInterface $serializer
* @param ValidatorInterface $validator
*/
public function __construct(SerializerInterface $serializer, ValidatorInterface $validator)
{
$this->serializer = $serializer;
$this->validator = $validator;
}
/**
* @param Document $document
* @throws \Exception
*/
public function prePersist(Document $document): void
{
if (!$document->getType()) {
throw new Exception('A document type must be provided.');
}
if (!class_exists($document->getType()->getClass())) {
throw new \Exception("Document type '{$document->getType()->getName()}' not supported.");
}
$documentContent = $this->serializer->deserialize(json_encode($document->getContent()), $document->getType()->getClass(), 'json');
$errors = $this->validator->validate($documentContent);
if ($errors->count() > 0) {
throw new ValidationException($errors);
}
$document->setContent($documentContent);
}
}