/**
  * @param Serializer $serializer
  * @param SqsClient  $sqsClient
  */
 public function __construct(Serializer $serializer, SqsClient $sqsClient)
 {
     $this->serializer = $serializer;
     $this->sqsClient = $sqsClient;
     $this->serializationContext = new SerializationContext();
     $this->serializationContext->setSerializeNull(true);
 }
Esempio n. 2
0
 /**
  * {@inheritdoc}
  */
 public function serializeEmbeddeds(array $embeddeds, XmlSerializationVisitor $visitor, SerializationContext $context)
 {
     foreach ($embeddeds as $embedded) {
         if ($embedded->getData() instanceof \Traversable || is_array($embedded->getData())) {
             foreach ($embedded->getData() as $data) {
                 $entryNode = $visitor->getDocument()->createElement('resource');
                 $visitor->getCurrentNode()->appendChild($entryNode);
                 $visitor->setCurrentNode($entryNode);
                 $visitor->getCurrentNode()->setAttribute('rel', $embedded->getRel());
                 if (null !== ($node = $context->accept($data))) {
                     $visitor->getCurrentNode()->appendChild($node);
                 }
                 $visitor->revertCurrentNode();
             }
             continue;
         }
         $entryNode = $visitor->getDocument()->createElement('resource');
         $visitor->getCurrentNode()->appendChild($entryNode);
         $visitor->setCurrentNode($entryNode);
         $visitor->getCurrentNode()->setAttribute('rel', $embedded->getRel());
         if (null !== ($node = $context->accept($embedded->getData()))) {
             $visitor->getCurrentNode()->appendChild($node);
         }
         $visitor->revertCurrentNode();
     }
 }
