import { isArray , isParserTree , isKeyVal , isToken , isString , isUndefined } from '../utils/is' ; import { ASTParserTree } from '../parser' ; import { ParserTreeValue } from '../parser/index' ; import KeyValueCollection from '../header' ; internal export default class DataParser { param dataTree param defs public static parse ( dataTree , vars ? ) { if ( ! isParserTree ( dataTree ) ) return undefined ; if ( dataTree . type === 'scalar' ) { const val = dataTree . values [ 0 ] ; if ( isToken ( val ) ) { return val . value ; } if ( isUndefined ( val ) ) { return ; } } const container = dataTree . type === 'object' ? { } : [ ] ; if ( dataTree . values . length === 0 ) { return container ; } return _parse ( dataTree , container , vars ) ; } } const _parse = ( root , container , vars ? ) => { for ( let index = 0 ; index < root . values . length ; index += 1 ) { let value = root . values [ index ] ; if ( isParserTree ( value ) ) { if ( value . type === 'object' ) { container [ index ] = _parse ( value , { } , vars ) ; } else if ( value . type === 'array' ) { container [ index ] = _parse ( value , [ ] , vars ) ; } } else if ( isKeyVal ( value ) ) { let parsedValue = null ; if ( isParserTree ( value . value ) ) { parsedValue = _parse ( value . value , value . value . type === 'object' ? { } : [ ] , vars ) ; } else if ( isKeyVal ( value . value ) ) { console . warn ( 'Validate this case!' ) ; } else { parsedValue = _getValue ( value . value , vars ) ; } if ( isArray ( container ) ) { container . push ( { [ value . key ] : parsedValue } ) ; } else { container [ value . key ] = parsedValue ; } } else { container [ index ] = _getValue ( value , vars ) ; } } return container ; } ; function _getValue ( value , vars ? ) { if ( isToken ( value ) ) { if ( vars && isString ( value . value ) && value . value . startsWith ( '$' ) ) { const key = value . value . substr ( 1 ) ; const val = vars . get ( key ) ; return val ? val : value . value ; } return value . value ; } return ; }