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 * @param bool $islookup 24 */ 25 public function __construct($table, $json, $islookup=false) { 26 parent::__construct($table, array('islookup' => $islookup)); 27 28 // number of existing columns 29 $existing = count($this->oldschema->getColumns()); 30 31 $input = json_decode($json, true); 32 if($input === null) { 33 switch(json_last_error()) { 34 case JSON_ERROR_NONE: 35 $error = 'No errors'; 36 break; 37 case JSON_ERROR_DEPTH: 38 $error = 'Maximum stack depth exceeded'; 39 break; 40 case JSON_ERROR_STATE_MISMATCH: 41 $error = 'Underflow or the modes mismatch'; 42 break; 43 case JSON_ERROR_CTRL_CHAR: 44 $error = 'Unexpected control character found'; 45 break; 46 case JSON_ERROR_SYNTAX: 47 $error = 'Syntax error, malformed JSON'; 48 break; 49 case JSON_ERROR_UTF8: 50 $error = 'Malformed UTF-8 characters, possibly incorrectly encoded'; 51 break; 52 default: 53 $error = 'Unknown error'; 54 break; 55 } 56 57 throw new StructException('JSON couldn\'t be decoded: ' . $error); 58 } 59 $data = array( 60 'cols' => array(), 61 'new' => array(), 62 ); 63 64 foreach($input['columns'] as $column) { 65 // config has to stay json 66 $column['config'] = json_encode($column['config'], JSON_PRETTY_PRINT); 67 68 if(!empty($column['colref']) && $column['colref'] <= $existing) { 69 // update existing column 70 $data['cols'][$column['colref']] = $column; 71 } else { 72 // add new column 73 $data['new'][] = $column; 74 } 75 } 76 77 $this->data = $data; 78 } 79 80} 81