| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImportWP\Common\Exporter\File; |
| 4 |
|
| 5 |
use ImportWP\Common\Exporter\Mapper\MapperData; |
| 6 |
|
| 7 |
class CSVFile extends File |
| 8 |
{ |
| 9 |
private $columns; |
| 10 |
public function start() |
| 11 |
{ |
| 12 |
$fields = $this->exporter->getFields(); |
| 13 |
|
| 14 |
$this->columns = array_reduce($fields, function ($carry, $item) { |
| 15 |
$carry[$this->getFieldLabel($item)] = isset($item['selection']) ? $item['selection'] : ''; |
| 16 |
return $carry; |
| 17 |
}, []); |
| 18 |
// write headers |
| 19 |
fputcsv($this->fh, array_keys($this->columns)); |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* @param MapperData $mapper |
| 24 |
* @return void |
| 25 |
*/ |
| 26 |
public function add($mapper) |
| 27 |
{ |
| 28 |
$data = []; |
| 29 |
$data = array_map(function ($item) use ($mapper) { |
| 30 |
$record = $mapper->data([]); |
| 31 |
$tmp = $mapper->get_value($item, $record[0]); |
| 32 |
return is_array($tmp) ? implode(',', $tmp) : $tmp; |
| 33 |
}, $this->columns); |
| 34 |
|
| 35 |
fputcsv($this->fh, $data); |
| 36 |
} |
| 37 |
|
| 38 |
public function end() |
| 39 |
{ |
| 40 |
fclose($this->fh); |
| 41 |
} |
| 42 |
|
| 43 |
public function get_file_name() |
| 44 |
{ |
| 45 |
return $this->exporter->getId() . '.csv'; |
| 46 |
} |
| 47 |
} |
| 48 |
|