예제 #1
0
 protected function jmsSerialization($serializationObject, $groups, $type = 'json')
 {
     /** @var $serializer \JMS\Serializer\Serializer */
     $serializer = $this->get('jms_serializer');
     $serializerContext = SerializationContext::create()->setGroups($groups);
     return $serializer->serialize($serializationObject, $type, $serializerContext);
 }
예제 #2
0
 /**
  * @param array $data
  * @param string|null|array $serializationLevel
  * @return Response
  */
 public function createResponse(array $data, $serializationLevel = null)
 {
     $responseData = [static::KEY_STATUS => static::STATUS_SUCCESS, static::KEY_DATA => $data];
     $serializedData = $this->serializer->serialize($responseData, self::STANDARD_RESPONSE_FORMAT, $serializationLevel ? SerializationContext::create()->setGroups($serializationLevel) : SerializationContext::create());
     $response = $this->getJsonResponse($serializedData);
     return $response;
 }
예제 #3
0
 /**
  * @param Context $context
  * @param int     $direction {@see self} constants
  *
  * @return JMSContext
  */
 private function convertContext(Context $context, $direction)
 {
     if ($direction === self::SERIALIZATION) {
         $jmsContext = JMSSerializationContext::create();
     } else {
         $jmsContext = JMSDeserializationContext::create();
         if (null !== $context->getMaxDepth()) {
             for ($i = 0; $i < $context->getMaxDepth(); ++$i) {
                 $jmsContext->increaseDepth();
             }
         }
     }
     foreach ($context->getAttributes() as $key => $value) {
         $jmsContext->attributes->set($key, $value);
     }
     if (null !== $context->getVersion()) {
         $jmsContext->setVersion($context->getVersion());
     }
     $groups = $context->getGroups();
     if (!empty($groups)) {
         $jmsContext->setGroups($context->getGroups());
     }
     if (null !== $context->getMaxDepth()) {
         $jmsContext->enableMaxDepthChecks();
     }
     if (null !== $context->getSerializeNull()) {
         $jmsContext->setSerializeNull($context->getSerializeNull());
     }
     return $jmsContext;
 }
 /**
  * This make sure there is no regression to retrieve the current website in a sub request
  *
  * reference: https://github.com/sonata-project/SonataPageBundle/pull/211
  *
  * @param Request $request
  *
  * @return Response
  */
 public function serializeAction(Request $request)
 {
     $raw = array('json' => 'no data available', 'xml' => 'no data available');
     if ($request->isMethod('POST')) {
         $class = $request->get('class');
         if ($request->get('id')) {
             $object = $this->getDoctrine()->getRepository($class)->find($request->get('id'));
         } else {
             $object = $this->getDoctrine()->getRepository($class)->findOneBy(array());
         }
         $serializationContext = SerializationContext::create();
         $serializationContext->enableMaxDepthChecks();
         if ($request->get('group')) {
             $serializationContext->setGroups(array($request->get('group')));
         }
         if ($request->get('version')) {
             $serializationContext->setVersion($request->get('version'));
         }
         $jsonSerializationContext = $serializationContext;
         $xmlSerializationContext = clone $serializationContext;
         $raw = array('json' => $this->get('jms_serializer')->serialize($object, 'json', $jsonSerializationContext), 'xml' => $this->get('jms_serializer')->serialize($object, 'xml', $xmlSerializationContext));
     }
     $metas = $this->getDoctrine()->getManager()->getMetadataFactory()->getAllMetadata();
     $classes = array();
     foreach ($metas as $name => $meta) {
         if ($meta->reflClass->isAbstract()) {
             continue;
         }
         $classes[] = $meta->name;
     }
     return $this->render('SonataQABundle:Serializer:serialize.html.twig', array('classes' => $classes, 'raw' => $raw));
 }
