/** * @Route("/exportcsvpro", name="export_pro") */ public function exportProCSVAction() { $now = new \DateTime('now'); $em = $this->getDoctrine()->getManager(); $response = new StreamedResponse(); $response->setCallback(function () use($em) { $normalizer = new ObjectNormalizer(); $count = $em->getRepository('AppBundle:Client')->getCount(); $total = intval($count[1]); $header = array('NOM', 'PRENOM', 'EMAIL', 'SEXE'); $handle = fopen('php://output', 'r+'); fputcsv($handle, $header, ";"); $row = 1; while ($total >= 0) { $clients = $em->getRepository('AppBundle:Client')->findAllClients(($row - 1) * 2, 2); foreach ($clients as $key => $obj) { $clients[$key] = $normalizer->normalize($obj); } foreach ($clients as $client) { fputcsv($handle, $client, ";"); } $total = $total - 2; $row++; } fclose($handle); }); $response->headers->set('Content-Type', 'application/force-download'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); return $response; }
/** * 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; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $uri = $request->path(); $uri_arr = explode("/", $uri); if (in_array($uri, $this->noAuth)) { return $next($request); } else { if ($uri_arr[0] == "stream") { $res = $this->permissionForStream($request, $next, $uri_arr[2]); if ($res['status'] == "2") { header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $response = new StreamedResponse(); $response->setCallback(function () use($res) { $output = json_encode($res); echo "data:" . $output . "\n\n"; flush(); //sleep(1); }); $response->send(); exit; } else { return $next($request); } } else { $this->_init_($request); return $this->permissionToAccess($request, $next); } } }
/** * Genera el excel con la planilla de servicios * @param type $fechaDesde * @param type $fechaHasta * @return StreamedResponse */ public function generateExcel($fechaDesde, $fechaHasta) { $response = new StreamedResponse(); $response->setCallback(function () use($fechaDesde, $fechaHasta) { $fileType = 'Excel2007'; $fileName = 'template/informeEpidemiologico.xlsx'; //$objPHPExcel = new PHPExcel(); $objReader = PHPExcel_IOFactory::createReader($fileType); $objPHPExcel = $objReader->load($fileName); $objPHPExcel->getProperties()->setCreator("MAB")->setLastModifiedBy("MAB")->setTitle("Informe epidemiológico")->setSubject("Reporte epidemiológico")->setDescription("Informe epidemiológico")->setKeywords("reporte servicio epidemiológico")->setCategory("Reporte excel"); //Categoria // ponemos los datos generales del informe $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', $fechaDesde)->setCellValue('J3', $fechaHasta); $filaServicio = 3; $repository = $this->getDoctrine()->getEntityManager()->getRepository('AppBundle:Servicio'); $query = $repository->createQueryBuilder('s')->where('s.fecha >= :desde')->andwhere('s.fecha < :hasta')->setParameter('desde', $fechaDesde)->setParameter('hasta', $fechaHasta)->orderBy('s.fecha', 'ASC')->getQuery(); $servicios = $query->getResult(); foreach ($servicios as $servicio) { $this->rellenarServicio($objPHPExcel, $servicio, $filaServicio); } $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); if (ob_get_contents()) { ob_end_clean(); } $objWriter->save('php://output'); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/vnd.ms-excel'); $response->headers->set('Content-Disposition', 'attachment; filename="informeEpidemiologico.xlsx"'); return $response; }
public function testGetContent() { $response = new StreamedResponse(function () { echo 'foo'; }); $this->assertFalse($response->getContent()); }
public function exportAction(Request $request, Application $app) { $exportOptions = $app['exportOptions']['winners']; $exportOptionsKeys = array_keys($exportOptions['fields']); $exportOptionsValues = array_values($exportOptions['fields']); $response = new StreamedResponse(); $response->setCallback(function () use($app, $exportOptionsKeys, $exportOptionsValues) { $handle = fopen('php://output', 'w+'); fputcsv($handle, $exportOptionsKeys, ';'); $winners = $app['orm.em']->getRepository('Application\\Entity\\WinnerEntity')->findAll(); $twig = clone $app['twig']; $twig->setLoader(new \Twig_Loader_String()); foreach ($winners as $winner) { $finalExportOptionsValues = array(); foreach ($exportOptionsValues as $singleValue) { $finalExportOptionsValues[] = $twig->render($singleValue, array('winner' => $winner)); } fputcsv($handle, $finalExportOptionsValues, ';'); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="winners.csv"'); return $response; }
/** * Save uploaded image according to comur_image field configuration * * @param Request $request */ public function uploadImageAction(Request $request) { $config = json_decode($request->request->get('config'), true); $uploadUrl = $config['uploadConfig']['uploadUrl']; $uploadUrl = substr($uploadUrl, -strlen('/')) === '/' ? $uploadUrl : $uploadUrl . '/'; // We must use a streamed response because the UploadHandler echoes directly $response = new StreamedResponse(); $webDir = $config['uploadConfig']['webDir']; $webDir = substr($webDir, -strlen('/')) === '/' ? $webDir : $webDir . '/'; $filename = sha1(uniqid(mt_rand(), true)); $thumbsDir = $this->container->getParameter('comur_image.thumbs_dir'); $thumbSize = $this->container->getParameter('comur_image.media_lib_thumb_size'); $galleryDir = $this->container->getParameter('comur_image.gallery_dir'); $gThumbSize = $this->container->getParameter('comur_image.gallery_thumb_size'); $ext = $request->files->get('image_upload_file')->getClientOriginalExtension(); //('image_upload_file'); $completeName = $filename . '.' . $ext; $controller = $this; $handlerConfig = array('upload_dir' => $uploadUrl, 'param_name' => 'image_upload_file', 'file_name' => $filename, 'upload_url' => $config['uploadConfig']['webDir'], 'min_width' => $config['cropConfig']['minWidth'], 'min_height' => $config['cropConfig']['minHeight'], 'image_versions' => array('thumbnail' => array('upload_dir' => $uploadUrl . $thumbsDir . '/', 'upload_url' => $config['uploadConfig']['webDir'] . '/' . $thumbsDir . '/', 'crop' => true, 'max_width' => $thumbSize, 'max_height' => $thumbSize))); $transDomain = $this->container->getParameter('comur_image.translation_domain'); $errorMessages = array(1 => $this->get('translator')->trans('The uploaded file exceeds the upload_max_filesize directive in php.ini', array(), $transDomain), 2 => $this->get('translator')->trans('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', array(), $transDomain), 3 => $this->get('translator')->trans('The uploaded file was only partially uploaded', array(), $transDomain), 4 => $this->get('translator')->trans('No file was uploaded', array(), $transDomain), 6 => $this->get('translator')->trans('Missing a temporary folder', array(), $transDomain), 7 => $this->get('translator')->trans('Failed to write file to disk', array(), $transDomain), 8 => $this->get('translator')->trans('A PHP extension stopped the file upload', array(), $transDomain), 'post_max_size' => $this->get('translator')->trans('The uploaded file exceeds the post_max_size directive in php.ini', array(), $transDomain), 'max_file_size' => $this->get('translator')->trans('File is too big', array(), $transDomain), 'min_file_size' => $this->get('translator')->trans('File is too small', array(), $transDomain), 'accept_file_types' => $this->get('translator')->trans('Filetype not allowed', array(), $transDomain), 'max_number_of_files' => $this->get('translator')->trans('Maximum number of files exceeded', array(), $transDomain), 'max_width' => $this->get('translator')->trans('Image exceeds maximum width', array(), $transDomain), 'min_width' => $this->get('translator')->trans('Image requires a minimum width (%min%)', array('%min%' => $config['cropConfig']['minWidth']), $transDomain), 'max_height' => $this->get('translator')->trans('Image exceeds maximum height', array(), $transDomain), 'min_height' => $this->get('translator')->trans('Image requires a minimum height (%min%)', array('%min%' => $config['cropConfig']['minHeight']), $transDomain), 'abort' => $this->get('translator')->trans('File upload aborted', array(), $transDomain), 'image_resize' => $this->get('translator')->trans('Failed to resize image', array(), $transDomain)); $response->setCallback(function () use($handlerConfig, $errorMessages) { new UploadHandler($handlerConfig, true, $errorMessages); }); return $response->send(); }
/** * @Route("/orangegate/media/show/{id}/{format}", name="orangegate_media_show") * * @throws NotFoundHttpException * * @param string $id * @param string $format * * @return Response */ public function showAction($id, $format = 'reference') { $media = $this->getMedia($id); if (!$media) { throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id)); } $provider = $this->get($media->getProviderName()); if ($format == 'reference') { $file = $provider->getReferenceFile($media); } else { $file = $provider->getFilesystem()->get($provider->generatePrivateUrl($media, $format)); } $filePath = sprintf('%s/%s', $provider->getFilesystem()->getAdapter()->getDirectory(), $file->getKey()); if (!$file || !file_exists($filePath)) { throw new NotFoundHttpException(sprintf('file not exists : %s', $file->getKey())); } $response = new StreamedResponse(function () use($file) { echo $file->getContent(); }, Response::HTTP_OK, array('Content-Type' => $media->getContentType(), 'Content-Disposition' => sprintf('inline; filename="%s"', $media->getMetadataValue('filename')))); $response->setPrivate(); $response->headers->addCacheControlDirective('max-age', 0); $response->headers->addCacheControlDirective('no-cache', true); $response->headers->addCacheControlDirective('no-store', true); $response->headers->addCacheControlDirective('must-revalidate', true); return $response; }
/** * {@inheritdoc} */ public function call(ActionEvent $event, string $format) : Response { $controller = $event->getController(); $this->checkRole($controller); $request = $event->getRequest(); $id = $request->get('id'); if (is_numeric($id)) { if (!$controller->has('knp_snappy.pdf')) { throw new \Exception('Have you registered KnpSnappyBundle?'); } $snappy = $controller->get('knp_snappy.pdf'); $showAction = $controller->get('vardius_crud.action_show'); $html = $showAction->call($event, 'html')->getContent(); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $type = $request->get('type'); if ($type === 'pdf') { if (!$controller->has('knp_snappy.pdf')) { throw new \Exception('Have you registered KnpSnappyBundle?'); } $snappy = $controller->get('knp_snappy.pdf'); $listAction = $controller->get('vardius_crud.action_list'); $html = $listAction->call($event, 'html')->getContent(); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $source = $event->getDataProvider()->getSource(); if (!$source instanceof EntityRepository) { throw new \Exception('CSV export supports only ORM db driver'); } $queryBuilder = $source->createQueryBuilder('vardius_csv_export'); $crudEvent = new CrudEvent($source, $controller, $queryBuilder); $dispatcher = $controller->get('event_dispatcher'); $queryBuilder = $dispatcher->dispatch(CrudEvents::CRUD_EXPORT, $crudEvent)->getData(); $response = new StreamedResponse(); $response->setCallback(function () use($queryBuilder, $controller) { $handle = fopen('php://output', 'w+'); $headers = $controller->getHeaders(); if (!empty($headers)) { fputcsv($handle, $headers, ';'); } $entityManager = $controller->get('doctrine.orm.entity_manager'); $results = $queryBuilder->getQuery()->iterate(); while (false !== ($row = $results->next())) { $element = $controller->getRow($row[0]); $entityManager->detach($row[0]); if (count($element)) { fputcsv($handle, $element); } } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); } } return $response; }
/** * Export the workbook. * * @param null|string $filename * * @throws \Exception * @return mixed|void */ public function stream($filename = null) { $filename = $this->getFilename($filename); $output = $this->getExportable()->getDriver()->getOutputFromHtml($this->convertToHtml($this->getExportable())); $response = new StreamedResponse(function () use($output) { echo $output; }, 200, ['Content-Type' => 'application/pdf', 'Content-Disposition' => 'inline; filename="' . $filename . '.' . $this->getExtension() . '"']); return $response->send(); }
/** * Set the stream response content. * @param StreamedResponse $response The response object. * @return StreamedResponse */ public function setContent(StreamedResponse $response) { $stream = $this->cache->readStream($this->path); $response->setCallback(function () use($stream) { rewind($stream); fpassthru($stream); fclose($stream); }); return $response; }
/** * Create a streamed response containing a file * * @return \Symfony\Component\HttpFoundation\StreamedResponse */ protected function createStreamedResponse() { $filename = $this->createFilename(); $response = new StreamedResponse(); $attachment = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename); $response->headers->set('Content-Type', $this->getContentType()); $response->headers->set('Content-Disposition', $attachment); $response->setCallback($this->quickExportCallback()); return $response; }
/** * @Route( * "/image/{node}", * name="claro_image" * ) */ public function fileAction(ResourceNode $node) { $image = $this->get('claroline.manager.resource_manager')->getResourceFromNode($node); $response = new StreamedResponse(); $path = $this->container->getParameter('claroline.param.files_directory') . DIRECTORY_SEPARATOR . $image->getHashName(); $response->setCallBack(function () use($path) { readfile($path); }); $response->headers->set('Content-Type', $node->getMimeType()); return $response->send(); }
public function downloadMatchAction() { $object = $this->admin->getSubject(); $matchId = $object->getId(); if (!$object) { throw new NotFoundHttpException(sprintf('Unable to find the object with id : %s', $matchId)); } // On récupère le service qui va envoyer le match $response = new StreamedResponse(function () use($matchId) { //$downloadMatching = $this->container->get('public_user.exportCsv')->fromMatching($matchId); $container = $this->container; $em = $container->get('doctrine')->getManager(); $conn = $em->getConnection(); // On crée la limite du nombre de donnée recuperés par requetes $lim = 10000; // On recupere les 10000 premiers resultat $query = "SELECT SQL_CALC_FOUND_ROWS md5 FROM matching_details WHERE id_matching = :id LIMIT :lim"; $sth = $conn->prepare($query); $sth->bindValue(':id', $matchId); $sth->bindValue(':lim', (int) $lim, \PDO::PARAM_INT); $sth->execute(); $results = $sth->fetchAll(); // On ouvre le fichier sur lequel on va ecrire $handle = fopen('php://output', 'r') or die("Couldn't get handle"); // On ajout au fichier les données recuperé precedement foreach ($results as $row) { fputcsv($handle, $row); } // On recupere le nombre de ligne total $sth = $conn->prepare('SELECT FOUND_ROWS()'); $sth->execute(array($matchId)); $resultLine = $sth->fetchAll(); // On recupere le nombre de ligne total $nb_line = intval($resultLine[0]["FOUND_ROWS()"]); // Si le nombrte de ligne max est superieurs aux nombres de lignes recuperé precedement if ($nb_line >= $lim) { // on retire du nombre de ligne le nombre d'elements recuperé precedement $lineDone = $lim; $offset = $lim; $this->getData($conn, $matchId, $handle, $nb_line, $lineDone, $lim, $offset); } else { fclose($handle); } }); $response->setStatusCode(200); $response->headers->set('Pragma', 'public'); $response->headers->set('Expires', '0'); $response->headers->set('Content-Disposition', 'attachment; filename="Export_matching_' . $matchId . '.csv"'); $response->headers->set('Cache-Control', 'must-revalidate; post-check=0; pre-check=0'); $response->headers->set('Cache-Control', 'private', false); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Transfer-Encoding', 'binary'); return $response; }
/** * @see StreamingEngineInterface::stream */ public function stream($view, array $parameters = [], StreamedResponse $response = null) { $callback = function () use($view, $parameters) { $this->templating->stream($view, $parameters); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; }
/** * CSV出力の共通処理 * @param Application $app * @param Request $request * @param string $type CSV出力形式の種類 * @return StreamedResponse */ public function export(Application $app, Request $request, $type) { // タイムアウトを無効にする. set_time_limit(0); $response = new StreamedResponse(); $response->setCallback(function () use($app, $request, $type) { $app['listing_ad_csv.service.listingad.data.creator']->create($app, $request, $type); }); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename=' . $this->createFileName($type)); $response->send(); return $response; }
/** * Returns the picture identified by the given id in a streamedResponse * * @route("/picture/{id}/stream", name="colibri_gallery_picture_stream", options={"expose"=true}) * @param string $id * @return StreamedResponse */ public function streamedPictureAction($id) { $mongo = $this->get('doctrine_mongodb')->getManager(); $picture = $mongo->getRepository('ColibriGalleryBundle:Picture')->find($id); /** @var \Colibri\GalleryBundle\Document\Picture $picture */ $response = new StreamedResponse(); $response->headers->add(array('Content-Type' => $picture->getMimeType())); $response->headers->add(array('Content-Disposition' => 'attachment; filename=' . $picture->getFilename())); $response->setCallback(function () use($picture) { echo $picture->getFile()->getBytes(); }); return $response; }
/** * @param string $template * @param array $arguments * @param StreamedResponse $response * @return StreamedResponse */ public function stream($template, $arguments = array(), StreamedResponse $response = null) { $this->ensureTemplatingEngineIsPresent(); $templating = $this->templatingEngine; $callback = function () use($templating, $template, $arguments) { $templating->stream($template, $arguments); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; }
/** * @EXT\Route( * "resource/media/{node}", * name="claro_file_get_media", * options={"expose"=true} * ) * * @param integer $id * * @return Response */ public function streamMediaAction(ResourceNode $node) { $collection = new ResourceCollection(array($node)); $this->checkAccess('OPEN', $collection); $file = $this->get('claroline.manager.resource_manager')->getResourceFromNode($node); $path = $this->container->getParameter('claroline.param.files_directory') . DIRECTORY_SEPARATOR . $file->getHashName(); $response = new StreamedResponse(); $response->setCallBack(function () use($path) { readfile($path); }); $response->headers->set('Content-Type', $node->getMimeType()); $response->send(); return new Response(); }
/** * {@inheritdoc} */ public function call(ActionEvent $event) { $controller = $event->getController(); $this->checkRole($controller); $repository = $event->getDataProvider()->getSource(); $request = $event->getRequest(); $dispatcher = $controller->get('event_dispatcher'); $snappy = $controller->get('knp_snappy.pdf'); $responseHandler = $this->getResponseHandler($controller); $crudEvent = new CrudEvent($repository, $controller); $dispatcher->dispatch(CrudEvents::CRUD_EXPORT, $crudEvent); $this->id = $request->get('id'); $options['template'] = !empty($this->options['template'] ?: (is_numeric($this->id) ? 'show' : 'list')); if (is_numeric($this->id)) { $dataProvider = $event->getDataProvider(); $html = $responseHandler->getHtml($event->getView(), $this->getTemplate(), ['data' => $dataProvider->get($this->id), 'ui' => false]); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $listView = $event->getListView(); $listDataEvent = new ListDataEvent($repository, $request); $type = $request->get('type'); if ($type === 'pdf') { $html = $responseHandler->getHtml($event->getView(), $this->getTemplate(), ['list' => $listView->render($listDataEvent), 'title' => $listView->getTitle(), 'ui' => false]); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $response = new StreamedResponse(); $listView->setPagination(false); $queryBuilder = $listView->getData($listDataEvent, true, true); $response->setCallback(function () use($queryBuilder, $controller) { $handle = fopen('php://output', 'w+'); $headers = $controller->getHeaders(); if (!empty($headers)) { fputcsv($handle, $headers, ';'); } $entityManager = $controller->get('doctrine.orm.entity_manager'); $results = $queryBuilder->getQuery()->iterate(); while (false !== ($row = $results->next())) { $element = $controller->getRow($row[0]); $entityManager->detach($row[0]); fputcsv($handle, $element); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); } } return $response; }
/** * @EXT\Route( * "/download/{pdf}", * name="claro_pdf_download", * options={"expose"=true} * ) * @EXT\ParamConverter( * "pdf", * class="ClarolinePdfGeneratorBundle:Pdf", * options={"mapping": {"pdf": "guid"}} * ) * * @param array $nodes * @param bool $forceArchive * * @return \Symfony\Component\HttpFoundation\Response */ public function download(Pdf $pdf) { $response = new StreamedResponse(); $file = $this->pdfManager->getFile($pdf); $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=' . urlencode($pdf->getName() . '.pdf')); $response->headers->set('Content-Type', 'application/pdf'); $response->headers->set('Connection', 'close'); $response->send(); }
/** * Server-Sent event stream handling * */ public function syncPresentation() { Log::info('setting: ' . env('PRESENTATION_ENABLE_SYNC', 'false')); if (!env('PRESENTATION_ENABLE_SYNC', 'false')) { return; } // define the new SSE stream $response = new StreamedResponse(); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('Cache-Control', 'no-cache'); $response->headers->set("X-Accel-Buffering", "no"); $response->setCallback(function () { // get current data $newMP = $this->getNewestMainPresenter(); $newPos = $this->getNewestShowPosition(); // (nearly) endless loop to keep stream open // the client will automatically reconnect when we close the stream after a while. // this is ti avoid memory leaks and hangs on the server side! $count = 0; while (true) { // if we have a new show position, send it out if ($newPos) { echo "event: syncPresentation\n"; echo "id: " . $count++ . "\n"; echo "data: " . json_encode($newPos) . "\n\n"; ob_flush(); flush(); } // if we have a new MP, send it out if ($newMP) { echo "event: newMainPresenter\n"; echo "id: " . $count++ . "\n"; echo "data: " . json_encode($newMP) . "\n\n"; ob_flush(); flush(); } sleep(2); // get latest data (will be empty if there was no change) $newMP = $this->getNewestMainPresenter(); $newPos = $this->getNewestShowPosition(); // close the stream after some time if (++$count > 100) { break; } } }); return $response; }
/** * @param StreamedResponse $response * @param Process $process */ private function searchDiffSetCallBack(StreamedResponse $response, Process $process) { $response->setCallback(function () use($process) { $server = new RecolnatServer(); $progress = 0; $server->step->send(\json_encode(['name' => 'general', 'progress' => $progress])); $process->run(function ($type, $buffer) use($server, &$progress) { $step = 100 / count(DiffManager::ENTITIES_NAME); if (Process::ERR === $type) { $server->error->send($buffer); } else { $data = \json_decode($buffer); // Cas ou des retours sont reçus simultanément if (is_null($data)) { $validJson = '[' . str_replace('}' . PHP_EOL . '{', '},{', $buffer) . ']'; $arrayJson = \json_decode($validJson); foreach ($arrayJson as $value) { $server->step->send(\json_encode($value)); } } else { $server->step->send($buffer); } if (isset($data->progress) && $data->progress == 100) { $progress += $step; } $server->step->send(\json_encode(['name' => 'general', 'progress' => $progress])); } }); $server->step->send(\json_encode(['name' => 'general', 'progress' => 100])); $server->stop->send(\json_encode(['name' => 'general', 'progress' => 100])); }); }
/** * {@inheritdoc} */ public function renderFile(CRUDEntity $entity, $entityName, $field) { $targetPath = $this->getPath($entityName, $entity, $field); $fileName = $entity->get($field); $file = $targetPath . '/' . $fileName; $response = new Response(''); $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $file); finfo_close($finfo); $size = filesize($file); if ($fileName && file_exists($file)) { $response = new StreamedResponse(CRUDStreamedFileResponse::getStreamedFileFunction($file), 200, array('Content-Type' => $mimeType, 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', 'Content-length' => $size)); $response->send(); } return $response; }
/** * Returns a streamed response. */ public function generate() { if (null == $this->name) { throw new \Exception("You must set a name to the file downloaded with setName() method before generate file."); } $filename = $this->name; $data = $this->data; $columns = $this->columns; $response = new StreamedResponse(); $response->setCallback(function () use($columns, $data) { $handle = fopen('php://output', 'w+'); // add csv header columns fputcsv($handle, $columns, ';'); // add data in the csv foreach ($data as $row) { $values = array(); foreach (array_values($row) as $value) { $values[] = $this->toString($value); } fputcsv($handle, $values, ';'); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Type', 'application/force-download'); $response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '.csv"'); return $response; }
/** * Export all plugins * * @return Response Exportation file */ public function exportAction() { /** * @var Plugin $plugin */ $plugin = $this->get('elcodi.manager.plugin')->getPlugin('Elcodi\\Plugin\\ProductCsvBundle'); if (!$plugin->isUsable()) { $this->createNotFoundException($this->get('translator')->trans('product_csv_plugin.error.is_disabled')); } /** * @var ProductExporter $exporter */ $exporter = $this->get('elcodi_plugin.product_csv.exporter'); $repository = $this->get('elcodi.repository.product'); $response = StreamedResponse::create(); $response->setCallback(function () use($repository, $exporter) { $rows = $repository->findAll(); $exporter->export($rows); }); $configuration = $plugin->getConfiguration(); $filename = $configuration['export_filename']; if (empty($filename)) { $filename = 'products.csv'; } return $this->makeDownloadable($response, $filename, 'text/csv'); }
/** * @param AssetInterface $asset * @param AssetWriter $writer * @param array $cachePath * @param array $headers */ public function __construct(AssetInterface $asset, AssetWriter $writer, $cachePath, array $headers = []) { $file = $asset->getTargetPath(); $cachePath = $cachePath . '/' . $file; $cached = false; $cacheTime = time(); if (is_file($cachePath)) { $mTime = $asset->getLastModified(); $cacheTime = filemtime($cachePath); if ($mTime > $cacheTime) { @unlink($cachePath); $cacheTime = $mTime; } else { $cached = true; } } if (!$cached) { $writer->writeAsset($asset); } $stream = function () use($cachePath) { readfile($cachePath); }; $headers['Content-Length'] = filesize($cachePath); if (preg_match('/.+\\.([a-zA-Z0-9]+)/', $file, $matches)) { $ext = $matches[1]; if (isset($this->mimeTypes[$ext])) { $headers['Content-Type'] = $this->mimeTypes[$ext]; } } parent::__construct($stream, 200, $headers); $date = new \DateTime(); $date->setTimestamp($cacheTime); $this->setLastModified($date); }
/** * @param string $content * @param string $filename * * @return \Symfony\Component\HttpFoundation\Response */ private function fileDownload($content, $filename) { if ($content instanceof StreamInterface) { $response = new StreamedResponse(); $response->setCallback(function () use($content) { $content->rewind(); while (!$content->eof()) { echo $content->read(8192); } }); } else { $response = new Response($content); } $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename); $response->headers->set('Content-Disposition', $disposition); return $response; }
/** * Constructor. * * @param array|\Traversable $rows * @param string $filename * * @throws \InvalidArgumentException */ public function __construct($rows, $filename) { if (!is_array($rows) && !$rows instanceof \Traversable) { throw new \InvalidArgumentException('$rows should be an array or an instance of \\Traversable.'); } $this->rows = $rows; parent::__construct(array($this, 'output'), 200, array('Content-Type' => 'text/csv', 'Content-disposition' => 'attachment; filename=' . $filename)); }
/** * Exporting a CSV file using an entity manager * The entity manager have to provide a getCsvExport function. * * @param string $service */ public function exportCsvAction($service, $option) { $manager = $this->get($service); if (!is_callable(array($manager, 'getCsvExport'))) { throw new \Exception('The service used for CSV export have to provide an export function'); } $response = new StreamedResponse(); list($content, $filename) = empty($option) ? $manager->getCsvExport() : $manager->getCsvExport($option); $response->setCallback(function () use($content) { $handle = fopen('php://output', 'w+'); fwrite($handle, ""); // adds BOM utf8 fox Excel foreach ($content as $index => $row) { if ($index == 0) { fputcsv($handle, array_keys($row), ';'); } $csvRow = array(); foreach ($row as $attribute) { if ($attribute instanceof \Datetime) { $csvRow[] = $attribute->format('Y-m-d'); } else { if (is_object($attribute)) { if (is_callable(array($attribute, '__toString'))) { $csvRow[] = $attribute; } else { if (is_callable(array($attribute, 'getId'))) { $csvRow[] = $attribute->getId(); } else { $csvRow[] = '#error'; } } } else { $csvRow[] = $attribute; } } } fputcsv($handle, $csvRow, ';'); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/force-download'); //$response->headers->set('') $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '.csv"'); return $response; }