/**
  * @param Request $request
  * @param $id
  * @return View
  */
 public function liquidacion(Request $request, $id)
 {
     /** @var ServicioOperativo $servicio */
     $servicio = $this->get($id);
     if (!$servicio) {
         throw new NotFoundHttpException("No existe el servicio '{$id}'");
     }
     $liquidacion = new Liquidacion();
     $olds = array();
     if ($servicio) {
         foreach ($servicio->getLiquidaciones() as $l) {
             $olds[$l->getId()] = $l;
         }
     }
     $form = $this->getFormfactory()->create(new LiquidacionType(), $liquidacion);
     $form->submit($request->request->all());
     if ($form->isValid()) {
         /** @var EntregaOperacion $entregaOperativo */
         /** @var EntregaOperacion $l */
         foreach ($liquidacion->getLiquidaciones() as $entregaOperativo) {
             if (isset($olds[$entregaOperativo->getId()])) {
                 $l = $olds[$entregaOperativo->getId()];
                 $l->setCantidad($entregaOperativo->getCantidad());
                 $this->getEm()->persist($l);
             } else {
                 $this->getEm()->persist($entregaOperativo);
             }
         }
         $this->getEm()->flush();
         return View::create()->setStatusCode(Codes::HTTP_NO_CONTENT);
     }
     return View::create($form)->setStatusCode(Codes::HTTP_BAD_REQUEST);
 }
Example #2
0
 /**
  * @param Request $request
  * @return View
  */
 public function postUserConsentAction(Request $request)
 {
     $practoAccountId = $this->authenticate(true);
     $userManager = $this->get('consult.user_manager');
     $userConsent = $userManager->setConsultEnabled($practoAccountId);
     return View::create(array("consent" => $userConsent));
 }
 /**
  * Change user password
  *
  * @View(serializerEnableMaxDepthChecks=true)
  *
  * @Put("/profile/change-password", name="_change_password_profile")
  *
  * @param Request $request
  * @param $entity
  *
  * @return Response
  */
 public function putAction(Request $request)
 {
     $request->request->set('current_password', $request->request->get('currentPassword'));
     $entity = $this->getUser();
     if (!is_object($entity) || !$entity instanceof UserInterface) {
         throw new AccessDeniedException('This user does not have access to this section.');
     }
     /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
     $dispatcher = $this->get('event_dispatcher');
     $event = new GetResponseUserEvent($entity, $request);
     $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_INITIALIZE, $event);
     if (null !== $event->getResponse()) {
         return $event->getResponse();
     }
     $changePasswordType = $this->get('app.change_password.form.type');
     try {
         $request->setMethod('PATCH');
         //Treat all PUTs as PATCH
         $form = $this->createForm($changePasswordType, $entity, array('method' => $request->getMethod(), 'validation_groups' => array('ChangePassword', 'Default')));
         $this->removeExtraFields($request, $form);
         $form->handleRequest($request);
         if ($form->isValid()) {
             /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
             $userManager = $this->get('fos_user.user_manager');
             $userManager->updateUser($entity);
             return $entity;
         }
         return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
     } catch (\Exception $e) {
         return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
     }
 }
