xref: /plugin/struct/meta/SchemaImporter.php (revision 8ddf87af744169eff8f5d143d3a526ba2a2e2987)
1<?php
2
3namespace plugin\struct\meta;
4
5/**
6 * Class SchemaImporter
7 *
8 * This works just like the schema builder, except that it expects a JSON structure as input
9 *
10 * @package plugin\struct\meta
11 */
12class SchemaImporter extends SchemaBuilder {
13
14    /**
15     * Import a schema using JSON
16     *
17     * @todo sanity checking of the input data should be added
18     *
19     * @param string $table
20     * @param string $json
21     */
22    public function __construct($table, $json) {
23        parent::__construct($table, array());
24
25        // number of existing columns
26        $existing = count($this->oldschema->getColumns());
27
28        $input = json_decode($json, true);
29        $data = array(
30            'cols' => array(),
31            'new' => array()
32        );
33
34        foreach($input['columns'] as $column) {
35            // config has to stay json
36            $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT);
37
38            if(!empty($column['colref']) && $column['colref'] <= $existing) {
39                // update existing column
40                $data['cols'][$column['colref']] = $column;
41            } else {
42                // add new column
43                $data['new'][] = $column;
44            }
45        }
46
47        $this->data = $data;
48    }
49
50}
51