xref: /plugin/struct/meta/SchemaImporter.php (revision 1dfe5343b719d50bfe1c5e0b85e6cdaa31180e35)
1<?php
2
3namespace 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 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     */
24    public function __construct($table, $json) {
25        parent::__construct($table, array());
26
27        // number of existing columns
28        $existing = count($this->oldschema->getColumns());
29
30        $input = json_decode($json, true);
31        if($input === null) {
32            switch(json_last_error()) {
33                case JSON_ERROR_NONE:
34                    $error = 'No errors';
35                    break;
36                case JSON_ERROR_DEPTH:
37                    $error = 'Maximum stack depth exceeded';
38                    break;
39                case JSON_ERROR_STATE_MISMATCH:
40                    $error = 'Underflow or the modes mismatch';
41                    break;
42                case JSON_ERROR_CTRL_CHAR:
43                    $error = 'Unexpected control character found';
44                    break;
45                case JSON_ERROR_SYNTAX:
46                    $error = 'Syntax error, malformed JSON';
47                    break;
48                case JSON_ERROR_UTF8:
49                    $error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
50                    break;
51                default:
52                    $error = 'Unknown error';
53                    break;
54            }
55
56            throw new StructException('JSON couldn\'t be decoded: ' . $error);
57        }
58        $data = array(
59            'cols' => array(),
60            'new' => array()
61        );
62
63        foreach($input['columns'] as $column) {
64            // config has to stay json
65            $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT);
66
67            if(!empty($column['colref']) && $column['colref'] <= $existing) {
68                // update existing column
69                $data['cols'][$column['colref']] = $column;
70            } else {
71                // add new column
72                $data['new'][] = $column;
73            }
74        }
75
76        $this->data = $data;
77    }
78
79}
80