Example #4
0
 public function postDarshansAction()
 {
     $postData = $this->getRequest()->request->all();
     $darshanManager = $this->get('abhay_api.darshan_manager');
     $darshan = $darshanManager->add($postData);
     return View::create($darshan->serialise(), Codes::HTTP_CREATED);
 }
 private function _processForm(User $user)
 {
     $statusCode = $user->isNew() ? 201 : 204;
     $form = $this->createForm(new UserType(), $user);
     $form->handleRequest($this->getRequest());
     if ($form->isValid()) {
         $factory = $this->get('security.encoder_factory');
         /** @var ObjectManager $em */
         $em = $this->getDoctrine()->getManager();
         /** @var PasswordEncoderInterface $encoder */
         $encoder = $factory->getEncoder($user);
         $data = $form->getData();
         try {
             $user->createNewAccount($encoder, $em, $data->getEmail(), $data->getPassword());
             $response = new Response();
             $response->setStatusCode($statusCode);
             // set the `Location` header only when creating new resources
             if (201 === $statusCode) {
                 $response->headers->set('Location', $this->generateUrl('api_user_get', array('id' => $user->getId()), true));
             }
             return $response;
         } catch (\PDOException $e) {
             $form->addError(new FormError("Same user already exists!"));
         }
     }
     return View::create($form, 400);
 }
 /**
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function searchJsonAction(Request $request)
 {
     $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
     $keyword = $request->get('keyword');
     $results = $this->get('dos.repository.tag')->search($keyword) ?: array();
     return $this->viewHandler->handle($configuration, View::create($results));
 }
 public function indexAction()
 {
     $view = View::create();
     $view->setData(array('date' => date('r'), 'name' => 'some name'));
     $view->setTemplate('APIUserBundle:Default:index.html.twig')->setTemplateData(array('name' => 'some name'));
     return $view;
 }
 public function indexAction(Request $request)
 {
     $view = View::create();
     $data = ['test' => 'test'];
     $view->setData($data)->setTemplateData(['testtemplate' => 'testtemplate']);
     return $view;
 }
Example #9
0
 /**
  * Creates a new Blog - need admin previlage
  *
  * @param ParamFetcher $paramFetcher Paramfetcher
  *
  * @RequestParam(name="title", requirements=".*", default="", description="Title.")
  * @RequestParam(name="blog", requirements=".*",  default="", description="Text.")
  * @RequestParam(name="tags",  requirements=".*", default="", description="tags - comma seperated.")
  *
  * @return FOSView
  * @Secure(roles="ROLE_ADMIN")
  * @ApiDoc()
  */
 public function postBlogsAction(ParamFetcher $paramFetcher)
 {
     $blog = new Blog();
     $form = $this->createFormBuilder($blog, array('csrf_protection' => false))->add('title')->add('blog')->add('tags')->getForm();
     //$form   = $this->createForm(new BlogType(), $blog);
     if (trim($paramFetcher->get('title')) == '') {
         throw new HttpException(400, 'Enter title.');
     }
     if (trim($paramFetcher->get('blog')) == '') {
         throw new HttpException(400, 'Enter blog.');
     }
     if (trim($paramFetcher->get('tags')) == '') {
         throw new HttpException(400, 'Enter tags.');
     }
     if ($this->getRequest()->getMethod() == 'POST') {
         $form->bindRequest($this->getRequest());
         $blog->setBlog($paramFetcher->get('blog'));
         $blog->setTags($paramFetcher->get('tags'));
         $blog->setTitle($paramFetcher->get('title'));
         $blog->setAuthor($this->get('security.context')->getToken()->getUser());
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getEntityManager();
             $em->persist($blog);
             $em->flush();
         } else {
             return FOSView::create($this->getErrorMessages($form), 400);
         }
     }
     return FOSView::create($blog, 200);
 }
Example #10
0
 /**
  * @Pdf(
  *    stylesheet="SisesApplicationBundle:PDF\PDF:planilla_style.pdf.twig",
  *    enableCache=true,
  *    headers={"Content-Type":"application/pdf", "Content-Disposition"="attachment"}
  * )
  *
  * @param $id
  * @param $date
  *
  * @return array
  */
 public function planillaAction($id, $date = null)
 {
     $ea = $this->getEm()->getRepository('SisesApplicationBundle:Entrega\\EntregaAsignacion')->find($id);
     if ($ea) {
         $asignacion = $ea->getAsignacion();
         $personas = $this->getEm()->getRepository('SisesApplicationBundle:Beneficio')->getPersonasDeAsignacion($asignacion);
         if ($date) {
             try {
                 $date = new \DateTime($date . '-1');
             } catch (\Exception $e) {
                 throw new NotFoundHttpException("Fecha no disponible");
             }
         } else {
             $date = new \DateTime();
         }
         $start = new \DateTime($date->format('1-m-Y'));
         $end = new \DateTime($date->format('t-m-Y'));
         $days = array();
         while ($start <= $end) {
             $days[] = $start->format('d');
             $start->add(new \DateInterval('P1D'));
         }
         return View::create(array('contrato' => $asignacion->getServicio()->getContrato(), 'lugar' => $asignacion->getLugar()->getNombre(), 'ubicacion' => $asignacion->getLugar()->getUbicacion()->getNombreDetallado(), 'servicio' => $asignacion->getServicio()->getNombre(), 'per_page' => 25, 'date' => $date, 'days' => $days, 'personas' => $personas))->setTemplate('SisesApplicationBundle:PDF\\PDF:planilla.pdf.twig');
     }
     throw new NotFoundHttpException("Entrega asignacion no encontrada");
 }
