本文整理汇总了PHP中JMS\Serializer\SerializationContext::create方法的典型用法代码示例。如果您正苦于以下问题:PHP SerializationContext::create方法的具体用法?PHP SerializationContext::create怎么用?PHP SerializationContext::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JMS\Serializer\SerializationContext
的用法示例。
在下文中一共展示了SerializationContext::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: jmsSerialization
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: createResponse
/**
* @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: convertContext
/**
* @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;
}
示例4: serializeAction
/**
* 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: rpcAction
/**
* 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;
}
示例6: handleResponse
/**
* 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;
}
示例7: getContext
/**
* @return SerializationContext
*/
protected function getContext()
{
if ($this->context === null) {
$this->context = SerializationContext::create();
}
return $this->context;
}
示例8: toArray
protected function toArray($oObject)
{
$oSerializer = SerializerBuilder::create()->build();
$aArray = $oSerializer->toArray($oObject, SerializationContext::create()->enableMaxDepthChecks());
$this->_aArray = $aArray;
return $this;
}
示例9: idsAction
/**
* 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);
}
示例10: getAction
/**
* @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'))));
}
示例11: testUninitializedContextIsWorking
/**
* @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);
}
示例12: getNotificationparameterAction
/**
* [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: getFinalResultByJMSGroup
/**
* Exclusion strategy by JMS group name
*
* @author Huong Le <tonyle.microsoft@gmail.com>
*
* @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: simpleSearchAction
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: searchAction
/**
* 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);
}