Example #1
0
 /**
  * {@inheritdoc}
  */
 public function handle(RequestConfiguration $requestConfiguration, View $view)
 {
     if (!$requestConfiguration->isHtmlRequest()) {
         $this->restViewHandler->setExclusionStrategyGroups($requestConfiguration->getSerializationGroups());
         if ($version = $requestConfiguration->getSerializationVersion()) {
             $this->restViewHandler->setExclusionStrategyVersion($version);
         }
         $view->getSerializationContext()->enableMaxDepthChecks();
     }
     return $this->restViewHandler->handle($view);
 }
 /**
  * Get single note,
  *
  * @ApiDoc(
  *   resource = true,
  *   description = "Gets a note for a given id",
  *   output = "Acme\Demo\DomainBundle\Entity\Note",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     404 = "Returned when the note is not found"
  *   }
  * )
  *
  * @Annotations\View(templateVar="note")
  *
  * @param Request $request the request object
  * @param int     $id      the note id
  *
  * @return array
  *
  * @throws NotFoundHttpException when note not exist
  */
 public function getNoteAction(Request $request, $id)
 {
     $note = $this->NoteHandler()->get($id);
     if (null === $note) {
         throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.', $id));
     }
     $view = new View($note);
     $group = $this->container->get('security.context')->isGranted('ROLE_API') ? 'restapi' : 'standard';
     $view->getSerializationContext()->setGroups(array('Default', $group));
     return $view;
 }
 /**
  * Get a single image.
  *
  * @ApiDoc(
  *   output = "Acme\DemoBundle\Model\Image",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     404 = "Returned when the note is not found"
  *   }
  * )
  *
  * @Annotations\View(templateVar="image")
  *
  * @param Request $request the request object
  * @param int     $id      the note id
  *
  * @return array
  *
  * @throws NotFoundHttpException when note not exist
  */
 public function getImageAction(Request $request, $id)
 {
     $image = $this->getImageManager()->get($id);
     if (false === $image) {
         throw $this->createNotFoundException("Image does not exist.");
     }
     $view = new View($image);
     $group = $this->container->get('security.context')->isGranted('ROLE_API') ? 'restapi' : 'standard';
     $view->getSerializationContext()->setGroups(array('Default', $group));
     return $view;
 }
 /**
  * Renders the parameters and template and initializes a new response object with the
  * rendered content.
  *
  * @param GetResponseForControllerResultEvent $event A GetResponseForControllerResultEvent instance
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $request = $event->getRequest();
     $configuration = $request->attributes->get('_view');
     $view = $event->getControllerResult();
     if (!$view instanceof View) {
         if (!$configuration && !$this->container->getParameter('fos_rest.view_response_listener.force_view')) {
             return parent::onKernelView($event);
         }
         $view = new View($view);
     }
     if ($configuration) {
         if ($configuration->getTemplateVar()) {
             $view->setTemplateVar($configuration->getTemplateVar());
         }
         if (null === $view->getStatusCode() && $configuration->getStatusCode()) {
             $view->setStatusCode($configuration->getStatusCode());
         }
         if ($configuration->getSerializerGroups()) {
             $context = $view->getSerializationContext() ?: new SerializationContext();
             $context->setGroups($configuration->getSerializerGroups());
             $view->setSerializationContext($context);
         }
     }
     if (null === $view->getFormat()) {
         $view->setFormat($request->getRequestFormat());
     }
     $vars = $request->attributes->get('_template_vars');
     if (!$vars) {
         $vars = $request->attributes->get('_template_default_vars');
     }
     $viewHandler = $this->container->get('fos_rest.view_handler');
     if ($viewHandler->isFormatTemplating($view->getFormat())) {
         if (!empty($vars)) {
             $parameters = (array) $viewHandler->prepareTemplateParameters($view);
             foreach ($vars as $var) {
                 if (!array_key_exists($var, $parameters)) {
                     $parameters[$var] = $request->attributes->get($var);
                 }
             }
             $view->setData($parameters);
         }
         $template = $request->attributes->get('_template');
         if ($template) {
             if ($template instanceof TemplateReference) {
                 $template->set('format', null);
             }
             $view->setTemplate($template);
         }
     }
     $response = $viewHandler->handle($view, $request);
     $event->setResponse($response);
 }
Example #5
0
 /**
  * Get a single server.
  *
  * @ApiDoc(
  *   output = "Aegir\Provision\Model\Server",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     404 = "Returned when the server is not found"
  *   }
  * )
  *
  * @Annotations\View(templateVar="server")
  *
  * @param Request $request the request object
  * @param int     $id      the server id
  *
  * @return array
  *
  * @throws NotFoundHttpException when server not exist
  */
 public function getServerAction(Request $request, $id)
 {
     $session = $request->getSession();
     $servers = $session->get(self::SESSION_CONTEXT_SERVER);
     if (!isset($servers[$id])) {
         throw $this->createNotFoundException("Server does not exist.");
     }
     $view = new View($servers[$id]);
     $group = $this->container->get('security.context')->isGranted('ROLE_API') ? 'restapi' : 'standard';
     $view->getSerializationContext()->setGroups(array('Default', $group));
     return $view;
 }
