예제 #1
0
파일: CsvHandler.php 프로젝트: sulu/sulu
 /**
  * Handles response for csv-request.
  *
  * @param ViewHandler $handler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  *
  * @throws ObjectNotSupportedException
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (!$view->getData() instanceof ListRepresentation) {
         throw new ObjectNotSupportedException($view);
     }
     $viewData = $view->getData();
     $data = new CallbackCollection($viewData->getData(), [$this, 'prepareData']);
     $fileName = sprintf('%s.csv', $viewData->getRel());
     $config = new ExporterConfig();
     $exporter = new Exporter($config);
     $data->rewind();
     if ($row = $data->current()) {
         $config->setColumnHeaders(array_keys($row));
     }
     $config->setDelimiter($this->convertValue($request->get('delimiter', ';'), self::$delimiterMap));
     $config->setNewline($this->convertValue($request->get('newLine', '\\n'), self::$newLineMap));
     $config->setEnclosure($request->get('enclosure', '"'));
     $config->setEscape($request->get('escape', '\\'));
     $response = new StreamedResponse();
     $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName, $fileName);
     $response->headers->set('Content-Type', 'text/csv');
     $response->headers->set('Content-Disposition', $disposition);
     $response->setCallback(function () use($data, $exporter) {
         $exporter->export('php://output', $data);
     });
     $response->send();
     return $response;
 }
 public function showAction(Request $request, $exception, DebugLoggerInterface $logger = null)
 {
     $view = new View();
     $view->setData(json_decode($exception->getMessage(), true));
     $view->setFormat('json');
     return $this->container->get('fos_rest.view_handler')->handle($view);
 }
예제 #3
0
 /**
  * FOSRest's ViewHandler has a private getStatusCode method. Because we cannot use it, we added
  * this lightweight method (without forms support) for Hal custom handler.
  *
  * @param View $view view instance
  * 
  * @return int HTTP status code
  */
 private function getStatusCode(View $view)
 {
     if (null !== ($code = $view->getStatusCode())) {
         return $code;
     }
     return Codes::HTTP_OK;
 }
 /**
  * Render js inclusion for create.js and dependencies and bootstrap code.
  *
  * THe hallo editor is bundled with create.js and available automatically.
  * To use aloha, you need to download the zip, as explained in step 8 of
  * the README.
  *
  * @param string $editor the name of the editor to load, currently hallo and aloha are supported
  */
 public function includeJSFilesAction($editor = 'hallo')
 {
     if ($this->securityContext && false === $this->securityContext->isGranted($this->requiredRole)) {
         return new Response('');
     }
     // We could inject a list of names to template mapping for this
     // to allow adding other editors without changing this bundle
     $view = new View();
     switch ($editor) {
         case 'hallo':
             if ($this->coffee) {
                 $view->setTemplate('SymfonyCmfCreateBundle::includecoffeefiles-hallo.html.twig');
             } else {
                 $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-hallo.html.twig');
             }
             break;
         case 'aloha':
             $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-aloha.html.twig');
             break;
         default:
             throw new \InvalidArgumentException("Unknown editor '{$editor}' requested");
     }
     $view->setData(array('cmfCreateStanbolUrl' => $this->stanbolUrl, 'cmfCreateImageUploadEnabled' => (bool) $this->imageClass));
     return $this->viewHandler->handle($view);
 }
예제 #5
0
 /**
  * @param $data array
  * @param format string, either rss or atom
  */
 protected function createFeed(View $view, Request $request)
 {
     $feed = new Feed();
     $data = $view->getData();
     $item = current($data);
     $annotationData = $this->reader->read($item);
     if ($item && ($feedData = $annotationData->getFeed())) {
         $class = get_class($item);
         $feed->setTitle($feedData->getName());
         $feed->setDescription($feedData->getDescription());
         $feed->setLink($this->urlGen->generateCollectionUrl($class));
         $feed->setFeedLink($this->urlGen->generateCollectionUrl($class, $request->getRequestFormat()), $request->getRequestFormat());
     } else {
         $feed->setTitle('Camdram feed');
         $feed->setDescription('Camdram feed');
     }
     $lastModified = null;
     $accessor = PropertyAccess::createPropertyAccessor();
     // Add one or more entries. Note that entries must be manually added once created.
     foreach ($data as $document) {
         $entry = $feed->createEntry();
         $entry->setTitle($accessor->getValue($document, $feedData->getTitleField()));
         $entry->setLink($this->urlGen->generateUrl($document));
         $entry->setDescription($this->twig->render($feedData->getTemplate(), array('entity' => $document)));
         if ($accessor->isReadable($document, $feedData->getUpdatedAtField())) {
             $entry->setDateModified($accessor->getValue($document, $feedData->getUpdatedAtField()));
         }
         $feed->addEntry($entry);
         if (!$lastModified || $entry->getDateModified() > $lastModified) {
             $lastModified = $entry->getDateModified();
         }
     }
     $feed->setDateModified($lastModified);
     return $feed->export($request->getRequestFormat());
 }
