1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5/**
6 * Class CSVExporter
7 *
8 * exports raw schema data to CSV.
9 *
10 * Note this is different from syntax/csv.php
11 *
12 * @package dokuwiki\plugin\struct\meta
13 */
14class CSVExporter
15{
16    public const DATATYPE_PAGE = 'page';
17    public const DATATYPE_GLOBAL = 'global';
18    public const DATATYPE_SERIAL = 'serial';
19
20    protected $type = '';
21
22    /**
23     * CSVExporter constructor.
24     *
25     * @param string $table
26     * @param string $type
27     */
28    public function __construct($table, $type)
29    {
30        // TODO make it nicer
31        $this->type = $type;
32
33        $search = new Search();
34        $search->addSchema($table);
35        $search->addColumn('*');
36
37        $result = $search->getRows();
38
39        if ($this->type !== self::DATATYPE_GLOBAL) {
40            $pids = $search->getPids();
41        }
42
43        echo $this->header($search->getColumns());
44        foreach ($result as $i => $row) {
45            if ($this->type !== self::DATATYPE_GLOBAL) {
46                $pid = $pids[$i];
47            } else {
48                $pid = '';
49            }
50            echo $this->row($row, $pid);
51        }
52    }
53
54    /**
55     * Create the header
56     *
57     * @param Column[] $columns
58     * @return string
59     */
60    protected function header($columns)
61    {
62        $row = '';
63
64        if ($this->type !== self::DATATYPE_GLOBAL) {
65            $row .= $this->escape('pid');
66            $row .= ',';
67        }
68
69        foreach ($columns as $col) {
70            $row .= $this->escape($col->getLabel());
71            $row .= ',';
72        }
73        return rtrim($row, ',') . "\r\n";
74    }
75
76    /**
77     * Create one row of data
78     *
79     * @param Value[] $values
80     * @param string $pid pid of this row
81     * @return string
82     */
83    protected function row($values, $pid)
84    {
85        $row = '';
86        if ($this->type !== self::DATATYPE_GLOBAL) {
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 = implode(',', $val);
95
96            // FIXME check escaping of composite ids (JSON with """")
97            $row .= $this->escape($val);
98            $row .= ',';
99        }
100
101        return rtrim($row, ',') . "\r\n";
102    }
103
104    /**
105     * Escapes and wraps the given string
106     *
107     * Uses doubled quotes for escaping which seems to be the standard escaping method for CSV
108     *
109     * @param string $str
110     * @return string
111     */
112    protected function escape($str)
113    {
114        return '"' . str_replace('"', '""', $str) . '"';
115    }
116}
117