...

Source file src/github.com/xeipuuv/gojsonschema/schemaType.go

Documentation: github.com/xeipuuv/gojsonschema

     1  // Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //   http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // author           xeipuuv
    16  // author-github    https://github.com/xeipuuv
    17  // author-mail      xeipuuv@gmail.com
    18  //
    19  // repository-name  gojsonschema
    20  // repository-desc  An implementation of JSON Schema, based on IETF's draft v4 - Go language.
    21  //
    22  // description      Helper structure to handle schema types, and the combination of them.
    23  //
    24  // created          28-02-2013
    25  
    26  package gojsonschema
    27  
    28  import (
    29  	"errors"
    30  	"fmt"
    31  	"strings"
    32  )
    33  
    34  type jsonSchemaType struct {
    35  	types []string
    36  }
    37  
    38  // Is the schema typed ? that is containing at least one type
    39  // When not typed, the schema does not need any type validation
    40  func (t *jsonSchemaType) IsTyped() bool {
    41  	return len(t.types) > 0
    42  }
    43  
    44  func (t *jsonSchemaType) Add(etype string) error {
    45  
    46  	if !isStringInSlice(JSON_TYPES, etype) {
    47  		return errors.New(formatErrorDescription(Locale.NotAValidType(), ErrorDetails{"given": "/" + etype + "/", "expected": JSON_TYPES}))
    48  	}
    49  
    50  	if t.Contains(etype) {
    51  		return errors.New(formatErrorDescription(Locale.Duplicated(), ErrorDetails{"type": etype}))
    52  	}
    53  
    54  	t.types = append(t.types, etype)
    55  
    56  	return nil
    57  }
    58  
    59  func (t *jsonSchemaType) Contains(etype string) bool {
    60  
    61  	for _, v := range t.types {
    62  		if v == etype {
    63  			return true
    64  		}
    65  	}
    66  
    67  	return false
    68  }
    69  
    70  func (t *jsonSchemaType) String() string {
    71  
    72  	if len(t.types) == 0 {
    73  		return STRING_UNDEFINED // should never happen
    74  	}
    75  
    76  	// Displayed as a list [type1,type2,...]
    77  	if len(t.types) > 1 {
    78  		return fmt.Sprintf("[%s]", strings.Join(t.types, ","))
    79  	}
    80  
    81  	// Only one type: name only
    82  	return t.types[0]
    83  }
    84  

View as plain text