ApiPlatform\Core\EventListener\DeserializeListener::onKernelRequest PHP Method

onKernelRequest() public method

Deserializes the data sent in the requested format.
public onKernelRequest ( GetResponseEvent $event )
$event Symfony\Component\HttpKernel\Event\GetResponseEvent
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->isMethodSafe(false) || $request->isMethod(Request::METHOD_DELETE)) {
            return;
        }
        try {
            $attributes = RequestAttributesExtractor::extractAttributes($request);
        } catch (RuntimeException $e) {
            return;
        }
        $format = $this->getFormat($request);
        $context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
        $data = $request->attributes->get('data');
        if (null !== $data) {
            $context['object_to_populate'] = $data;
        }
        $request->attributes->set('data', $this->serializer->deserialize($request->getContent(), $attributes['resource_class'], $format, $context));
    }

Usage Example

 /**
  * @expectedException \Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException
  * @expectedExceptionMessage The "Content-Type" header must exist.
  */
 public function testNoContentType()
 {
     $eventProphecy = $this->prophesize(GetResponseEvent::class);
     $request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'post'], [], [], [], '{}');
     $request->setMethod(Request::METHOD_POST);
     $request->setRequestFormat('unknown');
     $eventProphecy->getRequest()->willReturn($request)->shouldBeCalled();
     $serializerProphecy = $this->prophesize(SerializerInterface::class);
     $serializerProphecy->deserialize()->shouldNotBeCalled();
     $serializerContextBuilderProphecy = $this->prophesize(SerializerContextBuilderInterface::class);
     $serializerContextBuilderProphecy->createFromRequest()->shouldNotBeCalled();
     $listener = new DeserializeListener($serializerProphecy->reveal(), $serializerContextBuilderProphecy->reveal(), ['jsonld' => ['application/ld+json'], 'xml' => ['text/xml']]);
     $listener->onKernelRequest($eventProphecy->reveal());
 }