| 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 |
private $setup = false; |
| 11 |
|
| 12 |
public function start() |
| 13 |
{ |
| 14 |
$fields = $this->exporter->getFields(); |
| 15 |
|
| 16 |
$this->columns = array_reduce($fields, function ($carry, $item) { |
| 17 |
$carry[$this->getFieldLabel($item)] = isset($item['selection']) ? $item['selection'] : ''; |
| 18 |
return $carry; |
| 19 |
}, []); |
| 20 |
|
| 21 |
// write headers |
| 22 |
fputcsv($this->fh, array_keys($this->columns)); |
| 23 |
|
| 24 |
update_site_option('iwp_exporter_csv_config', [ |
| 25 |
'columns' => $this->columns |
| 26 |
]); |
| 27 |
} |
| 28 |
|
| 29 |
public function loadConfig() |
| 30 |
{ |
| 31 |
if (!$this->setup) { |
| 32 |
$config = get_site_option('iwp_exporter_csv_config', []); |
| 33 |
$this->columns = $config['columns']; |
| 34 |
$this->setup = true; |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* @param MapperData $mapper |
| 40 |
* @return void |
| 41 |
*/ |
| 42 |
public function add($mapper) |
| 43 |
{ |
| 44 |
$this->loadConfig(); |
| 45 |
$data = []; |
| 46 |
|
| 47 |
$max = $mapper->get_total_records(); |
| 48 |
if ($max <= 0) { |
| 49 |
$max = 1; |
| 50 |
} |
| 51 |
for ($i = 0; $i < $max; $i++) { |
| 52 |
|
| 53 |
$data = array_map(function ($item) use ($mapper, $i) { |
| 54 |
$record = $mapper->data([], $i); |
| 55 |
$tmp = $mapper->get_value($item, $record[0]); |
| 56 |
return is_array($tmp) ? implode(',', $tmp) : $tmp; |
| 57 |
}, $this->columns); |
| 58 |
|
| 59 |
fputcsv($this->fh, $data); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
public function end() |
| 64 |
{ |
| 65 |
fclose($this->fh); |
| 66 |
} |
| 67 |
|
| 68 |
public function get_file_name() |
| 69 |
{ |
| 70 |
return $this->exporter->getId() . '.csv'; |
| 71 |
} |
| 72 |
} |
| 73 |
|