xref: /plugin/struct/meta/SchemaImporter.php (revision 45560cc7da80a61cca33783efdbc315ccd232f90)
18ddf87afSAndreas Gohr<?php
28ddf87afSAndreas Gohr
38ddf87afSAndreas Gohrnamespace plugin\struct\meta;
48ddf87afSAndreas Gohr
5*45560cc7SAndreas Gohrif(!defined('JSON_PRETTY_PRINT')) define('JSON_PRETTY_PRINT', 0); // PHP 5.3 compatibility
6*45560cc7SAndreas Gohr
78ddf87afSAndreas Gohr/**
88ddf87afSAndreas Gohr * Class SchemaImporter
98ddf87afSAndreas Gohr *
108ddf87afSAndreas Gohr * This works just like the schema builder, except that it expects a JSON structure as input
118ddf87afSAndreas Gohr *
128ddf87afSAndreas Gohr * @package plugin\struct\meta
138ddf87afSAndreas Gohr */
148ddf87afSAndreas Gohrclass SchemaImporter extends SchemaBuilder {
158ddf87afSAndreas Gohr
168ddf87afSAndreas Gohr    /**
178ddf87afSAndreas Gohr     * Import a schema using JSON
188ddf87afSAndreas Gohr     *
198ddf87afSAndreas Gohr     * @todo sanity checking of the input data should be added
208ddf87afSAndreas Gohr     *
218ddf87afSAndreas Gohr     * @param string $table
228ddf87afSAndreas Gohr     * @param string $json
238ddf87afSAndreas Gohr     */
248ddf87afSAndreas Gohr    public function __construct($table, $json) {
258ddf87afSAndreas Gohr        parent::__construct($table, array());
268ddf87afSAndreas Gohr
278ddf87afSAndreas Gohr        // number of existing columns
288ddf87afSAndreas Gohr        $existing = count($this->oldschema->getColumns());
298ddf87afSAndreas Gohr
308ddf87afSAndreas Gohr        $input = json_decode($json, true);
318ddf87afSAndreas Gohr        $data = array(
328ddf87afSAndreas Gohr            'cols' => array(),
338ddf87afSAndreas Gohr            'new' => array()
348ddf87afSAndreas Gohr        );
358ddf87afSAndreas Gohr
368ddf87afSAndreas Gohr        foreach($input['columns'] as $column) {
378ddf87afSAndreas Gohr            // config has to stay json
388ddf87afSAndreas Gohr            $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT);
398ddf87afSAndreas Gohr
408ddf87afSAndreas Gohr            if(!empty($column['colref']) && $column['colref'] <= $existing) {
418ddf87afSAndreas Gohr                // update existing column
428ddf87afSAndreas Gohr                $data['cols'][$column['colref']] = $column;
438ddf87afSAndreas Gohr            } else {
448ddf87afSAndreas Gohr                // add new column
458ddf87afSAndreas Gohr                $data['new'][] = $column;
468ddf87afSAndreas Gohr            }
478ddf87afSAndreas Gohr        }
488ddf87afSAndreas Gohr
498ddf87afSAndreas Gohr        $this->data = $data;
508ddf87afSAndreas Gohr    }
518ddf87afSAndreas Gohr
528ddf87afSAndreas Gohr}
53