import {Rule} from "./Rule"; import {Rules} from "./Rules"; import {FactoryCreateRule} from "./FactoryCreateRule"; import {SetNextRule} from "./SetNextRule"; import {CallMethodRule} from "./CallMethodRule"; import {Stack} from "./Stack"; import {autobind} from "core-decorators"; import {StringBuffer} from "../../lang/StringBuffer"; export class JSONDigester { private _root:any; private _rules:Rules; private _bodyText:StringBuffer private _bodyTexts = new Stack(); private _params:StringBuffer; private _stacksByName:{ [key: string]: Stack }; private _stack:Stack = new Stack(); private _match:string; private _matches = new Stack>(); constructor() { this._match = ''; this._bodyText = new StringBuffer(); this._params = new StringBuffer(); this._stacksByName = {}; } get isDebugEnabled():boolean { return false; } get match():string { return this._match; } parse(json: {[key:string]: any}):void { Object.keys(json).forEach(key => { this.parseObject(key, json[key]) }); } private parseObject(name:string, obj: {[key:string]: any}):void { if (! obj) { return; } this.onTagOpen(name, this.getAttributes(obj)); // 继续处理其中包含的 Object 和 Array this.continueParseElements(obj); this.onTagClose(name); } private parseArray(name:string, array: Array<{[key:string]: any}>):void { if (! array) { return; } this.onTagOpen(name, {}); array.forEach(obj => { const key = Object.keys(obj)[0]; this.parseObject(key, obj[key]); }); this.onTagClose(name); } @autobind private onTagOpen(name:string, attrs:{[key:string]: any}):void { const debug = this.isDebugEnabled; // Save the body text accumulated for our surrounding element this._bodyTexts.push(this._bodyText); if (debug) { console.debug(` Pushing body text '${this._bodyText.toString()}'`); } this._bodyText = new StringBuffer(); const sb = new StringBuffer(); if (this._match) { sb.append(this._match); sb.append('/'); } sb.append(name); this._match = sb.toString(); if (debug) { console.debug(` New match='${this._match}'`); } // Fire "begin" events for all relevant rules const rules = this.getRules().match(this._match); this._matches.push(rules); if (rules && rules.length > 0) { for (let rule of rules) { try { if (debug) { console.debug(` Fire begin() for ${rule.toString()}`); } rule.begin(name, attrs); } catch (err) { console.error(`Begin event threw error ${err.toString()}`); throw err; } } } else { if (debug) { console.debug(` No rules found matching '${this._match}'`); } } } @autobind private onTagClose(name:string):void { const debug = this.isDebugEnabled; if (debug) { console.debug(` match='${this._match}'`); console.debug(` bodyText='${this._bodyText.toString()}'`); } const rules = this._matches.pop(); if (rules && rules.length > 0) { let bodyText = this._bodyText.toString(); for (let rule of rules) { try { if (debug) { console.debug(` Fire body() for ${rule.toString()}`); } rule.body(name, bodyText); } catch (err) { console.error(`Body event threw error ${err.toString()}`); throw err; } } } else { if (debug) { console.debug(` No rules found matching '${this._match}'`); } } this._bodyText = this._bodyTexts.pop(); if (debug) { console.debug(` Popping body text '${this._bodyText.toString()}'`); } if (rules && rules.length > 0) { let bodyText = this._bodyText.toString(); for (let i = 0; i < rules.length; i++) { const j = (rules.length - i) - 1; const rule = rules[j]; try { if (debug) { console.debug(` Fire end() for ${rule.toString()}`); } rule.end(name); } catch (err) { console.error(`End event threw error ${err.toString()}`); throw err; } } } const slash = this._match.lastIndexOf('/'); if (slash >= 0) { this._match = this._match.substring(0, slash); } else { this._match = ''; } } private continueParseElements(obj: {[key:string]: any}):void { Object.keys(obj) .forEach(key => { const value = obj[key]; const type = typeof(value); if (Array.isArray(value)) { this.parseArray(key, value); } else if (type === 'object') { this.parseObject(key, value); } }) } @autobind private getAttributes(obj: {[key:string]: any}):{[key:string]: any} { const result = {}; Object.keys(obj) .forEach(key => { const value = obj[key]; const type = typeof(value); if (type !== 'object') { result[key] = value; } }); return result; } getRules(): Rules { if (! this._rules) { this._rules = new Rules(); this._rules.digester = this; } return this._rules; } getCount():number { return this._stack.size(); } /** * Add a "factory create" rule for the specified parameters. * * @param pattern Element matching pattern * @param constructor object creation factory class * @param ignoreCreateExceptions when true any exceptions thrown during * object creation will be ignored. * @see FactoryCreateRule */ addFactoryCreate(pattern:string, constructor:Function, ignoreCreateExceptions = false):void { this.addRule(pattern, new FactoryCreateRule(constructor, ignoreCreateExceptions)); } /** * Add a "set next" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element * @see SetNextRule */ addSetNext(pattern:string, methodName:string):void { this.addRule(pattern, new SetNextRule(methodName)); } addCallMethod(pattern:string, methodName:string):void { this.addRule(pattern, new CallMethodRule(methodName)) } /** *

Register a new Rule matching the specified pattern. * This method sets the Digester property on the rule.

* * @param pattern Element matching pattern * @param rule Rule to be registered */ addRule(pattern:string, rule:Rule):void { rule.digester = this; this.getRules().add(pattern, rule); } push(object):void { if (this._stack.size() === 0) { this._root = object; } this._stack.push(object); } peek(n = 0):any { if (this._stack.isEmpty()) { return null; } if (n === 0) { return this._stack.peek(); } const index = (this._stack.size() - 1) - n; if (index < 0) { console.warn("Empty stack (returning null)"); return (null); } try { return (this._stack.get(index)); } catch (e) { console.warn("Empty stack (returning null)"); return (null); } } pop():any { if (this._stack.isEmpty()) { return null; } return this._stack.pop(); } clear():void { this._match = ''; this._matches.clear(); this._bodyTexts.clear(); this._bodyText.clear(); this._params.clear(); this._stack.clear(); this._stacksByName = {}; } }