ApiPlatform\Core\EventListener\SerializeListener::onKernelView PHP Метод

onKernelView() публичный Метод

Serializes the data to the requested format.
public onKernelView ( GetResponseForControllerResultEvent $event )
$event Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $controllerResult = $event->getControllerResult();
        $request = $event->getRequest();
        if ($controllerResult instanceof Response) {
            return;
        }
        try {
            $attributes = RequestAttributesExtractor::extractAttributes($request);
        } catch (RuntimeException $e) {
            $this->serializeRawData($event, $request, $controllerResult);
            return;
        }
        $context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
        $request->attributes->set('_api_respond', true);
        $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
    }

Usage Example

Пример #1
0
 public function testEncode()
 {
     $serializerProphecy = $this->prophesize(SerializerInterface::class);
     $serializerProphecy->willImplement(EncoderInterface::class);
     $serializerProphecy->encode(Argument::any(), 'xml')->willReturn('bar')->shouldBeCalled();
     $serializerProphecy->serialize()->shouldNotBeCalled();
     $request = new Request([], [], ['_api_respond' => true]);
     $request->setRequestFormat('xml');
     $eventProphecy = $this->prophesize(GetResponseForControllerResultEvent::class);
     $eventProphecy->getControllerResult()->willReturn([])->shouldBeCalled();
     $eventProphecy->getRequest()->willReturn($request)->shouldBeCalled();
     $eventProphecy->setControllerResult('bar')->shouldBeCalled();
     $serializerContextBuilderProphecy = $this->prophesize(SerializerContextBuilderInterface::class);
     $listener = new SerializeListener($serializerProphecy->reveal(), $serializerContextBuilderProphecy->reveal());
     $listener->onKernelView($eventProphecy->reveal());
 }