Esempio n. 3
0
 /**
  * @param SerializableInterface $serializable
  * @param SerializationContext  $serializationContext
  *
  * @return SerializationContext
  */
 private function getSerializationContext(SerializableInterface $serializable, SerializationContext $serializationContext)
 {
     if ($serializable instanceof OrderInterface) {
         $serializationContext->setGroups($this->groupsSpecifier->specifyGroups($serializable));
     }
     return $serializationContext;
 }
 /**
  * @param GetResponseForControllerResultEvent $event
  */
 public function serializeResponse(GetResponseForControllerResultEvent $event)
 {
     if ($this->doSerialize) {
         $data = $event->getControllerResult();
         $apiResponse = new ApiResponse(200, $data);
         $data = array_merge($apiResponse->toArray(), $this->data->all());
         $data = array_filter($data);
         if (!isset($data['data'])) {
             $data['data'] = [];
         }
         $context = new SerializationContext();
         $context->setSerializeNull(true);
         if (method_exists($context, 'enableMaxDepthChecks')) {
             $context->enableMaxDepthChecks();
         }
         if ($action = $this->getAction($event)) {
             $context->setGroups($action->getSerializationGroups());
         }
         if ($fields = $event->getRequest()->query->get('fields')) {
             $context->addExclusionStrategy(new FieldsListExclusionStrategy($fields));
         }
         $json = $this->serializer->serialize($data, 'json', $context);
         $response = new Response($json, 200, ['Content-Type' => 'application/json']);
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
Esempio n. 5
0
 /**
  * Информация о стране по id
  *
  * @param Country $country
  *
  * @Rest\Get("countries/{id}", requirements={"id"="\d+"})
  * @ParamConverter("country", class="VifeedGeoBundle:Country")
  * @ApiDoc(
  *     section="Campaign API",
  *     requirements={
  *       {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="id страны"}
  *     },
  *     output={
  *          "class"="Vifeed\GeoBundle\Entity\Country",
  *          "groups"={"default"}
  *     },
  *     statusCodes={
  *         200="Returned when successful",
  *         403="Returned when the user is not authorized to use this method",
  *         404="Returned when campaign not found"
  *     }
  * )
  *
  * @return Response
  */
 public function getCountryAction(Country $country)
 {
     $context = new SerializationContext();
     $context->setGroups(['default']);
     $view = new View($country);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
 /**
  * Serializes data to JSON, optionally filtering on a serialization group.
  *
  * @param mixed  $data
  * @param string $group
  */
 public function serialize($data, $group = null)
 {
     $context = new SerializationContext();
     if ($group) {
         $context->setGroups($group);
     }
     return $this->container->get('serializer')->serialize($data, 'json', $context);
 }
 /**
  * Render the view into a string and return for output
  *
  * @param mixed $input
  * @return string
  * @throws \Exception
  */
 public function render($input = null)
 {
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $context->enableMaxDepthChecks();
     FrontController::getInstance()->getResponse()->headers->set('Content-Type', 'application/json');
     return $this->serializer->serialize($input, $this->format, $context);
 }
 protected function serializeObject($object)
 {
     $serializer = SerializerBuilder::create()->build();
     $serializationContext = new SerializationContext();
     $serializationContext->setSerializeNull(true);
     $objectJson = $serializer->serialize($object, 'json', $serializationContext);
     return json_decode($objectJson);
 }
Esempio n. 9
0
 public function json($data, $groups = null)
 {
     if ($groups) {
         $this->context->setGroups($groups);
     }
     $serializedData = $this->serializer->serialize($data, 'json', $this->context);
     return $serializedData;
 }
Esempio n. 10
0
 /**
  * @param SerializerInterface $serializer
  */
 public function __construct(SerializerInterface $serializer = null)
 {
     $this->serializer = $serializer ?: SerializerBuilder::create()->build();
     $this->serializationContext = new SerializationContext();
     $this->serializationContext->setSerializeNull(true);
     $this->deserializationContext = new DeserializationContext();
     $this->deserializationContext->setSerializeNull(true);
 }
Esempio n. 11
0
 protected function jsonResponse($data)
 {
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $content = $this->serializer->serialize($data, 'json', $context);
     $this->response->setContent($content);
     return $this->response;
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 public function serializeEmbedded(array $embeds, JsonSerializationVisitor $visitor, SerializationContext $context)
 {
     $serializedEmbeds = array();
     foreach ($embeds as $embed) {
         $serializedEmbeds[$embed->getRel()] = $context->accept($embed->getData());
     }
     $visitor->addData('_embedded', $serializedEmbeds);
 }
 /**
  * @Route("/collection/category/{id}", methods={"GET"}, requirements={"id"="^[0-9].*$"})
  * @param CollectionCategory $collectionCategory
  * @return CollectionCategory
  */
 public function getCollectionCategoryAction(CollectionCategory $collectionCategory)
 {
     $serializer = $this->get("jms_serializer");
     $context = new SerializationContext();
     $context->enableMaxDepthChecks();
     $response = new Response($serializer->serialize($collectionCategory, 'json', $context));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  */
 public function setData($data = array())
 {
     $this->originalData = $data;
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $serializer = SerializerBuilder::create()->build();
     $this->data = $serializer->serialize($data, 'json', $context);
     return $this->update();
 }
 /**
  * @EXT\Route(
  *     "/card_learning/all/deck/{deck}",
  *     name="claroline_getall_card_learning"
  * )
  *
  * @param Deck $deck
  *
  * @return JsonResponse
  */
 public function allCardLearningAction(Deck $deck)
 {
     $this->assertCanOpen($deck);
     $user = $this->tokenStorage->getToken()->getUser();
     $cardLearnings = $this->manager->allCardLearning($deck, $user);
     $context = new SerializationContext();
     $context->setGroups('api_flashcard_card');
     return new JsonResponse(json_decode($this->serializer->serialize($cardLearnings, 'json', $context)));
 }
Esempio n. 16
0
 /**
  * Информация о юзере
  *
  * @ApiDoc(
  *     section="User API",
  *     output={
  *          "class"="Vifeed\UserBundle\Entity\User",
  *          "groups"={"user"}
  *     },
  *     statusCodes={
  *         200="Returned when successful",
  *         403="Returned when the user is not authorized to use this method"
  *     }
  * )
  *
  * @Rest\Get("users/current")
  *
  * @return Response
  */
 public function getUserAction()
 {
     $user = $this->getUser();
     $context = new SerializationContext();
     $context->setGroups(array('user'));
     $view = new View($user);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
Esempio n. 17
0
 /**
  * Create a new serialization context
  *
  * @param array $groups [optional]
  * @return SerializationContext
  */
 protected function createNewContext(array $groups = null)
 {
     $context = new SerializationContext();
     $context->setSerializeNull($this->serializeNull);
     if (null !== $groups) {
         $context->setGroups($groups);
     }
     return $context;
 }
 /**
  * @Route("/monster/{id}", methods={"GET"}, requirements={"id"="^[0-9].*$"})
  * @param Monster $monster
  * @return Monster
  */
 public function getMonsterAction(Monster $monster)
 {
     $serializer = $this->get("jms_serializer");
     $context = new SerializationContext();
     $context->enableMaxDepthChecks();
     $response = new Response($serializer->serialize($monster, 'json', $context));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function serialize($data, $format, SerializationContext $context = null)
 {
     if ($format === 'json') {
         foreach ($this->exclusionStrategies as $exclusionStrategy) {
             $context->addExclusionStrategy($exclusionStrategy);
         }
     }
     return parent::serialize($data, $format, $context);
 }
Esempio n. 20
0
 public static function create($data = null, $statusCode = null, array $headers = array(), array $groups = array())
 {
     $view = parent::create($data, $statusCode, $headers);
     if ($groups) {
         $context = new SerializationContext();
         $context->setGroups($groups);
         $view->setSerializationContext($context);
     }
     return $view;
 }
 public function testToArrayUseProvidedSerializationContext()
 {
     $contextFactoryMock = $this->getMockForAbstractClass('JMS\\Serializer\\ContextFactory\\SerializationContextFactoryInterface');
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $contextFactoryMock->expects($this->once())->method('createSerializationContext')->will($this->returnValue($context));
     $this->serializer->setDefaultSerializationContextFactory($contextFactoryMock);
     $result = $this->serializer->toArray(array('value' => null));
     $this->assertEquals(array('value' => null), $result);
 }
 function it_should_thow_exception_on_invalid_serialization_group()
 {
     $subject = ['data' => ['username' => 'drymek'], 'statusCode' => Codes::HTTP_OK, 'serializationGroups' => ['user_profile'], 'headers' => ['cache-control' => ['no-cache'], 'date' => ["@string@.isDateTime()"]]];
     $arguments = [$subject];
     $view = View::create($subject['data'], $subject['statusCode'], []);
     $context = new SerializationContext();
     $context->setGroups(['other']);
     $view->setSerializationContext($context);
     $this->shouldThrow(new FailureException('Expected serialization group to be user_profile, but they are not'))->during('positiveMatch', ['', $view, $arguments]);
 }
Esempio n. 23
0
 /**
  * Список городов по стране
  *
  * @param Country $country
  *
  * @Rest\Get("/countries/{id}/cities", requirements={"id"="\d+"})
  * @ParamConverter("country", class="VifeedGeoBundle:Country")
  * @ApiDoc(
  *     section="Geo API",
  *     resource=true,
  *     requirements={
  *       {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="id страны"}
  *     },
  *     output={
  *          "class"="Vifeed\GeoBundle\Entity\City",
  *          "groups"={"default"}
  *     },
  *     statusCodes={
  *         200="Returned when successful",
  *         403="Returned when the user is not authorized to use this method",
  *         404="Returned when country not found"
  *     }
  * )
  *
  * @return Response
  */
 public function getCitiesByCountryAction(Country $country)
 {
     /** @var City[] $data */
     $data = $this->getDoctrine()->getRepository('VifeedGeoBundle:City')->findBy(['country' => $country]);
     $context = new SerializationContext();
     $context->setGroups(['default']);
     $view = new View($data);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
Esempio n. 24
0
 private function shouldSkip($object, Exclusion $exclusion = null, SerializationContext $context)
 {
     if (null !== $exclusion && null !== $exclusion->getExcludeIf() && $this->expressionEvaluator->evaluate($exclusion->getExcludeIf(), $object)) {
         return true;
     }
     if (!$context->getExclusionStrategy()) {
         return false;
     }
     $propertyMetadata = new RelationPropertyMetadata($exclusion);
     return $context->getExclusionStrategy()->shouldSkipProperty($propertyMetadata, $context);
 }
Esempio n. 25
0
 /**
  * @EXT\Route(
  *     "/session/create/deck/{deck}",
  *     name="claroline_create_session"
  * )
  *
  * @param Deck $deck
  *
  * @return JsonResponse
  */
 public function createSessionAction(Deck $deck)
 {
     $this->assertCanOpen($deck);
     $user = $this->tokenStorage->getToken()->getUser();
     $session = new Session();
     $session->setDeck($deck);
     $session->setUser($user);
     $session = $this->manager->save($session);
     $context = new SerializationContext();
     $context->setGroups('api_flashcard_session');
     return new JsonResponse(json_decode($this->serializer->serialize($session, 'json', $context)));
 }
Esempio n. 26
0
 /**
  * Create new account
  */
 public function postAccountsAction()
 {
     try {
         $account = $this->accountService->createAccount($this->request);
     } catch (FormValidationException $e) {
         return View::create($e->getForm(), 400);
     }
     $view = View::create($account, 201)->setHeader('Location', $this->router->generate('get_account', ['id' => $account->getId()], true));
     $context = new SerializationContext();
     $context->setGroups(array('account_list'));
     $view->setSerializationContext($context);
     return $view;
 }
Esempio n. 27
0
 public function serialize($data, $format, SerializationContext $context = null)
 {
     if (!$this->serializationVisitors->containsKey($format)) {
         throw new UnsupportedFormatException(sprintf('The format "%s" is not supported for serialization.', $format));
     }
     if (null === $context) {
         $context = new SerializationContext();
     }
     $context->initialize($format, $visitor = $this->serializationVisitors->get($format)->get(), $this->navigator, $this->factory);
     $visitor->setNavigator($this->navigator);
     $this->navigator->accept($visitor->prepare($data), null, $context);
     return $visitor->getResult();
 }
Esempio n. 28
0
 /**
  */
 public function postCustomersAction()
 {
     try {
         $customer = $this->customerService->createCustomer($this->request);
     } catch (FormValidationException $e) {
         return View::create($e->getForm(), 400);
     }
     $view = View::create($customer, 201)->setHeader('Location', $this->router->generate('get_customer', ['id' => $customer->getId()], true));
     $context = new SerializationContext();
     $context->setGroups(array('customer_list'));
     $view->setSerializationContext($context);
     return $view;
 }
 public function serializerAction()
 {
     $article = new Article();
     $article->setPath('/foo');
     $article->setTitle('Example use of the default handlers');
     $article->setBody("Read up on JMSSerializerBundle to see how what other handlers exist ");
     $view = new View();
     $view->setData($article);
     $context = new SerializationContext();
     $context->setVersion('2.1');
     $context->setGroups(array('data'));
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
Esempio n. 30
0
 /**
  * @Route("/connected_roles")
  */
 public function connectedRoles()
 {
     /** @var \Symfony\Component\Security\Core\SecurityContext $securityContext */
     $tokenStorage = $this->container->get('security.token_storage');
     $token = $tokenStorage->getToken();
     if ($token) {
         $roles = $token->getRoles();
         $context = new SerializationContext();
         $context->setGroups('api_user');
         $data = $this->container->get('serializer')->serialize($roles, 'json');
         $roles = json_decode($data);
         return new JsonResponse($roles);
     }
     throw new \Exception('No security token.');
 }