<?php
namespace nur\mapper\csv;

use nur\t\TestCase;

class CsvReaderTest extends TestCase {
  function testReader1() {
    $rwf = fopen("php://memory", "w+b");
    fwrite($rwf, <<<EOT
nom,prenom,age
clain,jephté,45
enpion,tarte,36
x,y
z

a,b
first,second
EOT
    );
    rewind($rwf);

    $reader = new CsvReader($rwf);
    $reader->setMultiSchema(true);
    $rows = iterator_to_array($reader);
    self::assertSame([
      ["nom" => "clain", "prenom" => "jephté", "age" => "45"],
      ["nom" => "enpion", "prenom" => "tarte", "age" => "36"],
      ["nom" => "x", "prenom" => "y", "age" => false],
      ["nom" => "z", "prenom" => false, "age" => false],
      ["a" => "first", "b" => "second"],
    ], $rows);
  }

  function testReader2() {
    $rwf = fopen("php://memory", "w+b");
    fwrite($rwf, <<<EOT
nom,comment,num
clain,"ceci est
un commentaire",45
EOT
    );
    rewind($rwf);

    $reader = new CsvReader($rwf);
    $rows = iterator_to_array($reader);
    self::assertSame([
      ["nom" => "clain", "comment" => "ceci est
un commentaire", "num" => "45"],
    ], $rows);
  }

  function testReader3() {
    $rwf = fopen("php://memory", "w+b");
    fwrite($rwf, "");
    rewind($rwf);

    $reader = new CsvReader($rwf);
    $rows = iterator_to_array($reader);
    self::assertSame([], $rows);
  }

  function testReader4() {
    $rwf = fopen("php://memory", "w+b");
    fwrite($rwf, "nom,prenom,age");
    rewind($rwf);

    $reader = new CsvReader($rwf);
    $rows = iterator_to_array($reader);
    self::assertSame([], $rows);
  }

  function testReader5() {
    $reader = new CsvReader(__DIR__ . "/utf8.csv");
    $rows = iterator_to_array($reader);
    self::assertSame([
      ["nom" => "clain", "prénom" => "jephté", "age" => "45"],
    ], $rows);

    $reader = new CsvReader(__DIR__ . "/cp1252.csv");
    $reader->setEncodingFilter("cp1252");
    $rows = iterator_to_array($reader);
    self::assertSame([
      ["nom" => "clain", "prénom" => "jephté", "age" => "45"],
    ], $rows);
  }
}
