github.com/greenpau/go-identity@v1.1.6/name.go (about) 1 // Copyright 2020 Paul Greenberg greenpau@outlook.com 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 package identity 16 17 import ( 18 "github.com/greenpau/go-identity/pkg/errors" 19 "strings" 20 ) 21 22 // Name represents human name 23 type Name struct { 24 First string `json:"first,omitempty" xml:"first,omitempty" yaml:"first,omitempty"` 25 Last string `json:"last,omitempty" xml:"last,omitempty" yaml:"last,omitempty"` 26 Middle string `json:"middle,omitempty" xml:"middle,omitempty" yaml:"middle,omitempty"` 27 Preferred string `json:"preferred,omitempty" xml:"preferred,omitempty" yaml:"preferred,omitempty"` 28 Nickname bool `json:"nickname,omitempty" xml:"nickname,omitempty" yaml:"nickname,omitempty"` 29 Confirmed bool `json:"confirmed,omitempty" xml:"confirmed,omitempty" yaml:"confirmed,omitempty"` 30 Primary bool `json:"primary,omitempty" xml:"primary,omitempty" yaml:"primary,omitempty"` 31 Legal bool `json:"legal,omitempty" xml:"legal,omitempty" yaml:"legal,omitempty"` 32 Alias bool `json:"alias,omitempty" xml:"alias,omitempty" yaml:"alias,omitempty"` 33 } 34 35 // NewName returns an instance of Name. 36 func NewName() *Name { 37 return &Name{} 38 } 39 40 // GetNameClaim returns name field of a claim. 41 func (n *Name) GetNameClaim() string { 42 return n.GetFullName() 43 } 44 45 // ToString returns string represenation of name. 46 func (n *Name) ToString() string { 47 return n.GetFullName() 48 } 49 50 // GetFullName returns the primary full name for User. 51 func (n *Name) GetFullName() string { 52 var b strings.Builder 53 if n.Last != "" { 54 b.WriteString(n.Last) 55 } 56 if n.First != "" { 57 b.WriteString(", " + n.First) 58 } 59 return b.String() 60 } 61 62 // ParseName parses name from input. 63 func ParseName(s string) (*Name, error) { 64 n := &Name{} 65 var x, y int 66 for i, sp := range []string{",", " "} { 67 x = 0 68 y = 1 69 if i == 1 { 70 x = 1 71 y = 0 72 } 73 if !strings.Contains(s, sp) { 74 continue 75 } 76 arr := strings.Split(s, sp) 77 if len(arr) == 2 { 78 n.Last = strings.TrimSpace(arr[x]) 79 n.First = strings.TrimSpace(arr[y]) 80 return n, nil 81 } 82 } 83 return nil, errors.ErrParseNameFailed.WithArgs(s) 84 }