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