Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the serializer with api platform? #80

Open
thorau opened this issue Oct 30, 2019 · 1 comment
Open

How to use the serializer with api platform? #80

thorau opened this issue Oct 30, 2019 · 1 comment
Labels

Comments

@thorau
Copy link

thorau commented Oct 30, 2019

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

@DougHayward
Copy link

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);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants