Beispiel #1
0
 public function json($data, $groups = null)
 {
     if ($groups) {
         $this->context->setGroups($groups);
     }
     $serializedData = $this->serializer->serialize($data, 'json', $this->context);
     return $serializedData;
 }
Beispiel #2
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;
 }
 /**
  * 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);
 }
Beispiel #4
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);
 }
Beispiel #5
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);
 }
 /**
  * @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)));
 }
Beispiel #7
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;
 }
 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;
 }
Beispiel #9
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);
 }
 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]);
 }
 /**
  * @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)));
 }
Beispiel #12
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;
 }
Beispiel #13
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;
 }
 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);
 }
Beispiel #15
0
 /**
  * @ApiDoc
  *
  * @param integer $objectId            
  * @throws NotFoundHttpException
  */
 public function getUserAction($userId = 0)
 {
     /* @var $model \App\ModuleObjectsBundle\Model\MapObjectModel */
     $model = $this->container->get('app_module_user.model.user');
     $data = $model->findOneById($userId);
     if (null === $data) {
         throw new NotFoundHttpException();
     }
     $view = new View();
     $view->setData($data);
     $context = new SerializationContext();
     $context->setGroups(array('.all', 'user.get'));
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
Beispiel #16
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.');
 }
 public function cgetAction(Request $request)
 {
     $adminCode = $request->get('_sonata_admin');
     if (!$adminCode) {
         throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $request->get('_route')));
     }
     $admin = $this->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
     if (false === $admin->isGranted('LIST')) {
         throw new AccessDeniedException();
     }
     /** @var MenuItemRepository $menuRepository */
     $menuRepository = $this->get('doctrine.orm.entity_manager')->getRepository('GravityMenuBundle:MenuItem');
     $menus = $menuRepository->findBy(['parent' => null], null, 20, 0);
     $view = new View($menus);
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $context->setGroups(['gravity_api_read']);
     $view->setSerializationContext($context);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
Beispiel #18
0
 /**
  * вывести деньги
  *
  * @ApiDoc(
  *     section="Billing API",
  *     input="Vifeed\PaymentBundle\Form\WithdrawalType",
  *     output={
  *          "class"="Vifeed\PaymentBundle\Entity\Withdrawal",
  *          "groups"={"default"}
  *     },
  *     resource=true,
  *     statusCodes={
  *         201="Returned when successful",
  *         400="Returned when something is wrong",
  *         403="Returned when the user is not authorized to use this method"
  *     }
  * )
  *
  * @return Response
  */
 public function putWithdrawalAction()
 {
     $form = $this->createForm(new WithdrawalType());
     $form->submit($this->get('request'));
     if ($form->isValid()) {
         /** @var Withdrawal $withdrawal */
         $withdrawal = $form->getData();
         if ($withdrawal->getWallet()->getUser() != $this->getUser()) {
             throw new AccessDeniedHttpException('Можно вывести только на свой кошелёк');
         }
         if ($withdrawal->getAmount() > $this->getUser()->getBalance()) {
             $form->get('amount')->addError(new FormError('Недостаточно денег на балансе'));
         } else {
             $userRepo = $this->em->getRepository('VifeedUserBundle:User');
             $this->em->beginTransaction();
             $this->em->lock($this->getUser(), LockMode::PESSIMISTIC_WRITE);
             try {
                 $withdrawal->setUser($this->getUser())->setStatus(Withdrawal::STATUS_CREATED);
                 $this->em->persist($withdrawal);
                 $userRepo->updateBalance($this->getUser(), -$withdrawal->getAmount());
                 $this->em->flush();
                 $this->em->commit();
             } catch (\Exception $e) {
                 $this->em->rollback();
                 $this->em->close();
                 throw $e;
             }
             $mailer = $this->get('vifeed.mailer');
             $message = $mailer->renderMessage('VifeedPaymentBundle:Email:withdrawal.html.twig', ['withdrawal' => $withdrawal]);
             $mailer->sendMessage('Запрос на вывод средств', $message, $this->container->getParameter('withdrawal.notification.email'));
             $context = new SerializationContext();
             $context->setGroups(array('default'));
             $view = new View($withdrawal, 201);
             $view->setSerializationContext($context);
         }
     }
     if (!$form->isValid()) {
         $view = new View($form, 400);
     }
     return $this->handleView($view);
 }
 /**
  * @param PaginationInterface $pagination
  * @param Request             $request
  * @param Router              $router
  * @param array               $serializationGroups
  *
  * @return mixed
  */
 public function buildMultiObjectResponse(PaginationInterface $pagination, Request $request, Router $router, array $serializationGroups = array())
 {
     if (empty($pagination->getItems())) {
         return $this->handle(View::create(null, Response::HTTP_NO_CONTENT));
     }
     $paginationData = $pagination->getPaginationData();
     $link = $this->buildPaginationLink($paginationData, $request, $router);
     $headers = [];
     if (!empty($link)) {
         $headers['Link'] = $link;
     }
     if (isset($paginationData['totalCount'])) {
         $headers['X-Total-Count'] = $paginationData['totalCount'];
     }
     $view = View::create($pagination->getItems(), Response::HTTP_OK, $headers);
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     if (!empty($serializationGroups)) {
         $context->setGroups($serializationGroups);
     }
     $view->setSerializationContext($context);
     return $this->handle($view);
 }
 /**
  * @EXT\Route(
  *     "/note/list/deck/{deck}/note_type/{noteType}",
  *     name="claroline_list_notes"
  * )
  *
  * @param Deck     $deck
  * @param NoteType $noteType
  *
  * @return JsonResponse
  */
 public function listNotesAction(Deck $deck, NoteType $noteType)
 {
     $this->assertCanOpen($deck);
     $notes = $this->manager->findByNoteType($deck, $noteType);
     $response = new JsonResponse();
     $context = new SerializationContext();
     $context->setGroups('api_flashcard_deck');
     return $response->setData(json_decode($this->serializer->serialize($notes, 'json', $context)));
 }
 /**
  * @param $fields
  * @return SerializationContext
  */
 protected function getContextWithFields($fields)
 {
     $context = new SerializationContext();
     $context->setGroups(['Default', 'Detail']);
     $context->addExclusionStrategy(new FieldsListExclusionStrategy($fields));
     return $context;
 }
