Exporter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Export;
  11. use Exporter\Source\SourceIteratorInterface;
  12. use Symfony\Component\HttpFoundation\StreamedResponse;
  13. use Exporter\Writer\XlsWriter;
  14. use Exporter\Writer\XmlWriter;
  15. use Exporter\Writer\JsonWriter;
  16. use Exporter\Writer\CsvWriter;
  17. class Exporter
  18. {
  19. /**
  20. * @throws \RuntimeException
  21. *
  22. * @param string $format
  23. * @param string $filename
  24. * @param SourceIteratorInterface $source
  25. *
  26. * @return StreamedResponse
  27. */
  28. public function getResponse($format, $filename, SourceIteratorInterface $source)
  29. {
  30. switch ($format) {
  31. case 'xls':
  32. $writer = new XlsWriter('php://output');
  33. $contentType = 'application/vnd.ms-excel';
  34. break;
  35. case 'xml':
  36. $writer = new XmlWriter('php://output');
  37. $contentType = 'text/xml';
  38. break;
  39. case 'json':
  40. $writer = new JsonWriter('php://output');
  41. $contentType = 'application/json';
  42. break;
  43. case 'csv':
  44. $writer = new CsvWriter('php://output', ',', '"', "", true, true);
  45. $contentType = 'text/csv';
  46. break;
  47. default:
  48. throw new \RuntimeException('Invalid format');
  49. }
  50. $callback = function() use ($source, $writer) {
  51. $handler = \Exporter\Handler::create($source, $writer);
  52. $handler->export();
  53. };
  54. return new StreamedResponse($callback, 200, array(
  55. 'Content-Type' => $contentType,
  56. 'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
  57. ));
  58. }
  59. }