예제 #5
0
 /**
  *  RPC url action
  *
  * @param $bundle
  * @param $service
  * @param $method
  * @param Request $request
  *
  * @Route("/{bundle}/{service}/{method}" , defaults={"_format": "json"})
  * @Method("POST")
  *
  * @return Response
  */
 public function rpcAction($bundle, $service, $method, Request $request)
 {
     $response = new Response();
     $translator = $this->get('translator');
     try {
         $prefix = 'Hazu.Service';
         $serviceObject = $this->get("{$prefix}.{$bundle}.{$service}");
         if (true === method_exists($serviceObject, $method)) {
             $params = json_decode($request->getContent(), true);
             if (null === $params) {
                 throw new \Exception('$params não é um JSON valido');
             }
             $rService = $serviceObject->{$method}($params);
         } else {
             throw new \Exception($translator->trans('Metodo não encontrado'));
         }
     } catch (ServiceNotFoundException $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } catch (\Exception $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } finally {
         $serializer = SerializerBuilder::create()->build();
         $rJson = $serializer->serialize($rService, 'json', SerializationContext::create()->enableMaxDepthChecks());
         $response->headers->set('x-hazu-type', gettype($rService));
         if (gettype($rService) == 'object') {
             $response->headers->set('x-hazu-class', get_class($rService));
         }
         $response->setContent($rJson);
     }
     return $response;
 }
 /**
  * Returns response based on request content type
  * @param  Request $request       [description]
  * @param  [type]  $response_data [description]
  * @param  integer $response_code [description]
  * @return [type]                 [description]
  */
 protected function handleResponse(Request $request, $response_data, $response_code = 200)
 {
     $response = new Response();
     $contentType = $request->headers->get('Content-Type');
     $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
     if ($format == 'json') {
         $serializer = $this->get('serializer');
         $serialization_context = SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('Default', 'detail', 'from_user', 'from_oauth'));
         $response->setContent($serializer->serialize($response_data, 'json', $serialization_context));
         $response->headers->set('Content-Type', 'application/json');
     } else {
         if (is_array($response_data)) {
             if (isset($response_data['message'])) {
                 $response->setContent($response_data['message']);
             } else {
                 $response->setContent(json_encode($response_data));
             }
         }
     }
     if ($response_code == 0) {
         $response->setStatusCode(500);
     } else {
         $response->setStatusCode($response_code);
     }
     return $response;
 }
 /**
  * @return SerializationContext
  */
 protected function getContext()
 {
     if ($this->context === null) {
         $this->context = SerializationContext::create();
     }
     return $this->context;
 }
예제 #8
0
파일: App.php 프로젝트: lstaszak/zf2main
 protected function toArray($oObject)
 {
     $oSerializer = SerializerBuilder::create()->build();
     $aArray = $oSerializer->toArray($oObject, SerializationContext::create()->enableMaxDepthChecks());
     $this->_aArray = $aArray;
     return $this;
 }
