| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImportWP\Common\Importer\Preview; |
| 4 |
|
| 5 |
use ImportWP\Common\Importer\File\CSVFile; |
| 6 |
use ImportWP\Common\Importer\PreviewInterface; |
| 7 |
|
| 8 |
class CSVPreview implements PreviewInterface |
| 9 |
{ |
| 10 |
|
| 11 |
/** |
| 12 |
* @var CSVFile $file |
| 13 |
*/ |
| 14 |
private $file; |
| 15 |
|
| 16 |
/** |
| 17 |
* CSVPreview constructor. |
| 18 |
* |
| 19 |
* @param \ImportWP\Common\Importer\File\CSVFile $file |
| 20 |
* @param array $args |
| 21 |
*/ |
| 22 |
public function __construct(CSVFile $file, $args = array()) |
| 23 |
{ |
| 24 |
$this->file = $file; |
| 25 |
$this->file->processing(true); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Generate a return a table based on the CSV data being previewed. |
| 30 |
* |
| 31 |
* @return string |
| 32 |
*/ |
| 33 |
public function output() |
| 34 |
{ |
| 35 |
$records_to_fetch = 5; |
| 36 |
$total_records = $this->file->getRecordCount(); |
| 37 |
if ($total_records < $records_to_fetch) { |
| 38 |
$records_to_fetch = $total_records; |
| 39 |
} |
| 40 |
|
| 41 |
$output = '<table>'; |
| 42 |
|
| 43 |
for ($i = 0; $i < $records_to_fetch; $i++) { |
| 44 |
|
| 45 |
$csv = $this->file->getRecord($i); |
| 46 |
$wrapper = $i == 0 ? 'th' : 'td'; |
| 47 |
|
| 48 |
$output .= '<tr>'; |
| 49 |
$output .= sprintf('<%s>', $wrapper); |
| 50 |
$output .= implode(sprintf('</%s><%s>', $wrapper, $wrapper), str_getcsv($csv)); |
| 51 |
$output .= sprintf('</%s>', $wrapper); |
| 52 |
$output .= '</tr>'; |
| 53 |
} |
| 54 |
|
| 55 |
$output .= '</table>'; |
| 56 |
|
| 57 |
return $output; |
| 58 |
} |
| 59 |
|
| 60 |
public function data($record_index = 0, $show_headings = true) |
| 61 |
{ |
| 62 |
$result = []; |
| 63 |
$headings = str_getcsv($this->file->getRecord(0), $this->file->getDelimiter(), $this->file->getEnclosure(), $this->file->getEscape()); |
| 64 |
|
| 65 |
if (true === $show_headings) { |
| 66 |
$result['headings'] = $headings; |
| 67 |
$record_index++; |
| 68 |
} else { |
| 69 |
$result['headings'] = []; |
| 70 |
for ($i = 0; $i < count($headings); $i++) { |
| 71 |
$result['headings'][] = $i; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
$result['row'] = str_getcsv($this->file->getRecord($record_index), $this->file->getDelimiter(), $this->file->getEnclosure(), $this->file->getEscape()); |
| 76 |
return $result; |
| 77 |
} |
| 78 |
} |
| 79 |
|