<?php
namespace nur\mapper\csv;

use nur\b\io\StringWriter;
use nur\t\TestCase;

class CsvWriterTest extends TestCase {
  function testWriter() {
    $w = new StringWriter();
    $consumer = new CsvWriter($w);
    $consumer->consume([
      ["nom" => "clain", "prenom" => "jephté", "age" => 45],
      ["nom" => "enpion", "prenom" => "tarte", "age" => 36],
      ["nom" => "cool", "prenom" => "plusieurs
lignes", "age" => 15],
    ]);
    self::assertSame("nom,prenom,age
clain,jephté,45
enpion,tarte,36
cool,\"plusieurs
lignes\",15
", $w->getString());
  }

  function testResource() {
    $w = fopen("php://memory", "w+b");
    $consumer = new CsvWriter($w);
    $consumer->consume([
      ["nom" => "clain", "prenom" => "jephté", "age" => 45],
      ["nom" => "enpion", "prenom" => "tarte", "age" => 36],
      ["nom" => "cool", "prenom" => "plusieurs
lignes", "age" => 15],
    ]);
    rewind($w);
    self::assertSame("nom,prenom,age
clain,jephté,45
enpion,tarte,36
cool,\"plusieurs
lignes\",15
", stream_get_contents($w));
  }

  function testEmpty() {
    $w = new StringWriter();
    $consumer = new CsvWriter($w);
    $consumer->consume([]);
    self::assertSame("", $w->getString());

    $w = new StringWriter();
    $consumer = new CsvWriter($w);
    $consumer->setHeaders(["nom", "prenom", "age"]);
    $consumer->consume([]);
    self::assertSame("nom,prenom,age\n", $w->getString());
  }
}