예제 #9
0
 /**
  * Get a content items by a list of ids
  *
  * @param string $ids
  *
  * @return JsonResponse
  */
 public function idsAction($ids)
 {
     $items = $this->get('opifer.content.content_manager')->getRepository()->findAddressableByIds($ids);
     $contents = $this->get('jms_serializer')->serialize($items, 'json', SerializationContext::create()->setGroups(['list'])->enableMaxDepthChecks());
     $data = ['results' => json_decode($contents, true), 'total_results' => count($items)];
     return new JsonResponse($data);
 }
 /**
  * @FosRest\Get("/{section}")
  *
  * @ApiDoc(
  *  description = "Get the details of a section."
  * )
  *
  * @ParamConverter("section", class="MainBundle:Section")
  *
  * @FosRest\QueryParam(
  *     name = "token",
  *     nullable = false,
  *     description = "Mobilit token."
  * )
  *
  * @param Section $section
  * @param ParamFetcher $paramFetcher
  *
  * @return Response
  */
 public function getAction(Section $section, ParamFetcher $paramFetcher)
 {
     if ($this->container->getParameter('mobilit_token') != $paramFetcher->get('token')) {
         return new Response(json_encode(["message" => $this->get('translator')->trans("errors.api.android.v1.token")]), Response::HTTP_FORBIDDEN);
     }
     return new Response($this->get('serializer')->serialize($section, 'json', SerializationContext::create()->setGroups(array('details'))));
 }
 /**
  * @dataProvider getExclusionRules
  * @param array $propertyGroups
  * @param array $groups
  * @param $exclude
  */
 public function testUninitializedContextIsWorking(array $propertyGroups, array $groups, $exclude)
 {
     $metadata = new StaticPropertyMetadata('stdClass', 'prop', 'propVal');
     $metadata->groups = $propertyGroups;
     $strat = new GroupsExclusionStrategy($groups);
     $this->assertEquals($strat->shouldSkipProperty($metadata, SerializationContext::create()), $exclude);
 }
 /**
  * [GET] /notificationparameters/{type}
  * Return parameters of a specific notification
  *
  * @QueryParam(name="field", nullable=true, description="(optional) notification field (to, from, content)")
  *
  * @param string $type
  * @param string $field
  */
 public function getNotificationparameterAction($type, $field = null)
 {
     $notifiers = $this->container->getParameter('idci_notification.notifiers');
     $notificationParameters = array();
     if (!in_array($type, $notifiers)) {
         $view = $this->view(array("Error" => $type . " is not a valide type."), Codes::HTTP_NOT_FOUND);
         return $this->handleView($view);
     }
     $notifier = $this->get(sprintf("idci_notification.notifier.%s", $type));
     if ($field) {
         $getField = sprintf("get%sFields", ucfirst($field));
         try {
             $notificationParameters[$field] = $notifier->{$getField}() ? $notifier->{$getField}() : null;
             $cleanedNotificationParameters = $notifier->cleanEmptyValue($notificationParameters);
             if (empty($cleanedNotificationParameters)) {
                 return $this->handleView($this->view(array("message" => "No data associated with the field : " . $field), Codes::HTTP_NOT_FOUND));
             }
             return $this->handleView($this->view($notifier->cleanEmptyValue($notificationParameters), Codes::HTTP_OK));
         } catch (\Exception $e) {
             $view = $this->view(array("message" => $e->getMessage()), Codes::HTTP_NOT_FOUND);
             return $this->handleView($view);
         }
     }
     $notificationParameters["to"] = $notifier->getToFields() ? $notifier->getToFields() : null;
     $notificationParameters["from"] = $notifier->getFromFields() ? $notifier->getFromFields() : null;
     $notificationParameters["content"] = $notifier->getContentFields() ? $notifier->getContentFields() : null;
     $context = SerializationContext::create()->setGroups(array('list'));
     $view = $this->view($notifier->cleanEmptyValue($notificationParameters), Codes::HTTP_OK);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
예제 #13
0
 /**
  * Exclusion strategy by JMS group name
  *
  * @author Huong Le <*****@*****.**>
  *
  * @param  Entity|Collection $data     Entity or array collection of entity
  * @param  string            $JMSGroup Name of JMS group
  *
  * @return array                       Array after the exclusion was done
  */
 public function getFinalResultByJMSGroup($data, $JMSGroup)
 {
     $serializer = SerializerBuilder::create()->build();
     $json = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups([$JMSGroup])->setSerializeNull(true)->enableMaxDepthChecks());
     $arr = json_decode($json, true);
     return $arr;
 }
