xref: /plugin/struct/meta/SchemaImporter.php (revision 1edf6e46bf5ccbff2cab3b71d69ef4cf5f20a379)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5if(!defined('JSON_PRETTY_PRINT')) define('JSON_PRETTY_PRINT', 0); // PHP 5.3 compatibility
6
7/**
8 * Class SchemaImporter
9 *
10 * This works just like the schema builder, except that it expects a JSON structure as input
11 *
12 * @package dokuwiki\plugin\struct\meta
13 */
14class SchemaImporter extends SchemaBuilder {
15
16    /**
17     * Import a schema using JSON
18     *
19     * @todo sanity checking of the input data should be added
20     *
21     * @param string $table
22     * @param string $json
23     * @param bool $islookup
24     */
25    public function __construct($table, $json, $islookup=false) {
26        parent::__construct($table, array('islookup' => $islookup));
27
28        // number of existing columns
29        $existing = count($this->oldschema->getColumns());
30
31        $input = json_decode($json, true);
32        if($input === null) {
33            switch(json_last_error()) {
34                case JSON_ERROR_NONE:
35                    $error = 'No errors';
36                    break;
37                case JSON_ERROR_DEPTH:
38                    $error = 'Maximum stack depth exceeded';
39                    break;
40                case JSON_ERROR_STATE_MISMATCH:
41                    $error = 'Underflow or the modes mismatch';
42                    break;
43                case JSON_ERROR_CTRL_CHAR:
44                    $error = 'Unexpected control character found';
45                    break;
46                case JSON_ERROR_SYNTAX:
47                    $error = 'Syntax error, malformed JSON';
48                    break;
49                case JSON_ERROR_UTF8:
50                    $error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
51                    break;
52                default:
53                    $error = 'Unknown error';
54                    break;
55            }
56
57            throw new StructException('JSON couldn\'t be decoded: ' . $error);
58        }
59        $config = isset($input['config']) ? $input['config'] : array();
60        $data = array(
61            'config' => json_encode($config),
62            'cols' => array(),
63            'new' => array(),
64        );
65
66        foreach($input['columns'] as $column) {
67            // config has to stay json
68            $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT);
69
70            if(!empty($column['colref']) && $column['colref'] <= $existing) {
71                // update existing column
72                $data['cols'][$column['colref']] = $column;
73            } else {
74                // add new column
75                $data['new'][] = $column;
76            }
77        }
78
79        $this->data = $data;
80    }
81
82}
83