1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5class CSVSerialImporter extends CSVImporter
6{
7    /** @var bool[] */
8    protected $createPage = [];
9
10    /**
11     * Import page schema only when the pid header is present.
12     */
13    protected function readHeaders()
14    {
15        parent::readHeaders();
16        if (!in_array('pid', $this->header))
17            throw new StructException('There is no "pid" header in the CSV. Schema not imported.');
18    }
19
20    /**
21     * Add the revision.
22     *
23     * @param string[] $values
24     */
25    protected function saveLine($values)
26    {
27        // create new page
28        $pid = cleanID($values[0]);
29        if ($this->createPage[$pid]) {
30            $this->createPage($pid, $values);
31        }
32
33        parent::saveLine($values);
34    }
35
36    /**
37     * Create a page with serial syntax, either from a namespace template with _serial suffix
38     * or an empty one.
39     *
40     * @param string $pid
41     * @param array $line
42     */
43    protected function createPage($pid, $line)
44    {
45        $text = pageTemplate($pid);
46        if (trim($text) === '') {
47            $pageParts = explode(':', $pid);
48            $pagename = end($pageParts);
49            $text = "====== $pagename ======\n";
50        }
51
52        // add serial syntax
53        $schema = $this->schema->getTable();
54        $text .= "
55---- struct serial ----
56schema: $schema
57cols: *
58----
59";
60        saveWikiText($pid, $text, 'Created by struct csv import');
61    }
62
63    /**
64     * Check if page id realy exists
65     *
66     * @param Column $col
67     * @param mixed $rawvalue
68     * @return bool
69     */
70    protected function validateValue(Column $col, &$rawvalue)
71    {
72        global $INPUT;
73        if ($col->getLabel() !== 'pid' || !$INPUT->bool('createPage')) {
74            return parent::validateValue($col, $rawvalue);
75        }
76
77        $pid = cleanID($rawvalue);
78        if (!page_exists($pid)) {
79            $this->createPage[$pid] = true;
80        }
81        return true;
82    }
83}
84