Example #6
0
 /**
  * Get a single terrain.
  *
  * @ApiDoc(
  *   output = "Flyaround\DefaultBundle\Entity\Terrain",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     404 = "Returned when the note is not found"
  *   }
  * )
  *
  * @Annotations\View(templateVar="terrain")
  *
  * @param Request $request the request object
  * @param int     $id      the terrain id
  *
  * @return array
  *
  * @throws NotFoundHttpException when note not exist
  */
 public function getTerrainAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getManager();
     $entity = $em->getRepository('FlyaroundDefaultBundle:Terrain')->find($id);
     if (!$entity) {
         throw $this->createNotFoundException('Unable to find Terrain entity.');
     }
     $view = new View($entity);
     $group = $this->container->get('security.context')->isGranted('ROLE_API') ? 'restapi' : 'standard';
     $view->getSerializationContext()->setGroups(array('Default', $group));
     return $view;
 }
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     $data = $view->getData();
     $context = $view->getSerializationContext();
     $container = $handler->getContainer();
     $format = $view->getFormat();
     $file = $container->get('claroline.library.view.serializer.serializer')->serialize($data, $format);
     $response = new StreamedResponse();
     $response->setCallBack(function () use($file) {
         readfile($file);
     });
     $response->headers->set('Content-Transfer-Encoding', 'octet-stream');
     $response->headers->set('Content-Type', 'application/force-download');
     $response->headers->set('Content-Disposition', 'attachment; filename=file.' . $format);
     switch ($format) {
         case 'csv':
             $response->headers->set('Content-Type', 'text/csv');
             break;
         case 'xls':
             $response->headers->set('Content-Type', 'application/vnd.ms-excel');
             break;
     }
     return $response;
 }
