xref: /plugin/struct/meta/CSVExporter.php (revision 4569877746ab0c3591533699439bef409f38672a)
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 $type = '';
18
19    /**
20     * CSVExporter constructor.
21     *
22     * @param string $table
23     * @param string $type
24     */
25    public function __construct($table, $type)
26    {
27        // TODO make it nicer
28        $this->type = $type;
29
30        $search = new Search();
31        $search->addSchema($table);
32        $search->addColumn('*');
33        $result = $search->execute();
34
35        if ($this->type !== 'lookup') {
36            $pids = $search->getPids();
37        }
38
39        echo $this->header($search->getColumns());
40        foreach ($result as $i => $row) {
41            if ($this->type !== 'lookup') {
42                $pid = $pids[$i];
43            } else {
44                $pid = '';
45            }
46            echo $this->row($row, $pid);
47        }
48    }
49
50    /**
51     * Create the header
52     *
53     * @param Column[] $columns
54     * @return string
55     */
56    protected function header($columns)
57    {
58        $row = '';
59
60        if($this->type !== 'lookup') {
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    {
81        $row = '';
82        if($this->type !== 'lookup') {
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            // FIXME check escaping of composite ids (JSON with """")
93            $row .= $this->escape($val);
94            $row .= ',';
95        }
96
97        return rtrim($row, ',') . "\r\n";
98    }
99
100    /**
101     * Escapes and wraps the given string
102     *
103     * Uses doubled quotes for escaping which seems to be the standard escaping method for CSV
104     *
105     * @param string $str
106     * @return string
107     */
108    protected function escape($str)
109    {
110        return '"' . str_replace('"', '""', $str) . '"';
111    }
112}
113