예제 #14
0
 public function simpleSearchAction($format)
 {
     $request = $this->container->get('request');
     $serializer = $this->container->get('jms_serializer');
     $searchedTerm = $request->get('term');
     $useSynonyms = $request->get('useSynonyms');
     // Grabbing the repartition filters service, the department filter and the UE filter
     $repFilters = $this->get('eveg_app.repFilters');
     $depFrFilter = $repFilters->getDepFrFilterSession();
     $ueFilter = $repFilters->getUeFilterSession();
     if (!$searchedTerm) {
         throw new \Exception('Empty variable \'term\'.');
     }
     if (!$useSynonyms) {
         $useSynonyms = true;
     }
     $searchedTerm = $searchedTerm . ' ';
     $searchedTerm = str_replace(' ', '%', $searchedTerm);
     $result = $this->getDoctrine()->getManager()->getRepository('evegAppBundle:SyntaxonCore')->findForSearchEngine($searchedTerm, $useSynonyms, $depFrFilter, $ueFilter);
     $serializedResult = $serializer->serialize($result, $format, SerializationContext::create()->setGroups(array('searchEngine')));
     $response = new Response();
     $response->setContent($serializedResult);
     if ($format == 'json') {
         $response->headers->set('Content-Type', 'application/json');
     } elseif ($format == 'xml') {
         $response->headers->set('Content-Type', 'application/xml');
     }
     return $response;
 }
예제 #15
0
 /**
  * Perform a search and return a JSON response.
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function searchAction(Request $request)
 {
     $queryString = $request->query->get('q');
     $category = $request->query->get('category', null);
     $locale = $request->query->get('locale', null);
     $page = $this->listRestHelper->getPage();
     $limit = $this->listRestHelper->getLimit();
     $aggregateHits = [];
     $startTime = microtime(true);
     $categories = $category ? [$category] : $this->searchManager->getCategoryNames();
     foreach ($categories as $category) {
         $query = $this->searchManager->createSearch($queryString);
         if ($locale) {
             $query->locale($locale);
         }
         if ($category) {
             $query->category($category);
         }
         foreach ($query->execute() as $hit) {
             $aggregateHits[] = $hit;
         }
     }
     $time = microtime(true) - $startTime;
     $adapter = new ArrayAdapter($aggregateHits);
     $pager = new Pagerfanta($adapter);
     $pager->setMaxPerPage($limit);
     $pager->setCurrentPage($page);
     $representation = new SearchResultRepresentation(new CollectionRepresentation($pager->getCurrentPageResults(), 'result'), 'sulu_search_search', ['locale' => $locale, 'query' => $query, 'category' => $category], (int) $page, (int) $limit, $pager->getNbPages(), 'page', 'limit', false, count($aggregateHits), $this->getCategoryTotals($aggregateHits), number_format($time, 8));
     $view = View::create($representation);
     $context = SerializationContext::create();
     $context->enableMaxDepthChecks();
     $context->setSerializeNull(true);
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
예제 #16
0
 /**
  * Appends the given data to the app instance.
  * Additionally, sets the expiration header to 0, the
  * Content-Type to application/json and finally the HTTP status code to the
  * submitted one
  *
  * @param $app \Slim\Slim The slim application instance
  * @param $code integer The HTTP status code
  * @param $data mixed THe data to append as body to the response
  */
 public static function createJsonResponseWithCode($app, $code, $data)
 {
     $app->expires(0);
     $app->response->header('Content-Type', 'application/json');
     $app->response->setStatus($code);
     $app->response->setBody($app->serializer->serialize($data, 'json', SerializationContext::create()->enableMaxDepthChecks()));
 }
