本文整理汇总了PHP中Symfony\Component\HttpFoundation\StreamedResponse::setCallback方法的典型用法代码示例。如果您正苦于以下问题:PHP StreamedResponse::setCallback方法的具体用法?PHP StreamedResponse::setCallback怎么用?PHP StreamedResponse::setCallback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\StreamedResponse
的用法示例。
在下文中一共展示了StreamedResponse::setCallback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: uploadImageAction
/**
* 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();
}
示例2: exportProCSVAction
/**
* @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;
}
示例3: 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;
}
示例4: handle
/**
* 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);
}
}
}
示例5: 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;
}
示例6: createResponse
/**
* 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;
}
示例7: 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;
}
示例8: setContent
/**
* 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;
}
示例9: createStreamedResponse
/**
* 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;
}
示例10: stream
/**
* @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;
}
示例11: export
/**
* 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;
}
示例12: stream
/**
* @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;
}
示例13: 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;
}
示例14: streamedPictureAction
/**
* 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;
}
示例15: 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;
}