Example #8
0
 /**
  * @dataProvider exceptionWrapperSerializeResponseContentProvider
  *
  * @param string $format
  */
 public function testCreateResponseWithFormErrorsAndSerializationGroups($format)
 {
     $form = Forms::createFormFactory()->createBuilder()->add('name', 'text')->add('description', 'text')->getForm();
     $form->get('name')->addError(new FormError('Invalid name'));
     $exceptionWrapper = new ExceptionWrapper(['status_code' => 400, 'message' => 'Validation Failed', 'errors' => $form]);
     $view = new View($exceptionWrapper);
     $view->getSerializationContext()->addGroups(['Custom']);
     $wrapperHandler = new ExceptionWrapperSerializeHandler();
     $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface', ['trans', 'transChoice', 'setLocale', 'getLocale']);
     $translatorMock->expects($this->any())->method('trans')->will($this->returnArgument(0));
     $formErrorHandler = new FormErrorHandler($translatorMock);
     $serializer = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $handlerRegistry) use($wrapperHandler, $formErrorHandler) {
         $handlerRegistry->registerSubscribingHandler($wrapperHandler);
         $handlerRegistry->registerSubscribingHandler($formErrorHandler);
     })->build();
     $adapter = $this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface');
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\Container', ['get']);
     $container->expects($this->any())->method('get')->with($this->logicalOr($this->equalTo('fos_rest.serializer'), $this->equalTo('fos_rest.context.adapter.chain_context_adapter')))->will($this->returnCallback(function ($method) use($serializer, $adapter) {
         switch ($method) {
             case 'fos_rest.serializer':
                 return $serializer;
             case 'fos_rest.context.adapter.chain_context_adapter':
                 return $adapter;
         }
     }));
     $viewHandler = new ViewHandler([]);
     $viewHandler->setSerializationContextAdapter($this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface'));
     $viewHandler->setContainer($container);
     $response = $viewHandler->createResponse($view, new Request(), $format);
     $serializer2 = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $handlerRegistry) use($wrapperHandler, $formErrorHandler) {
         $handlerRegistry->registerSubscribingHandler($formErrorHandler);
     })->build();
     $container2 = $this->getMock('Symfony\\Component\\DependencyInjection\\Container', ['get']);
     $container2->expects($this->any())->method('get')->with($this->logicalOr($this->equalTo('fos_rest.serializer'), $this->equalTo('fos_rest.context.adapter.chain_context_adapter')))->will($this->returnCallback(function ($method) use($serializer2, $adapter) {
         switch ($method) {
             case 'fos_rest.serializer':
                 return $serializer2;
             case 'fos_rest.context.adapter.chain_context_adapter':
                 return $adapter;
         }
     }));
     $viewHandler = new ViewHandler([]);
     $viewHandler->setSerializationContextAdapter($this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface'));
     $viewHandler->setContainer($container2);
     $view2 = new View($exceptionWrapper);
     $response2 = $viewHandler->createResponse($view2, new Request(), $format);
     $this->assertEquals($response->getContent(), $response2->getContent());
 }
 /**
  * Renders the parameters and template and initializes a new response object with the
  * rendered content.
  *
  * @param GetResponseForControllerResultEvent $event
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $request = $event->getRequest();
     /** @var \FOS\RestBundle\Controller\Annotations\View $configuration */
     $configuration = $request->attributes->get('_view');
     $view = $event->getControllerResult();
     $customViewDefined = true;
     if (!$view instanceof View) {
         if (!$configuration && !$this->container->getParameter('fos_rest.view_response_listener.force_view')) {
             return parent::onKernelView($event);
         }
         $view = new View($view);
         $customViewDefined = false;
     }
     if ($configuration) {
         if ($configuration->getTemplateVar()) {
             $view->setTemplateVar($configuration->getTemplateVar());
         }
         if ($configuration->getStatusCode() && (null === $view->getStatusCode() || Codes::HTTP_OK === $view->getStatusCode())) {
             $view->setStatusCode($configuration->getStatusCode());
         }
         if ($configuration->getSerializerGroups() && !$customViewDefined) {
             $context = $view->getSerializationContext() ?: new SerializationContext();
             $context->setGroups($configuration->getSerializerGroups());
             $view->setSerializationContext($context);
         }
         if ($configuration->getSerializerEnableMaxDepthChecks()) {
             $context = $view->getSerializationContext() ?: new SerializationContext();
             $context->enableMaxDepthChecks();
             $view->setSerializationContext($context);
         }
         $populateDefaultVars = $configuration->isPopulateDefaultVars();
     } else {
         $populateDefaultVars = true;
     }
     if (null === $view->getFormat()) {
         $view->setFormat($request->getRequestFormat());
     }
     $vars = $request->attributes->get('_template_vars');
     if (!$vars && $populateDefaultVars) {
         $vars = $request->attributes->get('_template_default_vars');
     }
     $viewHandler = $this->container->get('fos_rest.view_handler');
     if ($viewHandler->isFormatTemplating($view->getFormat())) {
         if (!empty($vars)) {
             $parameters = (array) $viewHandler->prepareTemplateParameters($view);
             foreach ($vars as $var) {
                 if (!array_key_exists($var, $parameters)) {
                     $parameters[$var] = $request->attributes->get($var);
                 }
             }
             $view->setData($parameters);
         }
         $template = $request->attributes->get('_template');
         if ($template) {
             if ($template instanceof TemplateReference) {
                 $template->set('format', null);
             }
             $view->setTemplate($template);
         }
     }
     $response = $viewHandler->handle($view, $request);
     $event->setResponse($response);
 }
Example #10
0
 protected function handleView(View $view)
 {
     $handler = $this->get('fos_rest.view_handler');
     $handler->setExclusionStrategyGroups($this->config->getSerializationGroups());
     if ($version = $this->config->getSerializationVersion()) {
         $handler->setExclusionStrategyVersion($version);
     }
     $view->getSerializationContext()->enableMaxDepthChecks();
     return $handler->handle($view);
 }