예제 #17
0
    public function testSerializeAdrienBraultWithExclusion()
    {
        $hateoas = HateoasBuilder::buildHateoas();
        $adrienBrault = new AdrienBrault();
        $fakeAdrienBrault = new AdrienBrault();
        $fakeAdrienBrault->firstName = 'John';
        $fakeAdrienBrault->lastName = 'Smith';
        $context = SerializationContext::create()->setGroups(array('simple'));
        $context2 = clone $context;
        $this->string($hateoas->serialize($adrienBrault, 'xml', $context))->isEqualTo(<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<result>
  <first_name><![CDATA[Adrien]]></first_name>
  <last_name><![CDATA[Brault]]></last_name>
  <link rel="self" href="http://adrienbrault.fr"/>
  <link rel="computer" href="http://www.apple.com/macbook-pro/"/>
</result>

XML
)->string($hateoas->serialize($fakeAdrienBrault, 'xml', $context2))->isEqualTo(<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<result>
  <first_name><![CDATA[John]]></first_name>
  <last_name><![CDATA[Smith]]></last_name>
  <link rel="computer" href="http://www.apple.com/macbook-pro/"/>
</result>

XML
);
    }
예제 #18
0
 /**
  * Test HashHandler::serializeHashToJson()
  *
  * @return void
  */
 public function testSerializeHashToJson()
 {
     $hash = new Hash([__METHOD__]);
     $type = [__FILE__];
     $context = SerializationContext::create();
     $serializationVisitor = $this->getMockBuilder('JMS\\Serializer\\JsonSerializationVisitor')->disableOriginalConstructor()->getMock();
     $this->assertEquals($hash, (new HashHandler())->serializeHashToJson($serializationVisitor, $hash, $type, $context));
 }
예제 #19
0
 /**
  * @ApiDoc(
  *  description="Create a new game",
  *  requirements={
  *      {"name"="roomId", "dataType"="integer", "requirement"="\d+", "description"="room id"}
  *  }
  * )
  */
 public function postGameAction($roomId)
 {
     $game = new Game($this->getRoom($roomId));
     $game->castRoles();
     $this->persist($game);
     $this->refresh($game);
     return $this->view($game, Codes::HTTP_CREATED)->setRoute('get_game')->setRouteParameters(['gameId' => $game->getId()])->setSerializationContext(SerializationContext::create()->setGroups(['Default']));
 }
예제 #20
0
 /**
  * {@inheritdoc}
  */
 public function post($uri, $data = null, array $options = array())
 {
     if (is_array($data)) {
         $options = array_merge($data, $options);
         $data = new \StdClass();
     }
     $this->request('post', $uri, array('body' => $this->serializer->serialize($data, 'json', SerializationContext::create()->setAttribute('options', $options))));
 }
예제 #21
0
 /**
  * Obtains a list of smart lists for the user
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getListsAction()
 {
     $lists = $this->factory->getModel('lead.list')->getUserLists();
     $view = $this->view($lists, Codes::HTTP_OK);
     $context = SerializationContext::create()->setGroups(array('leadListList'));
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
예제 #22
0
 /**
  * @ApiDoc(
  *  resource=true,
  *  description="Returns results of a game specified by gameId",
  *  requirements={
  *      {"name"="gameId", "dataType"="integer", "requirement"="\d+", "description"="game id"}
  *  },
  *  statusCodes={
  *      404="Returned when the game has not been finished."
  *  }
  * )
  */
 public function getResultAction($gameId)
 {
     $game = $this->getGame($gameId);
     if (!$game->hasFinished()) {
         throw new ResourceNotFoundException('The game has not been finished.');
     }
     return $view = $this->view($game, Codes::HTTP_OK)->setSerializationContext(SerializationContext::create()->setGroups(['Default', 'finished']));
 }
예제 #23
0
 /**
  * @inheritdoc
  */
 public function serialize($data, $format, $groups = null)
 {
     $context = null;
     if ($groups) {
         $context = SerializationContext::create()->setGroups($groups);
     }
     return $this->serializer->serialize($data, $format, $context);
 }
 /**
  * @FosRest\Get("")
  *
  * @ApiDoc(
  *  description = "List all the countries and their sections."
  * )
  *
  * @FosRest\QueryParam(
  *     name = "token",
  *     nullable = false,
  *     description = "Mobilit token."
  * )
  *
  * @param ParamFetcher $paramFetcher
  *
  * @return Response
  */
 public function listAction(ParamFetcher $paramFetcher)
 {
     if ($this->container->getParameter('mobilit_token') != $paramFetcher->get('token')) {
         return new Response(json_encode(["message" => $this->get('translator')->trans("errors.api.android.v1.token")]), Response::HTTP_FORBIDDEN);
     }
     $countries = $this->get('main.country.service')->getCountries(true);
     $serializer = $this->get('serializer');
     return new Response($serializer->serialize($countries, 'json', SerializationContext::create()->setGroups(array('listSection'))));
 }
