CsvWriter.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 Exporter\Writer;
  11. use Exporter\Exception\InvalidDataFormatException;
  12. class CsvWriter implements WriterInterface
  13. {
  14. protected $filename;
  15. protected $delimiter;
  16. protected $enclosure;
  17. protected $escape;
  18. protected $file;
  19. protected $showHeaders;
  20. protected $position;
  21. /**
  22. * @param string $filename
  23. * @param string $delimiter
  24. * @param string $enclosure
  25. * @param string $escape
  26. * @param bool $showHeaders
  27. */
  28. public function __construct($filename, $delimiter = ",", $enclosure = "\"", $escape = "\\", $showHeaders = true)
  29. {
  30. $this->filename = $filename;
  31. $this->delimiter = $delimiter;
  32. $this->enclosure = $enclosure;
  33. $this->escape = $escape;
  34. $this->showHeaders = $showHeaders;
  35. $this->position = 0;
  36. if (is_file($filename)) {
  37. throw new \RuntimeException(sprintf('The file %s already exist', $filename));
  38. }
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function open()
  44. {
  45. $this->file = fopen($this->filename, 'w', false);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function close()
  51. {
  52. fclose($this->file);
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function write(array $data)
  58. {
  59. if ($this->position == 0 && $this->showHeaders) {
  60. $this->addHeaders($data);
  61. $this->position++;
  62. }
  63. $result = @fputcsv($this->file, $data, $this->delimiter, $this->enclosure);
  64. if (!$result) {
  65. throw new InvalidDataFormatException();
  66. }
  67. $this->position++;
  68. }
  69. /**
  70. * @param array $data
  71. *
  72. * @return void
  73. */
  74. protected function addHeaders(array $data)
  75. {
  76. $headers = array();
  77. foreach ($data as $header => $value) {
  78. $headers[] = $header;
  79. }
  80. fputcsv($this->file, $headers, $this->delimiter, $this->enclosure);
  81. }
  82. }