本文整理汇总了PHP中FOS\RestBundle\View\View::getSerializationContext方法的典型用法代码示例。如果您正苦于以下问题:PHP View::getSerializationContext方法的具体用法?PHP View::getSerializationContext怎么用?PHP View::getSerializationContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FOS\RestBundle\View\View
的用法示例。
在下文中一共展示了View::getSerializationContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: handle
/**
* {@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);
}
示例2: getNoteAction
/**
* 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;
}
示例3: getImageAction
/**
* 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;
}
示例4: onKernelView
/**
* 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);
}
示例5: getServerAction
/**
* 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;
}
示例6: getTerrainAction
/**
* 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;
}
示例7: createResponse
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;
}
示例8: testCreateResponseWithFormErrorsAndSerializationGroups
/**
* @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());
}
示例9: onKernelView
/**
* 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);
}
示例10: handleView
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);
}
示例11: testCreateResponseWithFormErrorsAndSerializationGroups
/**
* @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());
}
示例12: testCreateResponseWithFormErrorsAndSerializationGroups
/**
* @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());
}
示例13: serializationGroupsMatches
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;
}
示例14: getSerializationContext
/**
* 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;
}
示例15: getSerializationContext
/**
* 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;
}