Example #11
0
 /**
  * Processes the form and build the Response object
  *
  * @param Request $request
  * @param Organization $organization
  * @return Response|static
  * @throws BadRequestHttpException
  */
 public function processForm(Request $request, Organization $organization)
 {
     $statusCode = !$this->em->contains($organization) ? 201 : 204;
     $form = $this->container->get('form.factory')->create(OrganizationType::class, $organization);
     $formData = json_decode($request->getContent(), true);
     $form->submit($this->prepareFormData($formData));
     if (!$form->isValid()) {
         return View::create($form, 400);
     }
     if (!$this->em->contains($organization)) {
         $this->em->persist($organization);
     }
     try {
         $this->em->flush();
     } catch (\Exception $e) {
         $pdoException = $e->getPrevious();
         // unique constraint
         if ($pdoException->getCode() === '23000') {
             throw new BadRequestHttpException('Error 23000!');
         }
         throw new BadRequestHttpException('Unknown error code: ' . $pdoException->getCode());
     }
     $response = new Response();
     $response->setStatusCode($statusCode);
     if (201 === $statusCode) {
         $response->headers->set('Access-Control-Expose-Headers', 'Location');
         $response->headers->set('Location', $this->container->get('router')->generate('api_v1_get_organization', ['organization' => $organization->getId()], UrlGeneratorInterface::RELATIVE_PATH));
     }
     return $response;
 }
