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