blob: b7afe981bce3c8c2ae092ad25eb21b61342b1a69 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001// Copyright 2015 go-swagger maintainers
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
15package validate
16
17import (
18 "reflect"
19
20 "github.com/go-openapi/spec"
21 "github.com/go-openapi/strfmt"
22)
23
24type formatValidator struct {
25 Format string
26 Path string
27 In string
28 KnownFormats strfmt.Registry
29}
30
31func (f *formatValidator) SetPath(path string) {
32 f.Path = path
33}
34
35func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool {
36 doit := func() bool {
37 if source == nil {
38 return false
39 }
40 switch source.(type) {
41 case *spec.Items:
42 it := source.(*spec.Items)
43 return kind == reflect.String && f.KnownFormats.ContainsName(it.Format)
44 case *spec.Parameter:
45 par := source.(*spec.Parameter)
46 return kind == reflect.String && f.KnownFormats.ContainsName(par.Format)
47 case *spec.Schema:
48 sch := source.(*spec.Schema)
49 return kind == reflect.String && f.KnownFormats.ContainsName(sch.Format)
50 case *spec.Header:
51 hdr := source.(*spec.Header)
52 return kind == reflect.String && f.KnownFormats.ContainsName(hdr.Format)
53 }
54 return false
55 }
56 r := doit()
57 debugLog("format validator for %q applies %t for %T (kind: %v)\n", f.Path, r, source, kind)
58 return r
59}
60
61func (f *formatValidator) Validate(val interface{}) *Result {
62 result := new(Result)
63 debugLog("validating \"%v\" against format: %s", val, f.Format)
64
65 if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil {
66 result.AddErrors(err)
67 }
68
69 if result.HasErrors() {
70 return result
71 }
72 return nil
73}