Example #12
0
 /**
  * responseDenied
  *
  * Crea y devuelve una respuesta de denegación de la API.
  * Si no se proporcionan parámetros, el estado HTTP y el mensaje de error tendrán valores por defecto.
  *
  * @param string $message
  * @param int $httpStatusCode
  * @return Response
  */
 public function responseDenied($message = "", $httpStatusCode = Response::HTTP_NOT_FOUND)
 {
     $response['state'] = $this::STATE_ERROR;
     $response['msg'] = $this->translator->trans($message);
     $view = View::create()->setStatusCode($httpStatusCode)->setData($response);
     return $this->viewhandler->handle($view);
 }
 /**
  * Converts an Exception to a Response.
  *
  * @param FlattenException     $exception   A FlattenException instance
  * @param DebugLoggerInterface $logger      A DebugLoggerInterface instance
  * @param string               $format      The format to use for rendering (html, xml, ...)
  * @param integer              $code        An HTTP response code
  * @param string               $message     An HTTP response status message
  * @param array                $headers     HTTP response headers
  *
  * @return Response                         Response instance
  */
 public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
 {
     $format = $this->getFormat($request, $format);
     if (null === $format) {
         $message = 'No matching accepted Response format could be determined, while handling: ';
         $message .= $this->getExceptionMessage($exception);
         return new Response($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
     }
     // the count variable avoids an infinite loop on
     // some Windows configurations where ob_get_level()
     // never reaches 0
     $count = 100;
     $currentContent = '';
     while (ob_get_level() && --$count) {
         $currentContent .= ob_get_clean();
     }
     $code = $this->getStatusCode($exception);
     $viewHandler = $this->container->get('fos_rest.view_handler');
     $parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
     try {
         $view = View::create($parameters, $code, $exception->getHeaders());
         $view->setFormat($format);
         if ($viewHandler->isFormatTemplating($format)) {
             $view->setTemplate($this->findTemplate($format, $code));
         }
         $response = $viewHandler->handle($view);
     } catch (\Exception $e) {
         $message = 'An Exception was thrown while handling: ';
         $message .= $this->getExceptionMessage($exception);
         $response = new Response($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
     }
     return $response;
 }
 /**
  * Converts an Exception to a Response.
  *
  * @param Request                                    $request
  * @param HttpFlattenException|DebugFlattenException $exception
  * @param DebugLoggerInterface                       $logger
  * @param string                                     $format
  *
  * @return Response
  *
  * @throws \InvalidArgumentException
  */
 public function showAction(Request $request, $exception, DebugLoggerInterface $logger = null, $format = 'html')
 {
     /**
      * Add support for ApiExceptionInterface
      */
     if (!$exception instanceof DebugFlattenException && !$exception instanceof HttpFlattenException && !$exception instanceof ApiExceptionInterface) {
         throw new \InvalidArgumentException(sprintf('ExceptionController::showAction can only accept some exceptions (%s, %s), "%s" given', 'Symfony\\Component\\HttpKernel\\Exception\\FlattenException', 'Symfony\\Component\\Debug\\Exception\\FlattenException', get_class($exception)));
     }
     $format = $this->getFormat($request, $format);
     if (null === $format) {
         $message = 'No matching accepted Response format could be determined, while handling: ';
         $message .= $this->getExceptionMessage($exception);
         return new Response($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
     }
     $currentContent = $this->getAndCleanOutputBuffering();
     $code = $this->getStatusCode($exception);
     $viewHandler = $this->container->get('fos_rest.view_handler');
     $parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
     try {
         if (!$viewHandler->isFormatTemplating($format)) {
             $parameters = $this->createExceptionWrapper($parameters);
         }
         $view = View::create($parameters, $code, $exception->getHeaders());
         $view->setFormat($format);
         if ($viewHandler->isFormatTemplating($format)) {
             $view->setTemplate($this->findTemplate($request, $format, $code, $this->container->get('kernel')->isDebug()));
         }
         $response = $viewHandler->handle($view);
     } catch (\Exception $e) {
         $message = 'An Exception was thrown while handling: ';
         $message .= $this->getExceptionMessage($exception);
         $response = new Response($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
     }
     return $response;
 }
 /**
  * Converts an Exception to a Response.
  *
  * @param Request              $request
  * @param FlattenException     $exception
  * @param DebugLoggerInterface $logger
  *
  * @throws \InvalidArgumentException
  *
  * @return Response
  */
 public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
 {
     $format = $this->getFormat($request, $request->getRequestFormat());
     if (null === $format) {
         $message = 'No matching accepted Response format could be determined, while handling: ';
         $message .= $this->getExceptionMessage($exception);
         return new Response($message, Response::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
     }
     $currentContent = $this->getAndCleanOutputBuffering();
     $code = $this->getStatusCode($exception);
     $viewHandler = $this->container->get('fos_rest.view_handler');
     $parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
     $showException = $request->attributes->get('showException', $this->container->get('kernel')->isDebug());
     try {
         if (!$viewHandler->isFormatTemplating($format)) {
             $parameters = $this->createExceptionWrapper($parameters);
         }
         $view = View::create($parameters, $code, $exception->getHeaders());
         $view->setFormat($format);
         if ($viewHandler->isFormatTemplating($format)) {
             $view->setTemplate($this->findTemplate($request, $format, $code, $showException));
         }
         $response = $viewHandler->handle($view);
     } catch (\Exception $e) {
         $message = 'An Exception was thrown while handling: ';
         $message .= $this->getExceptionMessage($exception);
         $response = new Response($message, Response::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
     }
     return $response;
 }
Example #16
0
 public function postAshramsAction()
 {
     $postData = $this->getRequest()->request->all();
     $ashramManager = $this->get('abhay_api.ashram_manager');
     $ashram = $ashramManager->add($postData);
     return View::create($ashram->serialise(), Codes::HTTP_CREATED);
 }
 /**
  * Get a publicly visible article by slug, for the current locale.
  *
  * @param Request $request
  * @param $slug
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function showFrontAction(Request $request, $slug)
 {
     // Get current locale
     $locale = $this->get('sylius.context.locale')->getCurrentLocale();
     // Get request configuration
     $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
     /** @var ArticleRepositoryInterface $repository */
     $repository = $this->repository;
     // Get a publicly visible article by translated slug
     $article = $repository->findPublicBySlug($slug, $locale);
     if (!$article) {
         throw $this->createNotFoundException();
     }
     // Get categories for listing
     $categories = $this->get('webburza.repository.article_category')->findBy(['published' => true]);
     // Get related articles
     $relatedArticles = $this->get('webburza.repository.article')->getRelatedArticles($article, $locale, 3);
     // Create the view
     $view = View::create();
     // Set template and data
     $view->setTemplate('WebburzaSyliusArticleBundle:Frontend/Article:show.html.twig');
     $view->setData(array('article' => $article, 'categories' => $categories, 'related_articles' => $relatedArticles));
     // Handle view
     return $this->viewHandler->handle($configuration, $view);
 }
Example #18
0
 public function postBabasAction()
 {
     $postData = $this->getRequest()->request->all();
     $babaManager = $this->get('abhay_api.baba_manager');
     $baba = $babaManager->add($postData);
     return View::create($baba->serialise(), Codes::HTTP_CREATED);
 }
Example #19
0
 public function viewAction(Request $request, $type, $nodeId)
 {
     $em = $this->getDoctrine();
     $node = $em->getRepository($type)->findOneBy(['id' => $nodeId, 'deletedOn' => null]);
     if (!$node instanceof $type) {
         throw $this->createNotFoundException("Entity '{$nodeId}' not found for type '{$type}'");
     }
     $adminPool = $this->get('sonata.admin.pool');
     $entityClass = get_class($node);
     $admin = $adminPool->getAdminByClass($entityClass);
     $format = $request->attributes->get('_format', 'html');
     if ($format === 'html') {
         $displayHandlerManager = $this->get('gravity_cms.display_manager');
         $handler = $displayHandlerManager->getHandlerForEntity($node);
         if ($handler->supportsRequest($request)) {
             $config = $displayHandlerManager->getEntityConfig($entityClass);
             return $this->render($handler->getTemplate($config['options']), $handler->getTemplateOptions($node, $config['options']) + ['admin' => $admin]);
         } else {
             throw new \RuntimeException('Unknown Request Format');
         }
     } else {
         $fieldManager = $this->get('gravity_cms.field_manager');
         $view = View::create($node);
         $context = $view->getSerializationContext();
         $exclusionStrategyChain = new DisjunctExclusionStrategy([new GroupsExclusionStrategy(['gravity_api_read']), new VersionExclusionStrategy('1.0')]);
         $context->addExclusionStrategy(new NodeExclusionStrategy($fieldManager, $exclusionStrategyChain));
         $context->setSerializeNull(true);
         return $this->get('fos_rest.view_handler')->handle($view, $request);
     }
 }
Example #20
0
 /**
  * @Route("/category", name="api_category_list")
  * @Template()
  */
 public function getCategoryListAction()
 {
     $categoryItems = $this->fetchCategoryItems();
     $formattedCategoryItems = $this->container->get('protalk_api.helper.category_list')->buildArray($categoryItems);
     $view = View::create(array('media' => $formattedCategoryItems))->setStatusCode(200)->setEngine('twig')->setTemplate('ProtalkApiBundle:Error:noHtml.html.twig')->setTemplateVar('media')->setData($formattedCategoryItems);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
 /**
  * Register
  *
  * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
  *
  * @Post(path="/register", name="_registration")
  *
  * @param Request $request
  *
  * @return Response
  */
 public function registerAction(Request $request)
 {
     $registrationType = $this->get('app.registration.form.type');
     /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
     $userManager = $this->get('fos_user.user_manager');
     /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
     $dispatcher = $this->get('event_dispatcher');
     $entity = $userManager->createUser();
     $entity->setEnabled(true);
     $event = new GetResponseUserEvent($entity, $request);
     $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
     if (null !== $event->getResponse()) {
         return $event->getResponse();
     }
     try {
         $form = $this->createForm($registrationType, $entity, array('method' => $request->getMethod(), 'validation_groups' => array('Registration', 'Default')));
         $this->removeExtraFields($request, $form);
         $form->handleRequest($request);
         if ($form->isValid()) {
             $event = new FormEvent($form, $request);
             $dispatcher->dispatch(AppEvents::REGISTRATION_SUCCESS, $event);
             $userManager->updateUser($entity);
             if (null === ($response = $event->getResponse())) {
                 $url = $this->generateUrl('confirmed_registration');
                 $response = array('url' => $url);
             }
             //$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
             return $entity;
         }
         return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
     } catch (\Exception $e) {
         return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
     }
 }
Example #22
0
 public function getUserByNameAction($query)
 {
     $users = $this->getDoctrine()->getManager()->createQuery('SELECT u from TSKUserBundle:User u LEFT JOIN u.contact c WHERE c.firstName LIKE :query OR c.lastName LIKE :query OR u.username LIKE :query')->setParameter('query', '%' . $query . '%')->getResult();
     $tskusers = new TSKUserCollection($users);
     $view = View::create()->setStatusCode(200)->setData($tskusers);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
 private function processForm(Request $request, BadgeCollection $collection, $method = 'PUT')
 {
     $form = $this->createForm($this->get('icap_badge.form.badge.collection'), $collection, array('method' => $method));
     $formParameters = $request->request->get($form->getName());
     // Patch for boolean value, parameters are only string and always true for boolean value
     if (isset($formParameters['is_shared'])) {
         if ('0' === $formParameters['is_shared']) {
             $formParameters['is_shared'] = false;
         }
     }
     $form->submit($formParameters, 'PATCH' !== $method);
     if ($form->isValid()) {
         if (!$collection->isIsShared()) {
             $collection->setSlug(null);
         }
         $entityManager = $this->getDoctrine()->getManager();
         $entityManager->persist($collection);
         $entityManager->flush();
         $view = View::create();
         $view->setStatusCode(201);
         $data = array('collection' => array('id' => $collection->getId(), 'name' => $collection->getName(), 'is_shared' => $collection->isIsShared(), 'slug' => $this->generateUrl('icap_badge_badge_collection_share_view', array('slug' => $collection->getSlug()))));
         $view->setData($data);
         return $this->get('fos_rest.view_handler')->handle($view);
     }
     $view = View::create($form, 400);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
Example #24
0
 public function getPessoasAction()
 {
     $em = $this->get('doctrine')->getEntityManager();
     $contacts = $em->getRepository('SicoobSiccadBundle:Pessoa')->findAll();
     $data = array('success' => true, 'data' => $contacts, 'message' => '');
     $view = View::create()->setStatusCode(200)->setData($data);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
 /**
  * Handle view.
  *
  * @param int        $statusCode
  * @param mixed|null $data
  *
  * @return View
  */
 protected function handleView($statusCode = 200, $data = null)
 {
     $view = View::create()->setStatusCode($statusCode);
     if ($data) {
         $view->setData($data);
     }
     return $this->getViewHandler()->handle($view);
 }
Example #26
0
 /**
  * Id is autogenerated make PUT update only
  * @param $id
  * @return \Symfony\Component\HttpFoundation\Response
  * @ApiDoc()
  */
 public function putLeagueAction($id)
 {
     $league = $this->getDoctrine()->getManager()->getRepository('DraftBundle:League')->find($id);
     if (empty($league)) {
         return $this->handleView(View::create(null, 404));
     }
     return $this->processForm($league, false);
 }
 /**
  * @Post("")
  * @ApiDoc(
  *     section="Topics",
  *     input="AppBundle\Form\TopicForm"
  * )
  *
  * @param Request $request
  * @return View
  */
 public function postAction(Request $request)
 {
     $handler = $this->get('un.topic_handler');
     /** @var Topic $topic */
     $topic = $handler->post($request->request->all());
     $data = ['resource_id' => $topic->getId(), '_link' => $this->route($topic)];
     return View::create($data, Response::HTTP_CREATED);
 }
Example #28
0
 public static function message($textAlert = '', $typeAlert = 'success', $codeStatus = 200, $data = null)
 {
     $message = array('textAlert' => $textAlert, 'typeAlert' => $typeAlert);
     if ($codeStatus >= 400) {
         return View::create(array_merge($message, is_array($data) ? $data : array()), $codeStatus);
     }
     return View::create(array('data' => array_merge($message, is_array($data) ? $data : array())), $codeStatus);
 }
 /**
  * @Route("/media/{slug}", name="api_media_detail")
  * @Template()
  */
 public function getMediaDetailAction($slug)
 {
     $mediaRepository = $this->getDoctrine()->getRepository('ProtalkMediaBundle:Media');
     $mediaItem = $mediaRepository->findOneBySlug($slug, Query::HYDRATE_ARRAY);
     $formattedMediaItem = $this->container->get('protalk_api.helper.media_detail')->buildArray(new \RecursiveArrayIterator($mediaItem));
     $view = View::create(array('media' => $formattedMediaItem))->setStatusCode(200)->setEngine('twig')->setTemplate('ProtalkApiBundle:Error:noHtml.html.twig')->setTemplateVar('media')->setData($formattedMediaItem);
     return $this->get('fos_rest.view_handler')->handle($view);
 }
 /**
  * @Post("")
  * @ApiDoc(
  *     section="Modules",
  *     input="AppBundle\Form\ModuleForm"
  * )
  *
  * @param Request $request
  * @return View
  */
 public function postAction(Request $request)
 {
     $handler = $this->get('un.module_handler');
     /** @var Module $module */
     $module = $handler->post($request->request->all());
     $data = ['resource_id' => $module->getId(), '_link' => $this->route($module)];
     return View::create($data, Response::HTTP_CREATED);
 }