1<?php 2 3namespace dokuwiki\plugin\struct\meta; 4 5/** 6 * Class CSVExporter 7 * 8 * exports raw schema data to CSV. For lookup schemas this data can be reimported again through 9 * CSVImporter 10 * 11 * Note this is different from syntax/csv.php 12 * 13 * @package dokuwiki\plugin\struct\meta 14 */ 15class CSVExporter 16{ 17 18 protected $islookup = false; 19 20 /** 21 * CSVImporter constructor. 22 * 23 * @throws StructException 24 * @param string $table 25 */ 26 public function __construct($table) 27 { 28 29 $search = new Search(); 30 $search->addSchema($table); 31 $search->addColumn('*'); 32 $result = $search->execute(); 33 34 $this->islookup = $search->getSchemas()[0]->isLookup(); 35 if (!$this->islookup) { 36 $pids = $search->getPids(); 37 } else { 38 $pids = array(); 39 } 40 41 echo $this->header($search->getColumns()); 42 foreach ($result as $i => $row) { 43 if (!$this->islookup) { 44 $pid = $pids[$i]; 45 } else { 46 $pid = 0; 47 } 48 49 echo $this->row($row, $pid); 50 } 51 } 52 53 /** 54 * Create the header 55 * 56 * @param Column[] $columns 57 * @return string 58 */ 59 protected function header($columns) 60 { 61 $row = ''; 62 63 if (!$this->islookup) { 64 $row .= $this->escape('pid'); 65 $row .= ','; 66 } 67 68 foreach ($columns as $i => $col) { 69 $row .= $this->escape($col->getLabel()); 70 $row .= ','; 71 } 72 return rtrim($row, ',') . "\r\n"; 73 } 74 75 /** 76 * Create one row of data 77 * 78 * @param Value[] $values 79 * @param string $pid pid of this row 80 * @return string 81 */ 82 protected function row($values, $pid) 83 { 84 $row = ''; 85 86 if (!$this->islookup) { 87 $row .= $this->escape($pid); 88 $row .= ','; 89 } 90 91 foreach ($values as $value) { 92 /** @var Value $value */ 93 $val = $value->getRawValue(); 94 if (is_array($val)) $val = join(',', $val); 95 96 $row .= $this->escape($val); 97 $row .= ','; 98 } 99 100 return rtrim($row, ',') . "\r\n"; 101 } 102 103 /** 104 * Escapes and wraps the given string 105 * 106 * Uses doubled quotes for escaping which seems to be the standard escaping method for CSV 107 * 108 * @param string $str 109 * @return string 110 */ 111 protected function escape($str) 112 { 113 return '"' . str_replace('"', '""', $str) . '"'; 114 } 115} 116