Example #11
0
 /**
  * @dataProvider exceptionWrapperSerializeResponseContentProvider
  * @param string $format
  */
 public function testCreateResponseWithFormErrorsAndSerializationGroups($format)
 {
     $form = Forms::createFormFactory()->createBuilder()->add('name', 'text')->add('description', 'text')->getForm();
     $form->get('name')->addError(new FormError('Invalid name'));
     $exceptionWrapper = new ExceptionWrapper(array('status_code' => 400, 'message' => 'Validation Failed', 'errors' => $form));
     $view = new View($exceptionWrapper);
     $view->getSerializationContext()->setGroups(array('Custom'));
     $wrapperHandler = new ExceptionWrapperSerializeHandler();
     $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface', array('trans', 'transChoice', 'setLocale', 'getLocale'));
     $translatorMock->expects($this->any())->method('trans')->will($this->returnArgument(0));
     $formErrorHandler = new FormErrorHandler($translatorMock);
     $serializer = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $handlerRegistry) use($wrapperHandler, $formErrorHandler) {
         $handlerRegistry->registerSubscribingHandler($wrapperHandler);
         $handlerRegistry->registerSubscribingHandler($formErrorHandler);
     })->build();
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\Container', array('get'));
     $container->expects($this->once())->method('get')->with('fos_rest.serializer')->will($this->returnValue($serializer));
     $viewHandler = new ViewHandler(array());
     $viewHandler->setContainer($container);
     $response = $viewHandler->createResponse($view, new Request(), $format);
     $serializer2 = SerializerBuilder::create()->configureHandlers(function (HandlerRegistry $handlerRegistry) use($wrapperHandler, $formErrorHandler) {
         $handlerRegistry->registerSubscribingHandler($formErrorHandler);
     })->build();
     $container2 = $this->getMock('Symfony\\Component\\DependencyInjection\\Container', array('get'));
     $container2->expects($this->once())->method('get')->with('fos_rest.serializer')->will($this->returnValue($serializer2));
     $viewHandler = new ViewHandler(array());
     $viewHandler->setContainer($container2);
     $view2 = new View($exceptionWrapper);
     $response2 = $viewHandler->createResponse($view2, new Request(), $format);
     $this->assertEquals($response->getContent(), $response2->getContent());
 }
 /**
  * @dataProvider exceptionWrapperSerializeResponseContentProvider
  *
  * @param string $format
  */
 public function testCreateResponseWithFormErrorsAndSerializationGroups($format)
 {
     // BC hack for Symfony 2.7 where FormType's didn't yet get configured via the FQN
     $formType = method_exists('Symfony\\Component\\Form\\AbstractType', 'getBlockPrefix') ? 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType' : 'text';
     $form = Forms::createFormFactory()->createBuilder()->add('name', $formType)->add('description', $formType)->getForm();
     $form->get('name')->addError(new FormError('Invalid name'));
     $exceptionWrapper = new ExceptionWrapper(['status_code' => 400, 'message' => 'Validation Failed', 'errors' => $form]);
     $view = new View($exceptionWrapper);
     $view->getSerializationContext()->addGroups(['Custom']);
     $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface', ['trans', 'transChoice', 'setLocale', 'getLocale']);
     $translatorMock->expects($this->any())->method('trans')->will($this->returnArgument(0));
     $viewHandler = $this->createViewHandler([]);
     $viewHandler->setSerializationContextAdapter($this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface'));
     $response = $viewHandler->createResponse($view, new Request(), $format);
     $viewHandler = $this->createViewHandler([]);
     $viewHandler->setSerializationContextAdapter($this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface'));
     $view2 = new View($exceptionWrapper);
     $response2 = $viewHandler->createResponse($view2, new Request(), $format);
     $this->assertEquals($response->getContent(), $response2->getContent());
 }
 private function serializationGroupsMatches(View $subject, $argument)
 {
     if (isset($argument['serializationGroups'])) {
         if (empty($argument['serializationGroups'])) {
             return false;
         }
         foreach ($argument['serializationGroups'] as $group) {
             $property = new PropertyMetadataFake();
             $property->groups = [$group];
             $context = $subject->getSerializationContext();
             if ($context->getExclusionStrategy()->shouldSkipProperty($property, $context)) {
                 return false;
             }
         }
     }
     return true;
 }
Example #14
0
 /**
  * Gets or creates a JMS\Serializer\SerializationContext and initializes it with
  * the view exclusion strategies, groups & versions if a new context is created.
  *
  * @param View $view
  *
  * @return SerializationContext
  */
 protected function getSerializationContext(View $view)
 {
     $context = $view->getSerializationContext();
     if ($context->attributes->get('groups')->isEmpty() && $this->exclusionStrategyGroups) {
         $context->setGroups($this->exclusionStrategyGroups);
     }
     if ($context->attributes->get('version')->isEmpty() && $this->exclusionStrategyVersion) {
         $context->setVersion($this->exclusionStrategyVersion);
     }
     if (null === $context->shouldSerializeNull() && null !== $this->serializeNullStrategy) {
         $context->setSerializeNull($this->serializeNullStrategy);
     }
     return $context;
 }
 /**
  * Gets or creates a JMS\Serializer\SerializationContext and initializes it with
  * the view exclusion strategies, groups & versions if a new context is created
  *
  * @param View $view
  *
  * @return SerializationContext
  */
 public function getSerializationContext(View $view)
 {
     $context = $view->getSerializationContext();
     if (null === $context) {
         $context = new SerializationContext();
         $groups = $this->container->getParameter('fos_rest.serializer.exclusion_strategy.groups');
         if ($groups) {
             $context->setGroups($groups);
         }
         $version = $this->container->getParameter('fos_rest.serializer.exclusion_strategy.version');
         if ($version) {
             $context->setVersion($version);
         }
     }
     return $context;
 }
Example #16
0
 /**
  * Presents the form to use to update an existing fly.
  *
  * @throws AccessDeniedException
  *
  * @ApiDoc(
  *   resource = true,
  *   statusCodes={
  *     200 = "Returned when successful",
  *     404 = "Returned when the fly is not found"
  *   }
  * )
  *
  * @Annotations\View()
  *
  * @param Request $request the request object
  * @param int     $id      the fly id
  *
  * @return FormTypeInterface
  *
  * @throws NotFoundHttpException when fly not exist
  */
 public function editFliesAction(Request $request, $id)
 {
     if (!$this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
         throw new AccessDeniedException();
     }
     $fly = $this->getFlyRepository()->find($id);
     if (false === $fly) {
         throw $this->createNotFoundException("Fly does not exist.");
     }
     $form = $this->createForm(new FlyType(), $fly);
     $view = new View($form);
     $group = $this->container->get('security.context')->isGranted('ROLE_API') ? 'restapi' : 'standard';
     $view->getSerializationContext()->setGroups(array('Default', $group));
     return $view;
 }
 protected function handleView(View $view)
 {
     $handler = $this->get('fos_rest.view_handler');
     $context = $view->getSerializationContext();
     if ($groups = $this->config->getSerializationGroups()) {
         $context->setGroups($groups);
     }
     if ($version = $this->config->getSerializationVersion()) {
         $context->setVersion($version);
     }
     return $handler->handle($view);
 }
Example #18
0
 /**
  * Gets or creates a JMS\Serializer\SerializationContext and initializes it with
  * the view exclusion strategies, groups & versions if a new context is created.
  *
  * @param View $view
  *
  * @return ContextInterface
  */
 protected function getSerializationContext(View $view)
 {
     $context = $view->getSerializationContext();
     if ($context instanceof GroupableContextInterface) {
         $groups = $context->getGroups();
         if (empty($groups) && $this->exclusionStrategyGroups) {
             $context->addGroups((array) $this->exclusionStrategyGroups);
         }
     }
     if ($context instanceof VersionableContextInterface && null === $context->getVersion() && $this->exclusionStrategyVersion) {
         $context->setVersion($this->exclusionStrategyVersion);
     }
     if ($context instanceof SerializeNullContextInterface && null === $context->getSerializeNull()) {
         $context->setSerializeNull($this->serializeNullStrategy);
     }
     return $context;
 }
Example #19
0
 /**
  * Gets or creates a JMS\Serializer\SerializationContext and initializes it with
  * the view exclusion strategies, groups & versions if a new context is created
  *
  * @param View $view
  *
  * @return SerializationContext
  */
 public function getSerializationContext(View $view)
 {
     $context = $view->getSerializationContext();
     if ($context->attributes->get('groups')->isEmpty()) {
         $groups = $this->container->getParameter('fos_rest.serializer.exclusion_strategy.groups');
         if ($groups) {
             $context->setGroups($groups);
         }
     }
     if ($context->attributes->get('version')->isEmpty()) {
         $version = $this->container->getParameter('fos_rest.serializer.exclusion_strategy.version');
         if ($version) {
             $context->setVersion($version);
         }
     }
     if (null === $context->shouldSerializeNull()) {
         $serializeNull = $this->container->getParameter('fos_rest.serializer.serialize_null');
         $context->setSerializeNull($serializeNull);
     }
     return $context;
 }