本文整理汇总了PHP中FOS\RestBundle\View\View::setSerializationContext方法的典型用法代码示例。如果您正苦于以下问题:PHP View::setSerializationContext方法的具体用法?PHP View::setSerializationContext怎么用?PHP View::setSerializationContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FOS\RestBundle\View\View
的用法示例。
在下文中一共展示了View::setSerializationContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getCountryAction
/**
* Информация о стране по 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);
}
示例2: getUserAction
/**
* Информация о юзере
*
* @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);
}
示例3: getCitiesByCountryAction
/**
* Список городов по стране
*
* @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);
}
示例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: serializerAction
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);
}
示例6: getUserAction
/**
* @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);
}
示例7: cgetAction
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);
}
示例8: putWithdrawalAction
/**
* вывести деньги
*
* @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);
}
示例9: handleView
protected function handleView(View $view)
{
$serializeGroups = $this->get('request')->get('serialize', null);
if (is_null($serializeGroups) === false && strlen($serializeGroups) > 0) {
$view->setSerializationContext(SerializationContext::create()->setGroups(array($serializeGroups)));
}
return parent::handleView($view);
}
示例10: setGrouping
/**
* @param string $grouping
*/
protected function setGrouping($grouping)
{
if (false === empty($grouping)) {
$this->view->setSerializationContext(SerializationContext::create()->setGroups(array($grouping)));
}
}
示例11: 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);
}
示例12: putCampaignsAction
/**
* Создать новую кампанию
*
* @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);
}
示例13: setSerializationContext
/**
* Set serialization groups and exclusion strategies
*
* @param \FOS\RestBundle\View\View $view
*
* @return void
*/
protected function setSerializationContext(&$view)
{
$context = SerializationContext::create();
if (!empty($this->serializerGroups)) {
$context->setGroups($this->serializerGroups);
}
//Only include FormEntity properties for the top level entity and not the associated entities
$context->addExclusionStrategy(new PublishDetailsExclusionStrategy());
//include null values
$context->setSerializeNull(true);
$view->setSerializationContext($context);
}
示例14: doExecute
/**
* @param Response $response
* @param ParameterBag $parameterBag
* @return bool|void
*/
protected function doExecute(Response $response, ParameterBag $parameterBag)
{
/** @var Request $request */
/** @var AbstractType $formType */
/** @var object $entity */
/** @var bool $cleanForm */
/** @var bool $cleanRequestData */
/** @var bool $getContent */
/** @var array $formOptions */
/** @var SerializationContext $serializationContext */
/** @var \Closure $onPreValidation */
/** @var \Closure $onPostValidation */
/** @var \Closure $onPostPersist */
/** @var \Closure $onSuccess */
/** @var \Closure $onFailure */
$request = $parameterBag->get('request');
$formType = $parameterBag->get('formType');
$entity = $parameterBag->get('entity');
$cleanForm = $parameterBag->get('cleanForm');
$cleanRequestData = $parameterBag->get('cleanRequestData', true);
$getContent = $parameterBag->get('getContent');
$formOptions = $parameterBag->get('formOptions', array());
$serializationContext = $parameterBag->get('serializationContext');
$onPreValidation = $parameterBag->get('onPreValidation');
$onPostValidation = $parameterBag->get('onPostValidation');
$onPostPersist = $parameterBag->get('onPostPersist');
$onSuccess = $parameterBag->get('onSuccess');
$onFailure = $parameterBag->get('onFailure ');
$view = new View();
$httpResponse = $view->getResponse();
$requestData = array_merge($request->request->all(), $request->files->all());
if ($serializationContext) {
$view->setSerializationContext($serializationContext);
}
$form = $this->getFormFactory()->createNamed(null, get_class($formType), $entity, array_merge(array('csrf_protection' => false), $formOptions));
if ($cleanRequestData) {
$requestData = $this->cleanRequestData($requestData, $form);
}
if ($cleanForm) {
$this->cleanForm($requestData, $form);
}
$this->prepareFormCollections($request, $form);
/**
* Pre validation
*/
$this->onPreValidation($request, $form, $entity, $httpResponse);
if ($onPreValidation instanceof \Closure) {
$onPreValidation($request, $form, $entity, $httpResponse);
}
if ($httpResponse->getStatusCode() != HttpResponse::HTTP_OK) {
$response->response = $view;
return true;
}
$form->submit($requestData);
if ($form->isValid()) {
if ($onPostValidation instanceof \Closure) {
$onPostValidation($request, $form, $entity, $httpResponse);
if ($httpResponse->getStatusCode() != HttpResponse::HTTP_OK) {
$response->response = $view;
return true;
}
}
$isEditAction = $entity->getId();
$statusCode = $isEditAction ? HttpResponse::HTTP_OK : HttpResponse::HTTP_CREATED;
/** @var \Doctrine\Common\Persistence\ObjectManager $em */
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
if ($onPostPersist instanceof \Closure) {
$onPostPersist($request, $form, $entity, $httpResponse);
}
$em->flush();
$httpResponse->setStatusCode($statusCode);
if ($isEditAction) {
if ($getContent) {
$em->refresh($entity);
$view->setData($entity);
}
} else {
$view->setData($entity->getId());
}
if ($onSuccess instanceof \Closure) {
$onSuccess($request, $form, $entity, $httpResponse);
}
$response->response = $view;
return true;
}
if ($onFailure instanceof \Closure) {
$onFailure($request, $form, $entity, $httpResponse);
$response->response = $view;
return true;
}
$response->response = $form;
return false;
}
示例15: getWalletsAction
/**
* Все кошельки юзера
*
* @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);
}