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 protected $islookup = false; 18 19 /** 20 * CSVImporter constructor. 21 * 22 * @throws StructException 23 * @param string $table 24 */ 25 public function __construct($table) { 26 27 $search = new Search(); 28 $search->addSchema($table); 29 $search->addColumn('*'); 30 $result = $search->execute(); 31 32 $this->islookup = $search->getSchemas()[0]->isLookup(); 33 if(!$this->islookup) { 34 $pids = $search->getPids(); 35 } else { 36 $pids = array(); 37 } 38 39 echo $this->header($search->getColumns()); 40 foreach($result as $i => $row) { 41 if(!$this->islookup) { 42 $pid = $pids[$i]; 43 } else { 44 $pid = 0; 45 } 46 47 echo $this->row($row, $pid); 48 } 49 } 50 51 /** 52 * Create the header 53 * 54 * @param Column[] $columns 55 * @return string 56 */ 57 protected function header($columns) { 58 $row = ''; 59 60 if(!$this->islookup) { 61 $row .= $this->escape('pid'); 62 $row .= ','; 63 } 64 65 foreach($columns as $i => $col) { 66 $row .= $this->escape($col->getLabel()); 67 $row .= ','; 68 } 69 return rtrim($row, ',') . "\r\n"; 70 } 71 72 /** 73 * Create one row of data 74 * 75 * @param Value[] $values 76 * @param string $pid pid of this row 77 * @return string 78 */ 79 protected function row($values, $pid) { 80 $row = ''; 81 82 if(!$this->islookup) { 83 $row .= $this->escape($pid); 84 $row .= ','; 85 } 86 87 foreach($values as $value) { 88 /** @var Value $value */ 89 $val = $value->getRawValue(); 90 if(is_array($val)) $val = join(',', $val); 91 92 $row .= $this->escape($val); 93 $row .= ','; 94 } 95 96 return rtrim($row, ',') . "\r\n"; 97 } 98 99 /** 100 * Escapes and wraps the given string 101 * 102 * Uses doubled quotes for escaping which seems to be the standard escaping method for CSV 103 * 104 * @param string $str 105 * @return string 106 */ 107 protected function escape($str) { 108 return '"' . str_replace('"', '""', $str) . '"'; 109 } 110 111} 112