/** * Информация о стране по 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); }
/** * Информация о юзере * * @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); }
/** * Список городов по стране * * @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); }
/** * 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); }
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); }
/** * @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); }
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); }
/** * вывести деньги * * @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); }
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); }
/** * @param string $grouping */ protected function setGrouping($grouping) { if (false === empty($grouping)) { $this->view->setSerializationContext(SerializationContext::create()->setGroups(array($grouping))); } }
/** * 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); }
/** * Создать новую кампанию * * @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); }
/** * 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); }
/** * @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; }
/** * Все кошельки юзера * * @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); }
/** * Постраничный список кампаний по площадке. * В сериализованные кампании также добавляется ключ banned = true|false * * @param Platform $platform * @param ParamFetcher $paramFetcher * * @Rest\Get("platforms/{id}/campaigns", requirements={"id"="\d+"}) * @ParamConverter("platform", class="VifeedPlatformBundle:Platform") * @ApiDoc( * section="Platform API", * requirements={ * {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="id площадки"} * }, * output={ * "class"="Vifeed\CampaignBundle\Entity\Campaign", * "groups"={"default"} * }, * statusCodes={ * 200="Returned when successful", * 403="Returned when the user is not authorized to use this method", * 404="Returned when platform not found" * } * ) * * @Rest\QueryParam(name="page", requirements="\d+", default="1", description="page") * @Rest\QueryParam(name="per_page", requirements="\d+", default="10", description="campaigns per page") * @Rest\QueryParam(array=true, name="countries", requirements="\d+", description="country ids") * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * * @return Response */ public function getPlatformCampaignsAction(Platform $platform, ParamFetcher $paramFetcher) { if ($this->getUser()->getType() != User::TYPE_PUBLISHER) { throw new AccessDeniedHttpException(); } if ($platform->getUser() != $this->getUser()) { throw new AccessDeniedHttpException(); } $campaignRepo = $this->em->getRepository('VifeedCampaignBundle:Campaign'); $banRepo = $this->em->getRepository('VifeedPlatformBundle:CampaignBan'); $page = $paramFetcher->get('page'); $perPage = $paramFetcher->get('per_page'); $countries = $paramFetcher->get('countries'); $params = ['status' => Campaign::STATUS_ON, 'countries' => $countries, 'order' => [['bid', 'desc'], ['generalBudget', 'desc']]]; $campaignsPaginator = new PaginationHelper($campaignRepo->getCampaignsByParamsQuery($params), $perPage, $page); $campaigns = $campaignsPaginator->getItemsArray(); $bans = $banRepo->findBannedCampaignsByPlatfrom($platform); $context = new SerializationContext(); $context->setGroups(['default'])->setAttribute('banned_campaigns', $bans); $view = new View($campaigns); $view->setSerializationContext($context); $response = $this->handleView($view); $routeParams = ['id' => $platform->getId(), 'per_page' => $perPage]; $header = $campaignsPaginator->getLinkHeader($this->get('router'), 'api_get_platform_campaigns', $routeParams); $response->headers->add($header); return $response; }