예제 #25
0
 /**
  * {@inheritdoc}
  */
 public function convertSerializationContext(ContextInterface $context)
 {
     if (!$this->supportsSerialization($context)) {
         throw new \LogicException(sprintf('%s can\'t convert this serialization context.', get_class($this)));
     }
     $newContext = JMSSerializationContext::create();
     $this->fillContext($context, $newContext);
     return $newContext;
 }
예제 #26
0
 /**
  * Find and display an Artist entity.
  *
  * @ApiDoc(
  *  resource=true,
  *  description="Find and display an Artist entity.",
  *  requirements={
  *      {
  *          "name"="id",
  *          "description"="Id of the Artist entity how we want to show."
  *      }
  *  },
  *  statusCodes={
  *       200="Returned when successful",
  *       401="Returned when the user is not authorized to say hello",
  *       404={
  *         "Returned when the user is not found",
  *         "Returned when something else is not found"
  *       }
  *   }
  * )
  */
 public function getArtistAction($id)
 {
     $em = $this->getDoctrine()->getManager();
     $context = SerializationContext::create()->setGroups(array('artist_one'));
     $artist = $em->getRepository('MusicBundle:Artist')->findById($id);
     $view = $this->view($artist, 200);
     $view->setSerializationContext($context);
     return $this->handleView($view);
 }
예제 #27
0
 /**
  * @Route("/game/getall", name="fsd_game_getall")
  */
 public function getAllAction()
 {
     $objects = $this->getManager()->getAll();
     $tmp = array();
     foreach ($objects as $object) {
         $tmp[] = json_decode($this->get('jms_serializer')->serialize($object, 'json', SerializationContext::create()->setGroups(array('listgames'))));
     }
     return new JsonResponse($tmp);
 }
예제 #28
0
 /**
  * {@inheritdoc}
  */
 public function serialize(DocumentInterface $object)
 {
     $context = SerializationContext::create();
     if (!is_null($this->groupName)) {
         $context->setGroups(array($this->groupName));
         $context->setSerializeNull($this->serializeNull);
     }
     return $this->jmsSerializer->serialize($object, 'json', $context);
 }
예제 #29
0
 /**
  * @Route("/categories", name="json_categories")
  */
 public function jsonCategoriesAction()
 {
     $categoryManager = $this->container->get("youbookingbundle.category_manager");
     $categories = $categoryManager->findAllCategories();
     $categoriesJSON = $this->serializer->serialize($categories, "json", SerializationContext::create()->enableMaxDepthChecks());
     $response = new Response($categoriesJSON);
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 public function testShouldSkipPropertyReturnsFalseIfNoPredicateMatches()
 {
     $metadata = new StaticPropertyMetadata('stdClass', 'foo', 'bar');
     $context = SerializationContext::create();
     $strat = new DisjunctExclusionStrategy(array($first = $this->getMock('JMS\\Serializer\\Exclusion\\ExclusionStrategyInterface'), $last = $this->getMock('JMS\\Serializer\\Exclusion\\ExclusionStrategyInterface')));
     $first->expects($this->once())->method('shouldSkipProperty')->with($metadata, $context)->will($this->returnValue(false));
     $last->expects($this->once())->method('shouldSkipProperty')->with($metadata, $context)->will($this->returnValue(false));
     $this->assertFalse($strat->shouldSkipProperty($metadata, $context));
 }