CsvWriterTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Ddeboer\DataImport\Tests\Writer;
  3. use Ddeboer\DataImport\Writer\CsvWriter;
  4. class CsvWriterTest extends StreamWriterTest
  5. {
  6. public function testWriteItem()
  7. {
  8. $writer = new CsvWriter(';', '"', $this->getStream());
  9. $writer->prepare();
  10. $writer->writeItem(array('first', 'last'));
  11. $writer->writeItem(array(
  12. 'first' => 'James',
  13. 'last' => 'Bond'
  14. ));
  15. $writer->writeItem(array(
  16. 'first' => '',
  17. 'last' => 'Dr. No'
  18. ));
  19. $this->assertContentsEquals(
  20. "first;last\nJames;Bond\n;\"Dr. No\"\n",
  21. $writer
  22. );
  23. $writer->finish();
  24. }
  25. public function testWriteUtf8Item()
  26. {
  27. $writer = new CsvWriter(';', '"', $this->getStream(), true);
  28. $writer->prepare();
  29. $writer->writeItem(array('Précédent', 'Suivant'));
  30. $this->assertContentsEquals(
  31. chr(0xEF) . chr(0xBB) . chr(0xBF) . "Précédent;Suivant\n",
  32. $writer
  33. );
  34. $writer->finish();
  35. }
  36. /**
  37. * Test that column names not prepended to first row
  38. * if CsvWriter's 5-th parameter not given
  39. *
  40. * @author Igor Mukhin <igor.mukhin@gmail.com>
  41. */
  42. public function testHeaderNotPrependedByDefault()
  43. {
  44. $writer = new CsvWriter(';', '"', $this->getStream(), false);
  45. $writer->prepare();
  46. $writer->writeItem(array(
  47. 'col 1 name'=>'col 1 value',
  48. 'col 2 name'=>'col 2 value',
  49. 'col 3 name'=>'col 3 value'
  50. ));
  51. # Values should be at first line
  52. $this->assertContentsEquals(
  53. "\"col 1 value\";\"col 2 value\";\"col 3 value\"\n",
  54. $writer
  55. );
  56. $writer->finish();
  57. }
  58. /**
  59. * Test that column names prepended at first row
  60. * and values have been written at second line
  61. * if CsvWriter's 5-th parameter set to true
  62. *
  63. * @author Igor Mukhin <igor.mukhin@gmail.com>
  64. */
  65. public function testHeaderPrependedWhenOptionSetToTrue()
  66. {
  67. $writer = new CsvWriter(';', '"', $this->getStream(), false, true);
  68. $writer->prepare();
  69. $writer->writeItem(array(
  70. 'col 1 name'=>'col 1 value',
  71. 'col 2 name'=>'col 2 value',
  72. 'col 3 name'=>'col 3 value'
  73. ));
  74. # Column names should be at second line
  75. # Values should be at second line
  76. $this->assertContentsEquals(
  77. "\"col 1 name\";\"col 2 name\";\"col 3 name\"\n" .
  78. "\"col 1 value\";\"col 2 value\";\"col 3 value\"\n",
  79. $writer
  80. );
  81. $writer->finish();
  82. }
  83. }