本文整理汇总了PHP中Symfony\Component\HttpFoundation\StreamedResponse::setStatusCode方法的典型用法代码示例。如果您正苦于以下问题:PHP StreamedResponse::setStatusCode方法的具体用法?PHP StreamedResponse::setStatusCode怎么用?PHP StreamedResponse::setStatusCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\StreamedResponse
的用法示例。
在下文中一共展示了StreamedResponse::setStatusCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: exportAction
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;
}
示例2: generateExcel
/**
* 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;
}
示例3: call
/**
* {@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;
}
示例4: downloadMatchAction
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;
}
示例5: error
protected function error($error = null, $code = 200)
{
$this->builder->createPartial('body', 'error')->getParamManager()->setParams(['error' => $error === null ? _i('We encountered an unexpected error.') : $error]);
$this->response->setStatusCode($code);
if ($this->response instanceof StreamedResponse) {
$this->response->setCallback(function () {
$this->builder->stream();
});
} else {
$this->response->setContent($this->builder->build());
}
return $this->response;
}
示例6: call
/**
* {@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;
}
示例7: exportCsvAction
/**
* 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;
}
示例8: userDataAction
public function userDataAction(Request $request)
{
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException();
}
$userType = $request->query->get('usertype');
if (!in_array($userType, array('pupils', 'mentors', 'all'))) {
return null;
}
$status = $request->query->get('status');
if (!in_array($status, array('enabled', 'disabled', 'all'))) {
return null;
}
// Get user data
$users = $this->retrieveUserData($userType, $status);
// Output in a requested format
// CSV
if ($request->query->get('type') === 'csv') {
if ($userType === 'all') {
return new HttpException(400, "Only mentors' or pupils' export can be requested, but not both.");
}
$response = new StreamedResponse();
$response->setCallback(function () use($userType, $users) {
$this->outputCsvCallback($userType, $users);
});
$filename = $userType . date('-Ymd-Hi') . '.csv';
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
return $response;
} else {
if ($request->query->get('type') === 'email') {
$formatUser = function ($user) {
return $user->getFirstName() . ' ' . $user->getLastName() . ' <' . $user->getEmail() . '>';
};
$respStrs = array_map($formatUser, $users);
$response = new Response(implode(",\n", $respStrs));
return $response;
}
}
return null;
}
示例9: doCSVExportAction
/**
* @param Request $request
* @return StreamedResponse
*
* @Route("/csv/do", name="cto_export_csvdo")
*/
public function doCSVExportAction(Request $request)
{
$exportDTO = new ExportFilterDTO();
$form = $this->createForm(ExportFilterDTOType::class, $exportDTO);
$form->handleRequest($request);
$response = new StreamedResponse();
$carJobRepository = $this->getDoctrine()->getManager()->getRepository("CTOAppBundle:CarJob");
$response->setCallback(function () use($carJobRepository, $exportDTO) {
$handle = fopen('php://output', 'w+');
fputcsv($handle, ['Date', 'Day of week', 'Category', 'Description', 'Client', 'Master', 'Salary'], ';');
$result = $carJobRepository->getDataForExportToCSV($exportDTO);
foreach ($result as $item) {
fputcsv($handle, [$item['jdate']->format("d.m.Y"), $item['jdate']->format("l"), $item['catName'], $item['description'], $item['clientName'], $item['masterFName'] . ' ' . $item['masterLName'], $item['price']], ';');
}
fclose($handle);
});
$now = Carbon::now()->format("d.m.Y");
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename=' . "export_for_{$now}.csv");
return $response;
}
示例10: generate
/**
* 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;
}
示例11: generateStatisticsGeneral
/**
* Genera el excel con las estatisticas de traslados
* @param type $fechaDesde
* @param type $fechaHasta
* @return StreamedResponse
*/
public function generateStatisticsGeneral($fechaDesde, $fechaHasta)
{
$response = new StreamedResponse();
$response->setCallback(function () use($fechaDesde, $fechaHasta) {
$fileType = 'Excel2007';
$fileName = 'template/informeEstadisticoGeneral.xlsx';
//$objPHPExcel = new PHPExcel();
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
$objPHPExcel->getProperties()->setCreator("MAB")->setLastModifiedBy("MAB")->setTitle("Informe estadístico ")->setSubject("Reporte estadístico general")->setDescription("Informe estadistico general")->setKeywords("reporte servicio general")->setCategory("Reporte excel");
//Categoria
// ponemos los datos generales del informe
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', $fechaDesde)->setCellValue('I3', $fechaHasta);
$emConfig = $this->getDoctrine()->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\\Query\\Mysql\\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\\Query\\Mysql\\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\\Query\\Mysql\\Day');
$this->rellenarEstadisticasGenerales($objPHPExcel, $fechaDesde, $fechaHasta);
$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="informeEstadisticoDespachos.xlsx"');
return $response;
}
示例12: generateCsvFromVouchers
/**
* @param int $idPool
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function generateCsvFromVouchers($idPool)
{
$generatedVouchers = $this->getQueryContainer()->queryVouchersByIdVoucherPool($idPool)->find();
$streamedResponse = new StreamedResponse();
$streamedResponse->setCallback(function () use($generatedVouchers) {
$csvHandle = fopen('php://output', 'w+');
fputcsv($csvHandle, ['Voucher Code']);
foreach ($generatedVouchers as $voucher) {
fputcsv($csvHandle, [$voucher->getCode()]);
}
fclose($csvHandle);
});
$streamedResponse->setStatusCode(Response::HTTP_OK);
$streamedResponse->headers->set('Content-Type', 'text/csv; charset=utf-8');
$streamedResponse->headers->set('Content-Disposition', 'attachment; filename="' . self::CSV_FILENAME . '"');
return $streamedResponse->send();
}
示例13: exportar_archivoAction
/**
* @Route("/exportar_archivo", name="exportar_archivo_csv", options={"expose"=true})
* @Method("GET")
*/
public function exportar_archivoAction()
{
$response = new StreamedResponse();
$response->setCallback(function () {
$handle = fopen('php://output', 'w+');
// Add the header of the CSV file
fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
// Query data from database
$em = $this->getDoctrine()->getManager();
$results = $em->getRepository('BundlesInventarioBundle:InvProductoMov')->InventarioAldia('2016-01-01', '2016-04-30');
// Add the data queried from database
while ($row = $em->fetch($results)) {
fputcsv($handle, array($row['name'], $row['surname'], $row['age'], $row['sex']), ';');
}
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;
}
示例14: downloadSendedUsersAction
/**
* @param type $id
*
* @return StreamedResponse
* @Secure(roles="ROLE_NEWSLETTER_EDIT_CONTENT")
*/
public function downloadSendedUsersAction($id)
{
$response = new StreamedResponse();
$newsletterService = $this->get('maith_newsletter');
$response->setCallback(function () use($newsletterService, $id) {
$handle = fopen('php://output', 'w+');
// Add a row with the names of the columns for the CSV file
fputcsv($handle, array('Email', 'Hits'), ';');
// Query data from database
$results = $newsletterService->retrieveSendedUserSqlCursor($id);
// Add the data queried from database
while ($row = $results->fetch()) {
fputcsv($handle, array($row['email'], $row['hits']), ';');
}
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;
}
示例15: handleCsv
/**
* Export csv with entities.
*
* @param Request $request
*
* @return Response
*/
public function handleCsv(Request $request, array $criteria = [])
{
$this->entityList->build();
$response = new StreamedResponse();
$response->setCallback(function () use($request, $criteria) {
$handle = fopen('php://output', 'w+');
$fields = $this->entityList->getCsvFields();
fputcsv($handle, $fields);
$results = $this->entityList->createQueryBuilder($request, $criteria)->getQuery()->getResult();
foreach ($results as $entity) {
$row = array();
foreach ($fields as $field) {
$getField = 'get' . ucfirst($field);
if (method_exists($entity, $getField)) {
$value = $entity->{$getField}();
$row[] = $this->formatDataForCsv($field, $value);
continue;
}
$isField = 'is' . ucfirst($field);
if (method_exists($entity, $isField)) {
$row[] = $entity->{$isField}() === true ? 'Yes' : 'No';
}
}
fputcsv($handle, $row);
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $this->getExportName()));
return $response;
}