xref: /plugin/struct/meta/SchemaImporter.php (revision 16b7d914c0b69bf27d1ddd8a08e05beddbeedf02)
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        $data = array(
32            'cols' => array(),
33            'new' => array()
34        );
35
36        foreach($input['columns'] as $column) {
37            // config has to stay json
38            $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT);
39
40            if(!empty($column['colref']) && $column['colref'] <= $existing) {
41                // update existing column
42                $data['cols'][$column['colref']] = $column;
43            } else {
44                // add new column
45                $data['new'][] = $column;
46            }
47        }
48
49        $this->data = $data;
50    }
51
52}
53