Exporter.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 Exporter\Handler;
  13. use Symfony\Component\HttpFoundation\Response;
  14. class Exporter
  15. {
  16. /**
  17. * @throws \RuntimeException
  18. * @param $format
  19. * @param $filename
  20. * @param \Exporter\Source\SourceIteratorInterface $source
  21. * @return \Symfony\Component\HttpFoundation\Response
  22. */
  23. public function getResponse($format, $filename, SourceIteratorInterface $source)
  24. {
  25. $privateFilename = sprintf('%s/%s', sys_get_temp_dir(), uniqid('sonata_export_', true));
  26. switch($format) {
  27. case 'xls':
  28. $writer = new \Exporter\Writer\XlsWriter($privateFilename);
  29. $contentType = 'application/vnd.ms-excel';
  30. break;
  31. case 'xml':
  32. $writer = new \Exporter\Writer\XmlWriter($privateFilename);
  33. $contentType = 'text/xml';
  34. break;
  35. case 'json':
  36. $writer = new \Exporter\Writer\JsonWriter($privateFilename);
  37. $contentType = 'application/json';
  38. break;
  39. case 'csv':
  40. $writer = new \Exporter\Writer\CsvWriter($privateFilename, ',', '"', "", true);
  41. $contentType = 'text/csv';
  42. break;
  43. default:
  44. throw new \RuntimeException('Invalid format');
  45. }
  46. $handler = Handler::create($source, $writer);
  47. $handler->export();
  48. $response = new Response(file_get_contents($privateFilename), 200, array(
  49. 'Content-Type' => $contentType,
  50. 'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
  51. ));
  52. unlink($privateFilename);
  53. return $response;
  54. }
  55. }