1<?php 2 3namespace dokuwiki\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 dokuwiki\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, []); 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 $config = isset($input['config']) ? $input['config'] : array(); 59 $data = array( 60 'config' => json_encode($config), 61 'cols' => array(), 62 'new' => array(), 63 ); 64 65 foreach($input['columns'] as $column) { 66 // config has to stay json 67 $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT); 68 69 if(!empty($column['colref']) && $column['colref'] <= $existing) { 70 // update existing column 71 $data['cols'][$column['colref']] = $column; 72 } else { 73 // add new column 74 $data['new'][] = $column; 75 } 76 } 77 78 $this->data = $data; 79 } 80 81} 82