| 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 |
// Do not enable processing mode — preview navigation needs the full record index. |
| 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 |
$count = $this->file->getRecordCount(); |
| 65 |
$total = true === $show_headings ? max(0, $count - 1) : $count; |
| 66 |
$record_index = max(0, intval($record_index)); |
| 67 |
if ($total > 0) { |
| 68 |
$record_index = min($record_index, $total - 1); |
| 69 |
} else { |
| 70 |
$record_index = 0; |
| 71 |
} |
| 72 |
|
| 73 |
if (true === $show_headings) { |
| 74 |
$result['headings'] = $headings; |
| 75 |
$file_index = $record_index + 1; |
| 76 |
} else { |
| 77 |
$result['headings'] = []; |
| 78 |
for ($i = 0; $i < count($headings); $i++) { |
| 79 |
$result['headings'][] = $i; |
| 80 |
} |
| 81 |
$file_index = $record_index; |
| 82 |
} |
| 83 |
|
| 84 |
$result['row'] = str_getcsv($this->file->getRecord($file_index), $this->file->getDelimiter(), $this->file->getEnclosure(), $this->file->getEscape()); |
| 85 |
$result['record'] = $record_index; |
| 86 |
$result['total'] = $total; |
| 87 |
return $result; |
| 88 |
} |
| 89 |
} |
| 90 |
|