/** * @param FormatterData $data * @return mixed * * This method must use a FormatterData object and output * a formatted value. */ public function encode(FormatterData $data) { $string = ""; /** * Get the first row and delimiters lengths */ $firstRow = $data->getRow(); $delimiterLength = strlen($this->delimiter); $lineReturnLength = strlen($this->lineReturn); if ($firstRow === false) { return ""; } /** * check if $this->order doesn't have non-existing rows */ $this->checkOrders($firstRow); $rawKeys = array_keys($firstRow); $keys = []; foreach ($rawKeys as $key) { $keys[$key] = $key; } $values = $data->getData(); array_unshift($values, $keys); while (null !== ($row = array_shift($values))) { /** * First put the sorted ones */ foreach ($this->order as $order) { $string .= $this->formatField($row[$order]); unset($row[$order]); } /** * Then place the fields, * order by name */ ksort($row); foreach ($keys as $key) { if (array_key_exists($key, $row)) { $string .= $this->formatField($row[$key]); } } $string = substr($string, 0, -$delimiterLength) . $this->lineReturn; } return substr($string, 0, -$lineReturnLength); }
public function testPopRow() { $data = new FormatterData(); $row = ["title" => "A super book", "author" => "Manu"]; $data->addRow($row); $this->assertEquals($row, $data->popRow()); $this->assertFalse($data->getRow()); }