-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.go
More file actions
224 lines (207 loc) · 6.68 KB
/
Copy pathvalidator.go
File metadata and controls
224 lines (207 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// pkg/validation/schema.go
package validation
import (
"fmt"
"github.com/biyonik/go-fluent-validator/core"
)
//
// -----------------------------------------------------------------------------
// Validation Schema (Şema Tabanlı Doğrulama)
// -----------------------------------------------------------------------------
// Bu dosya, Fluent Validation sistemine ait `ValidationSchema` yapısını içerir.
// Amaç, bir JSON/Map yapısını Type bazlı doğrulamak, dönüştürmek, koşullu rule
// çalıştırmak ve çok alanlı (cross-field) validasyonlar uygulamaktır.
//
// Bu yapı, Laravel'in Validator::make() veya Yup, Joi, Zod gibi JS şema
// doğrulayıcılarının Go karşılığıdır.
//
// Metadata:
// @author Ahmet ALTUN
// @github github.com/biyonik
// @linkedin linkedin.com/in/biyonik
// @email ahmet.altun60@gmail.com
// -----------------------------------------------------------------------------
// Alias'lar (kullanıcı dostu API için)
type ValidationResult = core.ValidationResult
type Type = core.Type
type Schema = core.Schema
// conditionalRule
// -----------------------------------------------------------------------------
// "When" fonksiyonu ile kullanılan koşullu kuralı temsil eder.
// Bir alan belirli bir değere eşitse callback çağrılır ve alt-şema uygulanır.
type conditionalRule struct {
field string // Koşul kontrol edilecek alan
expectedValue any // Beklenen değer
callback func() core.Schema // Çalıştırılacak alt şema
}
// ValidationSchema
// -----------------------------------------------------------------------------
// Bir validasyon şemasını temsil eder.
//
// Alanlar:
// - shape: Her field için Type karşılığı
// - crossValidators: Çok alanlı doğrulama fonksiyonları
// - conditionalRules: When(...) ile eklenen koşullu doğrulama kuralları
//
// Örnek:
//
// schema := validation.Make().Shape(map[string]core.Type{
// "email": validation.String().Email().Required(),
// "age": validation.Number().Min(18),
// })
//
// -----------------------------------------------------------------------------
type ValidationSchema struct {
shape map[string]core.Type
crossValidators []func(data map[string]any) error
conditionalRules []conditionalRule
}
// Make
// -----------------------------------------------------------------------------
// Yeni bir ValidationSchema oluşturur.
//
// Dönüş:
// - *ValidationSchema
//
// Örnek:
//
// schema := validation.Make()
func Make() *ValidationSchema {
return &ValidationSchema{
shape: make(map[string]core.Type),
conditionalRules: make([]conditionalRule, 0),
}
}
// Shape
// -----------------------------------------------------------------------------
// Şema için alan–type eşlemesini belirtir.
//
// Parametreler:
// - shape: map[string]core.Type (örneğin email → StringType)
//
// Dönüş:
// - core.Schema (chainable)
//
// Örnek:
//
// schema.Shape(map[string]core.Type{
// "email": validation.String().Required().Email(),
// "age": validation.Number().Min(18),
// })
func (vs *ValidationSchema) Shape(shape map[string]core.Type) core.Schema {
vs.shape = shape
return vs
}
// CrossValidate
// -----------------------------------------------------------------------------
// Çok alanlı validasyon ekler. Örneğin password == password_confirm gibi.
//
// Parametreler:
// - fn: func(data map[string]any) error
//
// Eğer hata dönerse _cross_validation alanına eklenir.
//
// Örnek:
//
// schema.CrossValidate(func(data map[string]any) error {
// if data["password"] != data["password_confirm"] {
// return errors.New("Şifreler eşleşmiyor")
// }
// return nil
// })
func (vs *ValidationSchema) CrossValidate(fn func(data map[string]any) error) core.Schema {
vs.crossValidators = append(vs.crossValidators, fn)
return vs
}
// When
// -----------------------------------------------------------------------------
// Koşullu doğrulama ekler. Belli bir alan belirlenen değere eşitse
// callback çağrılır ve alt-şema çalıştırılır.
//
// Parametreler:
// - field: Koşul kontrol edilecek alan
// - expectedValue: Bu değer eşleşirse callback tetiklenir
// - callback: Alt şema döndüren fonksiyon
//
// Örnek:
//
// schema.When("type", "corporate", func() core.Schema {
// return validation.Make().Shape(map[string]core.Type{
// "tax_number": validation.String().Required(),
// })
// })
func (vs *ValidationSchema) When(field string, expectedValue any, callback func() core.Schema) core.Schema {
vs.conditionalRules = append(vs.conditionalRules, conditionalRule{
field: field,
expectedValue: expectedValue,
callback: callback,
})
return vs
}
// Validate
// -----------------------------------------------------------------------------
// Verilen veriyi şemaya göre doğrular.
//
// Adımlar:
// 1. Her alan için Transform çalıştırılır (tip dönüşümü).
// 2. Her alan için Validate çalıştırılır.
// 3. When(...) kuralları işlenir.
// 4. CrossValidate fonksiyonları çalıştırılır.
// 5. Hata yoksa ValidData set edilir.
//
// Parametre:
// - data: map[string]any
//
// Dönüş:
// - *core.ValidationResult
func (vs *ValidationSchema) Validate(data map[string]any) *core.ValidationResult {
result := core.NewResult()
transformedData := make(map[string]any)
// 1) Transform aşaması
for field, typ := range vs.shape {
value := data[field]
transformedValue, err := typ.Transform(value)
if err != nil {
result.AddError(field, fmt.Sprintf("Dönüşüm hatası: %s", err.Error()))
continue
}
transformedData[field] = transformedValue
}
// 2) Field-level validation
for field, typ := range vs.shape {
typ.Validate(field, transformedData[field], result)
}
if len(vs.conditionalRules) > 0 {
for _, rule := range vs.conditionalRules {
val, exists := transformedData[rule.field]
if exists && val == rule.expectedValue {
subSchema := rule.callback()
subResult := subSchema.Validate(data)
if subResult.HasErrors() {
for f, msgs := range subResult.Errors() {
for _, msg := range msgs {
result.AddError(f, msg)
}
}
} else {
for k, v := range subResult.ValidData() {
transformedData[k] = v
}
}
}
}
}
// 4) Cross-field validation
// Run cross-validation regardless of field-level errors
// This ensures important cross-field checks (like password confirmation) always run
for _, fn := range vs.crossValidators {
if err := fn(transformedData); err != nil {
result.AddError("_cross_validation", err.Error())
}
}
// 5) Valid data set
if !result.HasErrors() {
result.SetValidData(transformedData)
}
return result
}