예제 #6
0
 /**
  * @param ViewHandler $viewHandler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  */
 public function handleExtension(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (in_array("application/vnd.bpi.api+xml", $request->getAcceptableContentTypes())) {
         $view->setHeader("Content-Type", "application/vnd.bpi.api+xml");
     }
     return $handler->createResponse($view, $request, "xml");
 }
예제 #7
0
 public function postAction()
 {
     $todos = $this->getDoctrine()->getRepository('AppBundle:Todo')->findAll();
     $view = new View();
     $view->setData($todos);
     return $this->handleView($view);
 }
 /**
  * @Route("/")
  */
 public function indexAction()
 {
     $view = new View();
     $view->setFormat('html');
     $view->setTemplate('TastdCoreBundle:Default:index.html.twig');
     return $view;
 }
 /**
  * Sign in users by pair username:password.
  *
  * @ApiDoc(
  *     views={"default", "user"},
  *     section="Security API",
  *     resource=true,
  *     resourceDescription="Sign in users by pair username:password.",
  *     statusCodes={
  *         200="Returned when successful",
  *         400="Returned when an error has occurred",
  *     }
  * )
  *
  * @Rest\Route("/sign-in", requirements={
  *     "_format": "json|xml"
  * })
  *
  * @Rest\RequestParam(name="username", requirements="[\w\-]+", nullable=false, description="Username")
  * @Rest\RequestParam(name="password", nullable=false, description="Password")
  *
  * @param ParamFetcherInterface $paramFetcher
  * @return View
  */
 public function postUserSignInAction(ParamFetcherInterface $paramFetcher)
 {
     $username = $paramFetcher->get('username');
     $password = $paramFetcher->get('password');
     /** @var EntityRepository $repository */
     $repository = $this->getDoctrine()->getManager()->getRepository('UserBundle:User');
     /** @var User $user */
     $user = $repository->findOneBy(['username' => $username]);
     if (!$user || !$this->validatePassword($user, $password)) {
         return new View(array('message' => 'User not found.'), 400);
     }
     if (!$user->isEnabled()) {
         return new View(array('message' => 'Account is disabled.'), 400);
     }
     if (!$user->isAccountNonLocked()) {
         return new View(array('message' => 'Account is locked.'), 400);
     }
     if (!$user->isAccountNonExpired()) {
         return new View(array('message' => 'Account is expired.'), 400);
     }
     if (!$user->isCredentialsNonExpired()) {
         return new View(array('message' => 'Credentials is expired.'), 400);
     }
     $this->generateToken($user);
     $this->getDoctrine()->getManager()->flush();
     $headers = array('Token' => $user->getApiToken(), 'ExpireAt' => $user->getApiTokenExpireAt()->format('c'), 'Username' => $user->getUsername());
     $view = new View(array_merge(array('user' => $user->getId()), $headers), 200, $headers);
     $this->setAuthInfoInCookie($headers, $view->getResponse(), $user->getApiTokenExpireAt());
     return $view;
 }
예제 #10
0
 public function handle(RequestConfiguration $requestConfiguration, View $view)
 {
     if ($view->getResponse()->getContent()) {
         return $view->getResponse();
     }
     return parent::handle($requestConfiguration, $view);
 }
예제 #11
0
 /**
  * @ApiDoc(
  *  section="Admin/Users",
  *  description="Display the creation form of the user",
  *  input="AppBundle\Controller\Admin\Form\UserFormType",
  *  output="AppBundle\Controller\Admin\AdminUserController",
  * )
  */
 public function newUserAction()
 {
     $user = new User();
     $form = $this->getUserForm($user, 'post_user', 'POST');
     $view = new View($form);
     $view->setTemplate('AppBundle:User:add.html.twig');
     return $this->handleView($view);
 }
 protected function createView($returnData)
 {
     $view = new View();
     $view->setData($returnData);
     $view->setStatusCode($returnData['status']);
     $view->setFormat('json');
     return $view;
 }
예제 #13
0
 /**
  * Converts the viewdata to a RSS feed. Modify to suit your datastructure.
  *
  * @return Response
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request)
 {
     if ($view->getData() instanceof Diary) {
         return new Response($this->createFeed($view->getData()), Response::HTTP_OK, $view->getHeaders());
     } else {
         return new Response('Unsupported entity type', Response::HTTP_BAD_REQUEST);
     }
 }
예제 #14
0
 public function getView($msg, $code)
 {
     $data1 = new Response($msg, $code);
     $view = new View($data1);
     $view->setTemplate('AppBundle:message.html.twig');
     $view->setTemplateVar('data');
     return $view;
 }
예제 #15
0
 /**
  * Информация о стране по 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);
 }
 /**
  * @dataProvider createResponseWithLocationDataProvider
  */
 public function testCreateResponseWithLocation($expected, $format, $forceRedirects)
 {
     $viewHandler = new ViewHandler(array('html' => true, 'json' => false, 'xml' => false), Codes::HTTP_BAD_REQUEST, $forceRedirects);
     $view = new View();
     $view->setLocation('foo');
     $returnedResponse = $viewHandler->createResponse($view, new Request(), $format);
     $this->assertEquals($expected, $returnedResponse->getStatusCode());
     $this->assertEquals('foo', $returnedResponse->headers->get('location'));
 }
