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