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