예제 #17
0
 protected function renderResponse($contentTemplate, $params)
 {
     if ($this->viewHandler) {
         $view = new View($params);
         $view->setTemplate($contentTemplate);
         return $this->viewHandler->handle($view);
     }
     return $this->templating->renderResponse($contentTemplate, $params);
 }
예제 #18
0
 /**
  * @param ViewHandler $viewHandler
  * @param View $view
  * @param Request $request
  * @param string $format
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     $fosrestview = '<?xml version="1.0" encoding="ISO-8859-1"?>';
     $fosrestview .= '<rss version="2.0">';
     $fosrestview .= '<channel>';
     $fosrestview .= '<title>Get Afspraken</title>';
     $fosrestview .= '<language>en-us</language>';
     return new Response($fosrestview, 200, $view->getHeaders());
 }
예제 #19
0
 /**
  * Информация о юзере
  *
  * @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);
 }
예제 #20
0
 /**
  * alternatively use class="LiipHelloBundle:Article", but this has a bit more overhead
  *
  * @ParamConverter("article", class="Liip\HelloBundle\Document\Article")
  */
 public function converterAction(Article $article = null)
 {
     $view = new View();
     $view->setTemplate(new TemplateReference('LiipHelloBundle', 'Hello', 'index'));
     $name = $article ? 'found: ' . $article->getTitle() : 'No found';
     $view->setData(array('name' => $name));
     $viewHandler = $this->container->get('my_view');
     return $viewHandler->handle($view);
 }
예제 #21
0
 /**
  * @ApiDoc(
  *  section="Claims",
  *  description="Display the claimed requests of a user",
  *  output="AppBundle\Controller\ClaimController",
  *  parameters={
  *      {"name"="id", "dataType"="integer", "required"=true, "description"="The user's id"}
  *  }
  * )
  */
 public function getClaimedByUserAction($id)
 {
     $rep = $this->getDoctrine()->getRepository('AppBundle:Claim');
     $claims = $rep->findClaimedByUser($id);
     $view = new View($claims, 200);
     $view->setTemplate('AppBundle:Claim:claimed.html.twig');
     $view->setTemplateVar('claimeds');
     return $this->handleView($view);
 }
예제 #22
0
 /**
  * Список городов по стране
  *
  * @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);
 }
예제 #23
0
 /**
  * @ApiDoc(
  *  section="Categories",
  *  description="Display the creation form of categories",
  *  output="AppBundle\Controller\CategoryController",
  *  parameters={
  *      {"name"="cat", "dataType"="string", "required"=true, "description"="Category's name"},
  *  }
  * )
  */
 public function getCategoryItemsAction($cat)
 {
     $rep = $this->getDoctrine()->getRepository('AppBundle:Category');
     $category = $rep->findForItem($cat);
     $view = new View($category);
     $view->setTemplate('AppBundle:Category:items.html.twig');
     $view->setTemplateVar('items');
     //dump($view);die();
     return $this->handleView($view);
 }
 /**
  * @ApiDoc(
  *   resource = true,
  *   description = "Retrieves the health authority data for a postcode",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     400 = "Returned when there is a data error",
  *     404 = "Returned when no entities are found"
  *   }
  * )
  *
  * @param string $postcode
  * @return View
  */
 public function getAuthorityAction($postcode)
 {
     $result = $this->getService()->findByPostCode(strtolower(str_replace(' ', '', $postcode)));
     $view = new View();
     $view->setData($result);
     if (!count($result)) {
         $view->setStatusCode(404);
     }
     return $view;
 }
예제 #25
0
 /**
  * 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;
 }
예제 #26
0
 /**
  * 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;
 }
예제 #27
0
 /**
  * Lists all Article entities.
  *
  */
 public function indexAction()
 {
     //echo phpinfo(); die;
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('MwRestBundle:Article')->findAll();
     $view = new View();
     $view->setData($entities);
     $view->setTemplateVar('entities');
     $view->setTemplate('MwRestBundle:Article:index.html.twig');
     return $this->container->get('fos_rest.view_handler')->handle($view);
 }
예제 #28
0
 /**
  * {@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);
 }
예제 #29
0
 /**
  * @param ViewHandler $viewHandler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
 {
     $format = $request->get('_format') ?: 'json';
     if ($view->getData() instanceof ImageInterface && $format != 'json') {
         $image = $view->getData();
         $content = $this->manager->getImageSource($image);
         $headers = ['Content-Type' => $image->getMimeType()];
         return new Response($content, 200, $headers);
     }
     return $handler->createResponse($view, $request, 'json');
 }
예제 #30
0
 /**
  * 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;
 }