/** * 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; }
/** * 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); } }
/** * @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'); }
/** * Deserialize Hal object using Nocarrier's Hal library instead of using JMS Serializer * * @param ViewHandler $viewHandler * @param View $view * @param Request $request * @param string $format * * @return Response */ public function createResponse(ViewHandler $handler, View $view, Request $request, $format) { $hal = $view->getData(); //if not hal object process it with default view handler if (!$hal instanceof Hal) { return $handler->createResponse($view, $request, $format); } switch ($format) { case 'json': $content = $hal->asJson(); break; case 'xml': $content = $hal->asXml(); break; default: throw new HttpException(500, 'Custom HalViewHandler is misconfigured. Formats for deserializing HAL objects should be json or xml.'); } $response = $view->getResponse(); $response->setContent($content); $response->setStatusCode($this->getStatusCode($view)); if (!$response->headers->has('Content-Type')) { $response->headers->set('Content-Type', $request->getMimeType($format)); } return $response; }
/** * @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()); }
/** * Converts the viewdata to a RSS feed. Modify to suit your datastructure. * * @return Response */ public function createResponse(ViewHandler $handler, View $view, Request $request) { try { $content = $this->createFeed($view->getData()); $code = Response::HTTP_OK; } catch (\Exception $e) { if ($this->logger) { $this->logger->error($e); } $content = sprintf('%s:<br/><pre>%s</pre>', $e->getMessage(), $e->getTraceAsString()); $code = Response::HTTP_BAD_REQUEST; } return new Response($content, $code, $view->getHeaders()); }
/** * @param ViewHandler $handler * @param View $view * @param Request $request * * @return \Symfony\Component\HttpFoundation\Response */ public function createResponse(ViewHandler $handler, View $view, Request $request) { $format = $view->getFormat() ?: $request->getRequestFormat(); $data = $view->getData(); if ($data instanceof Cursor) { $view->setData(iterator_to_array($data, false)); $view->getResponse()->headers->set('X-Total-Count', $data->count()); return $handler->createResponse($view, $request, $view->getFormat()); } if ($data instanceof Form && Codes::HTTP_BAD_REQUEST === $view->getStatusCode()) { $view->setData($this->formatFormErrors($data)); return $handler->createResponse($view, $request, $format); } return $handler->createResponse($view, $request, $format); }
/** * @param ViewHandler $viewHandler * @param View $view * @param Request $request * @param string $format * * @return Response */ public function handle(ViewHandler $viewHandler, View $view, Request $request, $format) { $included = $this->buildIncludedArray(explode(',', $request->query->get('included', ''))); $data = $view->getData(); if (is_array($data) || $data instanceof \Traversable) { $document = new CollectionDocument(); foreach ($data as $resourceData) { $document->addData($this->buildResourceObject($document, $resourceData, $included)); } } else { $document = new ResourceDocument(); $document->setData($this->buildResourceObject($document, $data, $included)); } $response = new Response($this->serializer->serialize($document, 'json'), 200, array('Content-Type' => 'application/vnd.api+json')); return $response; }
public function createRedirectResponse(View $view, $location, $format) { if ($format == 'html' && $view->getData() != null && ($view->getStatusCode() == Codes::HTTP_CREATED || $view->getStatusCode() == Codes::HTTP_ACCEPTED)) { $prevStatus = $view->getStatusCode(); $view->setStatusCode(Codes::HTTP_OK); } $response = parent::createRedirectResponse($view, $location, $format); if ($response->headers->has('Location') && $response->getStatusCode() !== Codes::HTTP_CREATED && ($response->getStatusCode() < 300 || $response->getStatusCode() >= 400)) { $response->headers->remove('Location'); } if (isset($prevStatus)) { $view->setStatusCode($prevStatus); $code = isset($this->forceRedirects[$format]) ? $this->forceRedirects[$format] : $this->getStatusCode($view, $response->getContent()); $response->setStatusCode($code); } return $response; }
/** * 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(); $view = $event->getControllerResult(); if (!$view instanceof View) { if (!$request->attributes->get('_view') && !$this->container->getParameter('fos_rest.view_response_listener.force_view')) { return; } $view = new View($view); } if (null === $view->getFormat()) { $view->setFormat($request->getRequestFormat()); } $vars = $request->attributes->get('_template_vars'); if (!$vars) { $vars = $request->attributes->get('_template_default_vars'); } if (!empty($vars)) { $parameters = $view->getData(); if (null !== $parameters && !is_array($parameters)) { throw new \RuntimeException('View data must be an array if using a templating aware format.'); } $parameters = (array) $parameters; foreach ($vars as $var) { if (!array_key_exists($var, $parameters)) { $parameters[$var] = $request->attributes->get($var); } } $view->setData($parameters); } $viewHandler = $this->container->get('fos_rest.view_handler'); if ($viewHandler->isFormatTemplating($view->getFormat())) { $template = $request->attributes->get('_template'); if ($template) { if ($template instanceof TemplateReference) { $template->set('format', null); $template->set('engine', null); } $view->setTemplate($template); } } $response = $viewHandler->handle($view, $request); $event->setResponse($response); }
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; }
/** * @dataProvider setDataDataProvider */ public function testSetData($data) { $view = new View(); $view->setData($data); $this->assertEquals($data, $view->getData()); }
/** * Returns the form from the given view if present, false otherwise. * * @param View $view * * @return bool|FormInterface */ protected function getFormFromView(View $view) { $data = $view->getData(); if ($data instanceof FormInterface) { return $data; } if (is_array($data) && isset($data['form']) && $data['form'] instanceof FormInterface) { return $data['form']; } return false; }
/** * @param View $view */ private function unwrapViewData(View $view) { $view->setData($this->unwrapIfCollaborator($view->getData())); }
/** * @return bool */ public function isEntityEmpty() { return null === $this->view->getData() || $this->view->getStatusCode() != self::STATUS_OK && $this->view->getStatusCode() != self::STATUS_OK; }
/** * Handles creation of a Response using either redirection or the templating/serializer service * * @param View $view * @param Request $request * @param string $format * * @return Response */ public function createResponse(View $view, Request $request, $format) { $route = $view->getRoute(); $location = $route ? $this->getRouter()->generate($route, (array) $view->getData(), true) : $view->getLocation(); if ($location) { return $this->createRedirectResponse($view, $location, $format); } $content = null; if ($this->isFormatTemplating($format)) { $content = $this->renderTemplate($view, $format); } elseif ($this->serializeNull || null !== $view->getData()) { $serializer = $this->getSerializer($view); if ($serializer instanceof Serializer) { $context = $this->getSerializationContext($view); $content = $serializer->serialize($view->getData(), $format, $context); } else { $content = $serializer->serialize($view->getData(), $format); } } $response = $view->getResponse(); $response->setStatusCode($this->getStatusCode($view, $content)); if (null !== $content) { $response->setContent($content); } if (!$response->headers->has('Content-Type')) { $response->headers->set('Content-Type', $request->getMimeType($format)); } return $response; }
/** * Handles creation of a Response using either redirection or the templating/serializer service * * @param View $view * @param Request $request * @param string $format * * @return Response */ public function createResponse(View $view, Request $request, $format) { $headers = $view->getHeaders(); if (empty($headers['Content-Type'])) { $view->setHeader('Content-Type', $request->getMimeType($format)); } $route = $view->getRoute(); $location = $route ? $this->getRouter()->generate($route, (array) $view->getData(), true) : $view->getLocation(); if ($location) { return $this->createRedirectResponse($view, $location, $format); } if ($this->isFormatTemplating($format)) { $content = $this->renderTemplate($view, $format); } else { $serializer = $this->getSerializer($view); $content = $serializer->serialize($view->getData(), $format); } return new Response($content, $this->getStatusCode($view), $view->getHeaders()); }
private function dataMatches(View $subject, $argument) { if (isset($argument['data'])) { return $subject->getData() === $argument['data']; } return true; }