Beispiel #22
0
 /**
  * Create serialization context with settings taken from the controller's annotation
  *
  * @param MappingInterface $mapping
  * @return SerializationContext
  */
 protected function createSerializationContext(MappingInterface $mapping)
 {
     $context = new SerializationContext();
     if ($mapping->getAnnotation()->getSerializerEnableMaxDepthChecks()) {
         $context->enableMaxDepthChecks();
     }
     if ($mapping->getAnnotation()->getSerializerGroups()) {
         $context->setGroups($mapping->getAnnotation()->getSerializerGroups());
     }
     if ($mapping->getAnnotation()->getSerializerSerializeNull()) {
         $context->setSerializeNull(true);
     }
     return $context;
 }
 /**
  * @param array $groups
  * @return $this
  */
 public function setSerializationGroups($groups)
 {
     $this->context->setGroups($groups);
     return $this;
 }
Beispiel #24
0
 private function createSerialized($data, $serializerGroup)
 {
     $context = new SerializationContext();
     $format = $this->container->get('request')->getRequestFormat();
     $format = $format === 'html' ? 'json' : $format;
     $context->setGroups($serializerGroup);
     $content = $this->container->get('serializer')->serialize($data, $format, $context);
     $response = new Response($content);
     $response->headers->set('Content-Type', $this->container->get('request')->getMimeType($format));
     return $response;
 }
Beispiel #25
0
 /**
  * Создать новую кампанию
  *
  * @ApiDoc(
  *     section="Campaign API",
  *     input="Vifeed\CampaignBundle\Form\CampaignType",
  *     output={
  *          "class"="Vifeed\CampaignBundle\Entity\Campaign",
  *          "groups"={"own"}
  *     },
  *     statusCodes={
  *         201="Returned when successful",
  *         400="Returned when the something was wrong",
  *         403="Returned when the user is not authorized to use this method"
  *     }
  * )
  *
  * @return Response
  */
 public function putCampaignsAction()
 {
     if ($this->getUser()->getType() != User::TYPE_ADVERTISER) {
         throw new AccessDeniedHttpException('Вы не можете создавать кампании');
     }
     $form = $this->createCampaignForm();
     if ($form->isValid()) {
         /** @var Campaign $campaign */
         $campaign = $form->getData();
         $campaign->setUser($this->getUser());
         $this->campaignManager->save($campaign);
         $view = new View($campaign, 201);
         $context = new SerializationContext();
         $context->setGroups(['own']);
         $view->setSerializationContext($context);
     } else {
         $view = new View($form, 400);
     }
     return $this->handleView($view);
 }
Beispiel #26
0
 /**
  * 
  * @param mixed $data
  * @param array $groups
  * @return FOSview
  */
 private function setGroup($data, $groups = array("all_user"))
 {
     $view = $this->view($data, 200);
     $context = new SerializationContext();
     $context->setGroups($groups);
     $view->setSerializationContext($context);
     return $view;
 }
Beispiel #27
0
 /**
  * Все кошельки юзера
  *
  * @ApiDoc(
  *     section="Billing API",
  *     output={
  *          "class"="Vifeed\PaymentBundle\Entity\Wallet",
  *          "groups"={"default"}
  *     },
  *     statusCodes={
  *         200="Returned when successful",
  *         403="Returned when the user is not authorized to use this method"
  *     }
  * )
  *
  * @return Response
  */
 public function getWalletsAction()
 {
     $data = $this->em->getRepository('VifeedPaymentBundle:Wallet')->getWalletsDataByUser($this->getUser());
     $wallets = [];
     $walletData = [];
     foreach ($data as $row) {
         /** @var Wallet $wallet */
         $wallet = $row[0];
         $wallets[] = $wallet;
         unset($row[0]);
         $walletData[$wallet->getId()] = $row;
     }
     $context = new SerializationContext();
     $context->setGroups(['default'])->setAttribute('wallet_data', $walletData);
     $view = new View($wallets);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
 /**
  * @EXT\Route(
  *     "/card/card_to_review/deck/{deck}",
  *     name="claroline_card_to_review"
  * )
  *
  * @param Deck $deck
  *
  * @return JsonResponse
  */
 public function cardToReviewAction(Deck $deck)
 {
     $this->assertCanOpen($deck);
     $user = $this->tokenStorage->getToken()->getUser();
     $date = new \DateTime();
     $cards = $this->cardMgr->getCardToReview($deck, $user, $date);
     $context = new SerializationContext();
     $context->setGroups('api_flashcard_card');
     return new JsonResponse(json_decode($this->serializer->serialize($cards, 'json', $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;
 }
 /**
  * @EXT\Route(
  *     "/deck/{deck}/get_user_pref",
  *     name="claroline_get_user_pref"
  * )
  *
  * @param Deck $deck
  *
  * @return JsonResponse
  */
 public function getUserPreference(Deck $deck)
 {
     $response = new JsonResponse();
     $this->assertCanOpen($deck);
     $user = $this->tokenStorage->getToken()->getUser();
     $userPref = $deck->getUserPreference($user);
     $context = new SerializationContext();
     $context->setGroups('api_flashcard_user_pref');
     $response->setData(json_decode($this->serializer->serialize($userPref, 'json', $context)));
     return $response;
 }